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:
@@ -141,10 +141,12 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi
|
||||
by_point = {sp: pos_cart.unit_prices(db, products, sp) for sp in sales_points.IN_PERSON}
|
||||
default = pos_cart.point_for(settings["default_order_type"])
|
||||
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
|
||||
from services import price_changes
|
||||
from services import price_changes, split_bills
|
||||
return {
|
||||
# + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount
|
||||
"settings": {**settings, "price_change": price_changes.mode(db)},
|
||||
"settings": {**settings, "price_change": price_changes.mode(db),
|
||||
# 6F.6: splitting a bill by amount (the level and the most equal parts)
|
||||
"split_amount": split_bills.level(db), "split_max_parts": split_bills.max_parts(db)},
|
||||
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
|
||||
for c in cats],
|
||||
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON})
|
||||
@@ -180,14 +182,25 @@ class Payment(BaseModel):
|
||||
lines: Optional[List[int]] = None # indexes into `lines`; None = all of them
|
||||
|
||||
|
||||
class SaleSplit(BaseModel):
|
||||
"""A quick sale split by amount (6F.6, Q-4): the parts and how each is paid, all now."""
|
||||
mode: Literal["equal", "custom"] = "equal"
|
||||
parts: int = Field(default=2, ge=2, le=50)
|
||||
first_amount: Optional[float] = Field(default=None, gt=0, le=1000000)
|
||||
methods: List[Literal["cash", "card"]] = Field(min_length=2, max_length=50) # one per part
|
||||
|
||||
|
||||
class SaleBody(BaseModel):
|
||||
order_type: Literal["takeaway", "here"] = "takeaway"
|
||||
lines: List[dict] = Field(min_length=1, max_length=200)
|
||||
payments: List[Payment] = Field(min_length=1, max_length=2)
|
||||
payments: List[Payment] = Field(default_factory=list, max_length=2) # without `split`: at least one
|
||||
split: Optional[SaleSplit] = None
|
||||
cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
|
||||
|
||||
|
||||
def _payment_groups(body: SaleBody, n: int) -> list:
|
||||
if not body.payments:
|
||||
raise XeniaError("pos.payment_invalid", reason="lines")
|
||||
if len(body.payments) == 1 and body.payments[0].lines is None:
|
||||
return [(body.payments[0].method, list(range(n)))]
|
||||
seen = [i for pay in body.payments for i in (pay.lines or [])]
|
||||
@@ -211,12 +224,14 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
|
||||
_require_shift(db, user)
|
||||
orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key
|
||||
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
|
||||
groups = _payment_groups(body, len(lines))
|
||||
groups = _payment_groups(body, len(lines)) if body.split is None else []
|
||||
approved_by = _check_discounts(request, db, user, lines)
|
||||
_check_fiscal(db, {line.product for line in lines})
|
||||
priced = pos_cart.price_lines(db, lines, body.order_type)
|
||||
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
|
||||
totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)]
|
||||
if body.split is not None:
|
||||
return _split_sale(body, request, db, user, lines, adjs, approved_by, totals)
|
||||
cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2)
|
||||
_check_cash(body.cash_given, cash_due)
|
||||
|
||||
@@ -239,6 +254,53 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
|
||||
}
|
||||
|
||||
|
||||
def _split_sale(body, request, db, user, lines, adjs, approved_by, totals):
|
||||
"""A quick sale split by amount (6F.6, Q-4): the order and its lines as any quick sale, then
|
||||
the lines settled into a split bill and each part paid now by its own method (one payment per
|
||||
method). The fiscal receipt is the lines themselves, issued with the last part (Q-3)."""
|
||||
from models.order import OrderItem
|
||||
from routers import orders as orders_api
|
||||
from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest
|
||||
from services import split_bills
|
||||
sp = body.split
|
||||
orders_api._need(request, db, user, "ordering.payments.split_amount", target="pos sale")
|
||||
if len(sp.methods) != sp.parts:
|
||||
raise XeniaError("pos.payment_invalid", reason="lines")
|
||||
if not split_bills.allowed(split_bills.level(db), sp.mode, sp.parts, split_bills.max_parts(db)):
|
||||
raise XeniaError("split.not_allowed")
|
||||
total = round(sum(totals), 2)
|
||||
if total < 0.01 * sp.parts:
|
||||
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
|
||||
amounts = split_bills.amounts(total, sp.mode, sp.parts, sp.first_amount)
|
||||
cash_due = round(sum(a for a, m in zip(amounts, sp.methods) if m == "cash"), 2)
|
||||
_check_cash(body.cash_given, cash_due)
|
||||
|
||||
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
|
||||
items = db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()
|
||||
bill = split_bills.create(db, order, items, mode=sp.mode, parts=sp.parts, first=sp.first_amount, user=user)
|
||||
orders_api._audit(db, order.id, "SPLIT_CREATED", waiter_id=user.id, item_ids=[i.id for i in items], amount=bill.total,
|
||||
note=f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts))
|
||||
db.commit()
|
||||
parts = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id, OrderItem.status == "active").order_by(OrderItem.id).all()
|
||||
paid, fiscal = [], None
|
||||
for method in ("cash", "card"):
|
||||
ids = [p.id for p, m in zip(parts, sp.methods) if m == method]
|
||||
if not ids:
|
||||
continue
|
||||
res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=ids, payment_method=method), request, db, user)
|
||||
paid.append({"method": method, "amount": round(sum(a for a, m in zip(amounts, sp.methods) if m == method), 2),
|
||||
"item_ids": res["paid_item_ids"]})
|
||||
fiscal = res.get("fiscal") or fiscal
|
||||
drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none"
|
||||
change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None
|
||||
return {
|
||||
"order_id": order.id, "total": total, "payments": paid, "split": {"id": bill.id, "amounts": amounts, "methods": sp.methods},
|
||||
"cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal,
|
||||
"print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []),
|
||||
}
|
||||
|
||||
|
||||
# ── shared checks (3.3b, 3.3c) ─────────────────────────────────────────────────
|
||||
|
||||
def _require_shift(db, user):
|
||||
@@ -458,7 +520,8 @@ def pos_order_pay(order_id: int, body: OrderPayBody, request: Request, db: Sessi
|
||||
items = {i.id: i for i in db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.id.in_(wanted)).all()}
|
||||
if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()):
|
||||
raise XeniaError("pos.items_changed")
|
||||
_check_fiscal(db, {i.product for i in items.values()})
|
||||
from services.split_bills import is_part
|
||||
_check_fiscal(db, {i.product for i in items.values() if not is_part(i)}) # 6F.6: the settled lines were checked
|
||||
amount = {pay.method: round(sum(_item_total(items[i]) for i in pay.item_ids), 2) for pay in body.payments}
|
||||
cash_due = amount.get("cash", 0.0)
|
||||
_check_cash(body.cash_given, cash_due)
|
||||
|
||||
Reference in New Issue
Block a user