feat(backend,waiter,terminal,manager): split the bill by amount
Owner 2026-11-23 (plan 6F.6). Venue setting payments.split_amount (off | two_equal | two_custom |
multiple_equal, each level with the ones before; default off) and payments.split_max_parts (10);
key ordering.payments.split_amount (everyone who takes payments; Alembic 0050 grants it).
POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status 'split': sold, no shift,
no payment method) and adds part lines (system product split_part, "Split bill 1/3", printed and
served; equal parts with the remainder on the last, or two parts with part 1 typed). Parts are paid
like any line (cash, card, tab). POST .../split-bills/{bill}/undo while no part is paid or tabbed.
Counting (services/sales.py): settled lines are the sales, parts never (a refunded part comes off
the settled lines by share); drawers and payment methods count the parts. Older reports use
split_bills.sold_filter / counts_as_sale. Locks: parts can't be cancelled, moved, combined or
re-priced; settled lines are no longer active; closing or cancelling an order with unpaid parts is
refused. Fiscal: one receipt with the settled lines when the last part is paid, with each method's
amount (txt driver: CD per card amount, then CR for cash).
Waiter: Pay -> "Split the amount" (pre-filled from the customers), the split bill above the lines
with Undo. Counter: "By amount" in the payment (quick sale split and paid at once, Q-4; a table's
lines split then paid). Manager: the pay dialog splits, the order shows its split bills, Settings ->
Operation card. Shared rules in @xenia/ordering/split.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+109
-11
@@ -61,6 +61,7 @@ from core.access.deps import require
|
||||
from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket
|
||||
from models.settings import PosSettings
|
||||
from services.ws_bus import broadcast_sync
|
||||
from services import split_bills
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -370,6 +371,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"deal_id": i.deal_id, "linked_item_id": i.linked_item_id,
|
||||
"split_from_id": i.split_from_id, # 6F.4: the line it was cut from
|
||||
"cancel_reason": i.cancel_reason,
|
||||
"split_bill_id": i.split_bill_id, # 6F.6: settled into a split bill (status split) or one of its parts
|
||||
}
|
||||
|
||||
def fmt_log(l):
|
||||
@@ -422,6 +424,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"requested_for": _iso(order.requested_for),
|
||||
"online_delivery_area": order.online_delivery_area,
|
||||
"items": [fmt_item(i) for i in order.items],
|
||||
"split_bills": [split_bills.bill_out(b, order.items) for b in split_bills.live_bills(db, order.id)], # 6F.6
|
||||
"waiters": [{"waiter_id": w.waiter_id} for w in order.waiters],
|
||||
"audit_logs": [fmt_log(l) for l in order.audit_logs],
|
||||
}
|
||||
@@ -923,6 +926,9 @@ def cancel_item(
|
||||
raise XeniaError("order.item_not_found")
|
||||
if item.status == "paid":
|
||||
raise XeniaError("order.item_paid")
|
||||
if item.status not in ("active", "ready"):
|
||||
raise XeniaError("order.item_not_active")
|
||||
split_bills.refuse_parts([item]) # 6F.6: undo the split instead
|
||||
|
||||
now = utcnow()
|
||||
item.status = "cancelled"
|
||||
@@ -973,10 +979,13 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
|
||||
OrderItem.status.in_(["active", "ready"]), # ready items are also payable
|
||||
).all()
|
||||
|
||||
# Fiscal validation: if enabled, all items must have VAT group assigned before payment
|
||||
# Fiscal validation: if enabled, all items must have VAT group assigned before payment.
|
||||
# A split bill's parts (6F.6) aren't on a receipt themselves: the settled lines are, once the
|
||||
# last part is paid (checked when the bill was made).
|
||||
fiscal_on = is_fiscal_enabled(db)
|
||||
if fiscal_on and items:
|
||||
missing = validate_items_for_fiscal(items, db)
|
||||
own = [i for i in items if not split_bills.is_part(i)]
|
||||
if fiscal_on and own:
|
||||
missing = validate_items_for_fiscal(own, db)
|
||||
if missing:
|
||||
names = ", ".join(missing)
|
||||
raise XeniaError("pos.fiscal_vat_missing", names=names)
|
||||
@@ -1020,7 +1029,12 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
|
||||
order.closed_by = user.id
|
||||
auto_closed = True
|
||||
|
||||
if fiscal_on and items:
|
||||
bills_due = split_bills.receipts_due(db, items) # 6F.6: the last part of a split bill
|
||||
for due in bills_due:
|
||||
_audit(db, order_id, "SPLIT_SETTLED", waiter_id=user.id, item_ids=[i.id for i in due["lines"]],
|
||||
amount=due["bill"].total, note=" + ".join(f"{p['method']} {p['amount']:.2f}" for p in due["payments"]))
|
||||
fiscal_sent = fiscal_on and (bool(own) or bool(bills_due))
|
||||
if fiscal_sent:
|
||||
order.fiscal_status = "pending"
|
||||
|
||||
db.commit()
|
||||
@@ -1028,18 +1042,25 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
|
||||
if auto_closed:
|
||||
broadcast_sync("order_closed", {"order_id": order_id, "table_id": order.table_id, "auto_closed": True})
|
||||
|
||||
if fiscal_on and items:
|
||||
if fiscal_on and own:
|
||||
from database import SessionLocal
|
||||
fiscal_items = build_fiscal_items(items)
|
||||
send_fiscal_receipt_background(fiscal_items, effective_method, total_paid, db,
|
||||
fiscal_items = build_fiscal_items(own)
|
||||
own_total = sum((i.unit_price + (i.price_adjustment or 0.0)) * i.quantity for i in own)
|
||||
send_fiscal_receipt_background(fiscal_items, effective_method, own_total, db,
|
||||
order_id=order_id, db_factory=SessionLocal,
|
||||
timeout_seconds=60)
|
||||
if fiscal_on:
|
||||
from database import SessionLocal
|
||||
for due in bills_due: # the settled lines as if paid normally, with each method's amount (Q-3)
|
||||
send_fiscal_receipt_background(build_fiscal_items(due["lines"]), effective_method, due["bill"].total, db,
|
||||
order_id=order_id, db_factory=SessionLocal, timeout_seconds=60,
|
||||
payments=due["payments"])
|
||||
|
||||
return {
|
||||
"status": order.status,
|
||||
"paid_item_ids": paid_ids,
|
||||
"auto_closed": auto_closed,
|
||||
"fiscal": "pending" if fiscal_on and items else None,
|
||||
"fiscal": "pending" if fiscal_sent else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -1100,6 +1121,8 @@ def close_order(order_id: int, request: Request, db: Session = Depends(get_db),
|
||||
raise XeniaError("order.not_yours")
|
||||
if order.status not in ("paid", "open", "partially_paid"):
|
||||
raise XeniaError("order.cannot_close", status=order.status)
|
||||
if split_bills.has_unpaid_parts(db, order_id): # 6F.6: never written off: the settled lines were sold
|
||||
raise XeniaError("split.parts_unpaid")
|
||||
|
||||
now = utcnow()
|
||||
|
||||
@@ -1256,6 +1279,8 @@ def cancel_order(
|
||||
if not is_manager and not _waiter_can_cancel(user, db):
|
||||
# a manager may approve this one cancellation with their PIN (D-10)
|
||||
approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
|
||||
if split_bills.has_unpaid_parts(db, order_id): # 6F.6: undo the split first
|
||||
raise XeniaError("split.parts_unpaid")
|
||||
|
||||
now = utcnow()
|
||||
|
||||
@@ -1319,11 +1344,12 @@ def cancel_items_bulk(
|
||||
OrderItem.order_id == order_id,
|
||||
).all()
|
||||
|
||||
split_bills.refuse_parts(items) # 6F.6: undo the split instead
|
||||
now = utcnow()
|
||||
cancelled_ids = []
|
||||
skipped_paid = []
|
||||
for item in items:
|
||||
if item.status == "paid":
|
||||
if item.status not in ("active", "ready"): # paid, on a tab, settled by a split bill (6F.6)
|
||||
skipped_paid.append(item.id)
|
||||
continue
|
||||
item.status = "cancelled"
|
||||
@@ -1436,6 +1462,8 @@ def print_order(
|
||||
if item.status == "cancelled":
|
||||
continue
|
||||
product_name = item.product.name if item.product else f"#{item.product_id}"
|
||||
if item.split_bill_id is not None and item.status != "split":
|
||||
product_name = item.product_name # 6F.6: "Split bill 1/3"
|
||||
adj = getattr(item, 'price_adjustment', 0.0) or 0.0
|
||||
effective_price = item.unit_price + adj
|
||||
items_data.append({
|
||||
@@ -1447,7 +1475,7 @@ def print_order(
|
||||
"status": item.status,
|
||||
})
|
||||
|
||||
grand_total = sum(i["total"] for i in items_data)
|
||||
grand_total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them
|
||||
|
||||
receipt = {
|
||||
"order_id": order.id,
|
||||
@@ -1552,6 +1580,8 @@ def merge_order(
|
||||
for item in source.items:
|
||||
item.order_id = target.id
|
||||
moved_item_ids.append(item.id)
|
||||
from models.order import SplitBill # 6F.6: a split bill goes with its lines
|
||||
db.query(SplitBill).filter(SplitBill.order_id == source.id).update({SplitBill.order_id: target.id}, synchronize_session=False)
|
||||
|
||||
# Copy source waiters to target (no duplicates)
|
||||
existing_waiter_ids = {w.waiter_id for w in target.waiters}
|
||||
@@ -1589,6 +1619,68 @@ def merge_order(
|
||||
return target
|
||||
|
||||
|
||||
# ─── Split the bill by amount (6F.6, services/split_bills.py) ─────────────────
|
||||
|
||||
class SplitBillRequest(BaseModel):
|
||||
item_ids: List[int] = Field(min_length=1, max_length=500)
|
||||
mode: str = "equal" # equal | custom (two parts)
|
||||
parts: int = Field(default=2, ge=2, le=50)
|
||||
first_amount: Optional[float] = Field(default=None, gt=0, le=1000000) # custom: part 1, part 2 is the rest
|
||||
|
||||
|
||||
@router.post("/{order_id}/split-bills")
|
||||
def create_split_bill(order_id: int, body: SplitBillRequest, request: Request, db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user)):
|
||||
"""Settle the chosen unpaid lines into a split bill and cut it into parts paid on their own
|
||||
(equal parts, the remainder on the last; or two parts, part 1 typed). The venue's
|
||||
payments.split_amount decides which splits exist; the key ordering.payments.split_amount (a
|
||||
manager may approve it once, D-10) who may. The parts are paid with POST /pay like any line."""
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
if order.status not in ("open", "partially_paid"):
|
||||
raise XeniaError("order.not_open")
|
||||
ids = sorted(set(body.item_ids))
|
||||
items = db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.id.in_(ids)).order_by(OrderItem.id).all()
|
||||
if len(items) != len(ids):
|
||||
raise XeniaError("split.lines_changed")
|
||||
bill = split_bills.create(db, order, items, mode=body.mode, parts=body.parts, first=body.first_amount, user=user)
|
||||
amounts = json.loads(bill.amounts)
|
||||
note = f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts)
|
||||
approved = _approval_note(approval)
|
||||
_audit(db, order_id, "SPLIT_CREATED", waiter_id=user.id, item_ids=ids, amount=bill.total,
|
||||
note=f"{note}; {approved}" if approved else note)
|
||||
db.commit()
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_created"})
|
||||
db.refresh(order)
|
||||
return split_bills.bill_out(bill, order.items)
|
||||
|
||||
|
||||
@router.post("/{order_id}/split-bills/{bill_id}/undo")
|
||||
def undo_split_bill(order_id: int, bill_id: int, request: Request, db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user)):
|
||||
"""Undo a split while none of its parts is paid or on a tab (Q-2): the parts are cancelled
|
||||
("split undone"), the lines are unpaid again. Same key as splitting."""
|
||||
from models.order import SplitBill
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}")
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
bill = db.get(SplitBill, bill_id)
|
||||
if bill is None:
|
||||
raise XeniaError("split.not_found")
|
||||
back = split_bills.undo(db, order, bill, user)
|
||||
_audit(db, order_id, "SPLIT_UNDONE", waiter_id=user.id, item_ids=back, amount=bill.total, note=_approval_note(approval))
|
||||
db.commit()
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_undone"})
|
||||
return {"item_ids": back}
|
||||
|
||||
|
||||
# ─── Split a stacked item into two rows ──────────────────────────────────────
|
||||
|
||||
@router.post("/{order_id}/items/{item_id}/split", response_model=List[OrderItemOut])
|
||||
@@ -1787,6 +1879,7 @@ def adjust_item_price(
|
||||
raise XeniaError("order.item_not_found")
|
||||
if item.status != "active":
|
||||
raise XeniaError("order.item_not_active")
|
||||
split_bills.refuse_parts([item]) # 6F.6
|
||||
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not _can_access_order(order, user, db):
|
||||
@@ -1873,6 +1966,7 @@ def apply_waiter_discount(
|
||||
).all()
|
||||
if not items:
|
||||
raise XeniaError("order.no_active_items", status=404)
|
||||
split_bills.refuse_parts(items) # 6F.6
|
||||
|
||||
item_unit_prices = {i.id: i.unit_price + i.price_adjustment for i in items}
|
||||
|
||||
@@ -2100,6 +2194,7 @@ def move_items(
|
||||
).all()
|
||||
if not items:
|
||||
raise XeniaError("order.no_active_items")
|
||||
split_bills.refuse_parts(items) # 6F.6: a part stays with its bill
|
||||
|
||||
from services import moves # 6F.4
|
||||
moves.record(db, kind="items_moved", source=source, target=target, items=items, user_id=user.id)
|
||||
@@ -2166,6 +2261,8 @@ def print_synopsis(
|
||||
if item.status == "cancelled":
|
||||
continue
|
||||
product_name = item.product.name if item.product else f"#{item.product_id}"
|
||||
if item.split_bill_id is not None and item.status != "split":
|
||||
product_name = item.product_name # 6F.6: "Split bill 1/3"
|
||||
adj = getattr(item, 'price_adjustment', 0.0) or 0.0
|
||||
effective_price = item.unit_price + adj
|
||||
items_data.append({
|
||||
@@ -2177,7 +2274,7 @@ def print_synopsis(
|
||||
"status": item.status,
|
||||
})
|
||||
|
||||
total = sum(i["total"] for i in items_data)
|
||||
total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them
|
||||
paid_total = sum(i["total"] for i in items_data if i["status"] == "paid")
|
||||
|
||||
synopsis = {
|
||||
@@ -2290,6 +2387,7 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
|
||||
raise XeniaError("order.items_not_combinable", reason="not_found")
|
||||
if any(i.status != "active" for i in items):
|
||||
raise XeniaError("order.items_not_combinable", reason="not_unpaid")
|
||||
split_bills.refuse_parts(items) # 6F.6
|
||||
if any(i.deal_id or i.linked_item_id for i in items) or \
|
||||
db.query(OrderItem).filter(OrderItem.linked_item_id.in_(ids)).first() is not None:
|
||||
raise XeniaError("order.items_not_combinable", reason="deal")
|
||||
|
||||
Reference in New Issue
Block a user