Spaces:
Running
Running
Update main.py
Browse files1588 unmodified lines15891590159115921593159415951582 unmodified lines3178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932109 unmodified lines322032213222322332243225322632273228322911 unmodified lines324132423243324432453246324721 unmodified lines326932703271327232733274327532763277327832793280328132821 unmodified line32843285328632873288328932901 unmodified line329232933294329532963297329811 unmodified lines33103311331233133314331533169 unmodified lines33263327332833293330333133321588 unmodified lines"""Return the next sequential auto‑batch number (e.g., autogen005)."""client = get_supabase()try:# Correct RPC call: client.rpc('function_name', {'param': value})result = client.rpc('get_next_auto_batch_number', {}).execute()next_num = result.data # integerreturn f"autogen{next_num:03d}"1582 unmodified linesawait rate_limit(get_client_ip(request), user_data[1])_, org_id, _ = user_dataclient = get_supabase()data = item.dict()data["org_id"] = org_iddata["created_at"] = datetime.now().isoformat()data["updated_at"] = datetime.now().isoformat()# ---- AUTO‑BATCH GENERATION ----expiry_date = data.get("expiry_date")batch_number = data.get("batch_number")lot_number = data.get("lot_number")# Only generate if expiry exists and batch not providedif expiry_date and not batch_number:batch_number = await get_next_auto_batch_number()data["batch_number"] = batch_numberif not lot_number:lot_number = "LEGACY-IMPORT"data["lot_number"] = lot_number# ------------------------------# Insert inventory recordinv_result = client.table("inventory").insert(data).execute()if not inv_result.data:raise HTTPException(status_code=500, detail="Failed to create inventory item")new_inv = inv_result.data[0]# ---- If a batch was generated (or provided), insert a batch record ----if expiry_date and data.get("batch_number"):batch_data = {"inventory_id": new_inv["id"],9 unmodified lines}client.table("inventory_batches").insert(batch_data).execute()logger.info(f"Auto‑batch {data['batch_number']} created for inventory {new_inv['id']}")# Location stock (existing logic, but now we also need to link batch?)# The current location_stocks table expects inventory_id; we also want batch_id.# Optionally, add batch_id to location_stocks – but for now we keep as is.try:main_location = client.table("locations") \.select("id") \11 unmodified lines}).execute()except Exception as loc_err:logger.warning(f"Failed to create location stock: {loc_err}")return new_inv@app.put("/inventory/{item_id}")async def update_inventory(21 unmodified linesupdate_data = {k: v for k, v in item.dict().items() if v is not None}update_data["updated_at"] = datetime.now().isoformat()# 3. Handle batch insertion/updatenew_expiry = update_data.get("expiry_date")new_batch = update_data.get("batch_number")new_lot = update_data.get("lot_number")new_qty = update_data.get("current_qty", existing.data.get("current_qty", 0))if new_expiry:# Generate batch number if not providedif not new_batch:new_batch = await get_next_auto_batch_number()update_data["batch_number"] = new_batch1 unmodified linenew_lot = "LEGACY-IMPORT"update_data["lot_number"] = new_lot# Check if a batch with this number already exists for this inventorytry:batch_query = client.table("inventory_batches") \.select("id, quantity, expiry_date") \1 unmodified line.eq("batch_number", new_batch) \.maybe_single() \.execute()existing_batch = batch_query.data if batch_query else Noneexcept Exception as e:logger.error(f"Error querying existing batch: {e}")11 unmodified lines.execute()logger.info(f"Updated batch {new_batch} for inventory {item_id}")else:# Insert a new batchbatch_data = {"inventory_id": item_id,"batch_number": new_batch,9 unmodified linesclient.table("inventory_batches").insert(batch_data).execute()logger.info(f"Inserted new batch {new_batch} for inventory {item_id}")# 4. Update the main inventory recordresult = client.table("inventory").update(update_data) \.eq("id", item_id) \.eq("org_id", org_id) \1588 unmodified lines15891590159115921593159415951582 unmodified lines31783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732089 unmodified lines3218321932203221322232233224322511 unmodified lines323732383239324032413242324321 unmodified lines32653266326732683269327032713272327332743275327632771 unmodified line32793280328132823283328432851 unmodified line32873288328932903291329211 unmodified lines33043305330633073308330933109 unmodified lines33203321332233233324332533261588 unmodified lines"""Return the next sequential auto‑batch number (e.g., autogen005)."""client = get_supabase()try:# Correct RPC call: client.rpc('function_name', {})result = client.rpc('get_next_auto_batch_number', {}).execute()next_num = result.data # integerreturn f"autogen{next_num:03d}"1582 unmodified linesawait rate_limit(get_client_ip(request), user_data[1])_, org_id, _ = user_dataclient = get_supabase()data = item.dict()data["org_id"] = org_iddata["created_at"] = datetime.now().isoformat()data["updated_at"] = datetime.now().isoformat()# ---- Auto‑batch generation ----expiry_date = data.get("expiry_date")batch_number = data.get("batch_number")lot_number = data.get("lot_number")if expiry_date and not batch_number:batch_number = await get_next_auto_batch_number()data["batch_number"] = batch_numberif not lot_number:lot_number = "LEGACY-IMPORT"data["lot_number"] = lot_number# Insert inventoryinv_result = client.table("inventory").insert(data).execute()if not inv_result.data:raise HTTPException(status_code=500, detail="Failed to create inventory item")new_inv = inv_result.data[0]# ---- Insert batch record if expiry exists ----if expiry_date and data.get("batch_number"):batch_data = {"inventory_id": new_inv["id"],9 unmodified lines}client.table("inventory_batches").insert(batch_data).execute()logger.info(f"Auto‑batch {data['batch_number']} created for inventory {new_inv['id']}")# (Optional) Location stocktry:main_location = client.table("locations") \.select("id") \11 unmodified lines}).execute()except Exception as loc_err:logger.warning(f"Failed to create location stock: {loc_err}")return new_inv@app.put("/inventory/{item_id}")async def update_inventory(21 unmodified linesupdate_data = {k: v for k, v in item.dict().items() if v is not None}update_data["updated_at"] = datetime.now().isoformat()# 3. Handle batch logicnew_expiry = update_data.get("expiry_date")new_batch = update_data.get("batch_number")new_lot = update_data.get("lot_number")new_qty = update_data.get("current_qty", existing.data.get("current_qty", 0))if new_expiry:if not new_batch:new_batch = await get_next_auto_batch_number()update_data["batch_number"] = new_batch1 unmodified linenew_lot = "LEGACY-IMPORT"update_data["lot_number"] = new_lot# Check for existing batch (with safe handling)try:batch_query = client.table("inventory_batches") \.select("id, quantity, expiry_date") \1 unmodified line.eq("batch_number", new_batch) \.maybe_single() \.execute()existing_batch = batch_query.data if batch_query else Noneexcept Exception as e:logger.error(f"Error querying existing batch: {e}")11 unmodified lines.execute()logger.info(f"Updated batch {new_batch} for inventory {item_id}")else:# Insert new batchbatch_data = {"inventory_id": item_id,"batch_number": new_batch,9 unmodified linesclient.table("inventory_batches").insert(batch_data).execute()logger.info(f"Inserted new batch {new_batch} for inventory {item_id}")# 4. Update inventory recordresult = client.table("inventory").update(update_data) \.eq("id", item_id) \.eq("org_id", org_id) \
main.py+16-22