Spaces:
Running
Running
Update main.py
Browse files1588 unmodified lines158915901591159215921593159415951582 unmodified lines317831793180318131813182318331843185318631873186318731883189319031913192319131923193319431953196319731993200320131983199320032013202320332063207320432053206320732089 unmodified lines32183219322032233224322532263221322232233224322511 unmodified lines3237323832393244324032413242324321 unmodified lines3265326632673272326832693270327132723273327432793275327632771 unmodified line327932803281328732823283328432851 unmodified line328732883289329532903291329211 unmodified lines330433053306331333073308330933109 unmodified lines332033213322332933233324332533261588 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}) # Correct RPC call: client.rpc('function_name', {}) result = client.rpc('get_next_auto_batch_number', {}).execute() next_num = result.data # integer return f"autogen{next_num:03d}"1582 unmodified lines await rate_limit(get_client_ip(request), user_data[1]) _, org_id, _ = user_data client = get_supabase()
data = item.dict() data["org_id"] = org_id data["created_at"] = datetime.now().isoformat() data["updated_at"] = datetime.now().isoformat() # ---- AUTO‑BATCH GENERATION ----
# ---- 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 provided
if expiry_date and not batch_number: batch_number = await get_next_auto_batch_number() data["batch_number"] = batch_number if not lot_number: lot_number = "LEGACY-IMPORT" data["lot_number"] = lot_number # ------------------------------ # Insert inventory record
# Insert inventory inv_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 ----
# ---- 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']}") # 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.
# (Optional) Location stock 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 lines update_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/update # 3. Handle batch logic new_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 provided if not new_batch: new_batch = await get_next_auto_batch_number() update_data["batch_number"] = new_batch1 unmodified line new_lot = "LEGACY-IMPORT" update_data["lot_number"] = new_lot
# Check if a batch with this number already exists for this inventory # 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 None except 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 batch # Insert new batch batch_data = { "inventory_id": item_id, "batch_number": new_batch,9 unmodified lines client.table("inventory_batches").insert(batch_data).execute() logger.info(f"Inserted new batch {new_batch} for inventory {item_id}")
# 4. Update the main inventory record # 4. Update inventory record result = client.table("inventory").update(update_data) \ .eq("id", item_id) \ .eq("org_id", org_id) \main.py+16-22