AhmadYarAI commited on
Commit
c370c93
·
1 Parent(s): 3220e75

fix: the Unique id issue

Browse files
Files changed (1) hide show
  1. api/invoices.py +17 -12
api/invoices.py CHANGED
@@ -35,8 +35,7 @@ def create_invoice(data: InvoiceCreate, db: Session = Depends(get_db)):
35
  # 1. Calculate total
36
  total = sum(item.quantity * item.price_per_unit for item in data.items)
37
 
38
- # 2. Create the invoice object
39
- # Notice: NO db.flush() here!
40
  new_invoice = Invoice(
41
  date=data.date or datetime.utcnow(),
42
  doctor_name=data.doctor_name,
@@ -47,17 +46,19 @@ def create_invoice(data: InvoiceCreate, db: Session = Depends(get_db)):
47
  received_amount=data.received_amount,
48
  remaining_balance=total - data.received_amount,
49
  notes=data.notes,
50
- invoice_no="PENDING" # Temporary placeholder
51
  )
52
 
53
  db.add(new_invoice)
54
- db.commit()
55
- db.refresh(new_invoice)
56
-
57
- # 3. Update the string now that we officially have the ID
58
- new_invoice.invoice_no = f"INV-{new_invoice.id:04d}"
59
 
60
- # 4. Add the items using the confirmed ID
 
 
 
 
 
 
 
61
  for item in data.items:
62
  db.add(InvoiceItem(
63
  invoice_id=new_invoice.id,
@@ -67,9 +68,13 @@ def create_invoice(data: InvoiceCreate, db: Session = Depends(get_db)):
67
  total_price=item.quantity * item.price_per_unit
68
  ))
69
 
70
- db.commit() # Save everything finally
71
- return {"status": "success", "invoice_no": new_invoice.invoice_no}
72
-
 
 
 
 
73
 
74
  @router.get("/{invoice_id}")
75
  def get_invoice(invoice_id: int, db: Session = Depends(get_db)):
 
35
  # 1. Calculate total
36
  total = sum(item.quantity * item.price_per_unit for item in data.items)
37
 
38
+ # 2. Create the invoice object
 
39
  new_invoice = Invoice(
40
  date=data.date or datetime.utcnow(),
41
  doctor_name=data.doctor_name,
 
46
  received_amount=data.received_amount,
47
  remaining_balance=total - data.received_amount,
48
  notes=data.notes,
49
+ invoice_no="TEMP" # This will be overwritten before the commit
50
  )
51
 
52
  db.add(new_invoice)
 
 
 
 
 
53
 
54
+ # --- THE SECRET SAUCE ---
55
+ db.flush() # This asks the DB for an ID without committing the record
56
+
57
+ # 3. Now we have new_invoice.id, so we set the real invoice_no
58
+ new_invoice.invoice_no = f"INV-{new_invoice.id:04d}"
59
+ # ------------------------
60
+
61
+ # 4. Add the items
62
  for item in data.items:
63
  db.add(InvoiceItem(
64
  invoice_id=new_invoice.id,
 
68
  total_price=item.quantity * item.price_per_unit
69
  ))
70
 
71
+ try:
72
+ db.commit() # Now everything is saved in ONE transaction
73
+ db.refresh(new_invoice)
74
+ return {"status": "success", "invoice_no": new_invoice.invoice_no}
75
+ except Exception as e:
76
+ db.rollback()
77
+ raise HTTPException(status_code=400, detail=f"Database error: {str(e)}")
78
 
79
  @router.get("/{invoice_id}")
80
  def get_invoice(invoice_id: int, db: Session = Depends(get_db)):