Update backend/crud/bill_crud.py
Browse files- backend/crud/bill_crud.py +16 -12
backend/crud/bill_crud.py
CHANGED
|
@@ -213,27 +213,31 @@ def get_all_bills(db: Session):
|
|
| 213 |
"""Get all bills"""
|
| 214 |
return db.query(Bill).order_by(Bill.created_date.desc()).all()
|
| 215 |
def delete_bill(db: Session, bill_id: int):
|
| 216 |
-
# Fetch the bill
|
| 217 |
bill = db.query(models.Bill).filter(models.Bill.id == bill_id).first()
|
| 218 |
|
| 219 |
if not bill:
|
| 220 |
return "bill_not_found"
|
| 221 |
|
| 222 |
-
|
| 223 |
-
db.query(models.Sale).filter(models.Sale.bill_id == bill_id).delete()
|
| 224 |
-
|
| 225 |
-
# --- 2. Restore stock and delete the line items ---
|
| 226 |
-
if hasattr(bill, 'items'):
|
| 227 |
for item in bill.items:
|
| 228 |
-
# Restore the stock
|
| 229 |
product = db.query(models.Product).filter(models.Product.id == item.product_id).first()
|
| 230 |
if product:
|
| 231 |
product.quantity_left += item.quantity
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
db.delete(bill)
|
| 238 |
db.commit()
|
| 239 |
|
|
|
|
| 213 |
"""Get all bills"""
|
| 214 |
return db.query(Bill).order_by(Bill.created_date.desc()).all()
|
| 215 |
def delete_bill(db: Session, bill_id: int):
|
|
|
|
| 216 |
bill = db.query(models.Bill).filter(models.Bill.id == bill_id).first()
|
| 217 |
|
| 218 |
if not bill:
|
| 219 |
return "bill_not_found"
|
| 220 |
|
| 221 |
+
if bill.status == "finalized" and hasattr(bill, 'items'):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
for item in bill.items:
|
|
|
|
| 223 |
product = db.query(models.Product).filter(models.Product.id == item.product_id).first()
|
| 224 |
if product:
|
| 225 |
product.quantity_left += item.quantity
|
| 226 |
+
db.commit()
|
| 227 |
+
|
| 228 |
+
sales = db.query(models.Sale.id).filter(models.Sale.bill_id == bill_id).all()
|
| 229 |
+
sale_ids = [sale.id for sale in sales]
|
| 230 |
+
|
| 231 |
+
if sale_ids:
|
| 232 |
+
|
| 233 |
+
db.query(models.Return).filter(models.Return.sale_id.in_(sale_ids)).delete(synchronize_session=False)
|
| 234 |
+
|
| 235 |
+
db.query(models.Sale).filter(models.Sale.bill_id == bill_id).delete(synchronize_session=False)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
db.query(models.BillItem).filter(models.BillItem.bill_id == bill_id).delete(synchronize_session=False)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
db.delete(bill)
|
| 242 |
db.commit()
|
| 243 |
|