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:
@@ -0,0 +1,228 @@
|
||||
"""Split a bill by amount (owner 2026-11-23, plan 6F.6). One rule for every app:
|
||||
|
||||
- The chosen unpaid lines are **settled** at once into a split bill: status `split` (sold, settled by
|
||||
the bill; `paid_at` / `paid_by` say when and who split, no shift, no payment method), so no
|
||||
drawer, payment method or person is charged for them.
|
||||
- `parts` **part lines** appear on the order: the system product `split_part`, named "Split bill
|
||||
1/3", one each, already printed and served (the kitchen never sees them). They are paid like any
|
||||
line (cash, card, on a tab, at different times, by different people): they are the money.
|
||||
- Counting (services/sales.py): the settled lines are the sales (products, categories, costs);
|
||||
parts are settlement lines, never sales, but money taken (shifts' drawers, payment methods,
|
||||
tabs, the day's takings), so nothing is counted twice. A refund of a part comes off the settled
|
||||
lines by their share.
|
||||
- Locks: settled lines are no longer `active`, so cancelling, moving, combining, re-pricing and
|
||||
splitting them is refused everywhere; parts can't be moved, re-priced, combined or cancelled one
|
||||
by one (undo the split instead).
|
||||
- Undo while no part is paid or on a tab (Q-2): parts cancelled ("split undone"), lines back to
|
||||
unpaid. Refused once any payment was taken.
|
||||
- Fiscal (Greece, Q-3): a split is whole lines, so the receipt is the settled lines themselves, as
|
||||
if paid normally: issued once, when the **last part is paid**, with each method's amount as the
|
||||
receipt's payments (`receipts_due`). A part on a tab: no receipt from the split (like any line
|
||||
on a tab) — open point for the accountant (plan 6F.6).
|
||||
|
||||
Venue setting `payments.split_amount` (levels include the ones before, Q-1): off | two_equal |
|
||||
two_custom | multiple_equal (2…`payments.split_max_parts` equal parts). Key
|
||||
`ordering.payments.split_amount`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from core.errors import XeniaError
|
||||
|
||||
LEVELS = ("off", "two_equal", "two_custom", "multiple_equal")
|
||||
PART_KEY = "split_part"
|
||||
|
||||
|
||||
def _setting(db, key: str, default: str) -> str:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
return row.value if row is not None and row.value not in (None, "") else default
|
||||
|
||||
|
||||
def level(db) -> str:
|
||||
v = _setting(db, "payments.split_amount", "off")
|
||||
return v if v in LEVELS else "off"
|
||||
|
||||
|
||||
def max_parts(db) -> int:
|
||||
try:
|
||||
n = int(_setting(db, "payments.split_max_parts", "10"))
|
||||
except ValueError:
|
||||
n = 10
|
||||
return max(2, min(50, n))
|
||||
|
||||
|
||||
def allowed(lvl: str, mode: str, parts: int, most: int) -> bool:
|
||||
"""Whether the venue's level allows this split (each level includes the ones before)."""
|
||||
rank = LEVELS.index(lvl) if lvl in LEVELS else 0
|
||||
if mode == "custom":
|
||||
return parts == 2 and rank >= LEVELS.index("two_custom")
|
||||
if parts == 2:
|
||||
return rank >= LEVELS.index("two_equal")
|
||||
return rank >= LEVELS.index("multiple_equal") and 2 < parts <= most
|
||||
|
||||
|
||||
def amounts(total: float, mode: str, parts: int, first: float | None = None) -> list[float]:
|
||||
"""Each part, to the cent. Equal: the remainder goes on the last part (10.00 / 3 = 3.33 + 3.33
|
||||
+ 3.34). Custom (two parts): `first` is part 1, part 2 the rest."""
|
||||
cents = round(total * 100)
|
||||
if mode == "custom":
|
||||
a = round((first or 0) * 100)
|
||||
if not 0 < a < cents:
|
||||
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
|
||||
return [a / 100, (cents - a) / 100]
|
||||
base = cents // parts
|
||||
return [base / 100] * (parts - 1) + [(cents - base * (parts - 1)) / 100]
|
||||
|
||||
|
||||
def is_part(item) -> bool:
|
||||
"""A split bill's part line (money for the settled lines), not a sale."""
|
||||
return getattr(item, "split_bill_id", None) is not None and item.status != "split"
|
||||
|
||||
|
||||
def counts_as_sale(item, statuses=("active", "paid")) -> bool:
|
||||
"""For the older reports that pick lines by status: a settled line counts, a part never."""
|
||||
return item.status == "split" or (item.status in statuses and not is_part(item))
|
||||
|
||||
|
||||
def sold_filter(statuses=("active", "paid")):
|
||||
"""The same as SQL (OrderItem): settled lines, or lines in `statuses` that aren't parts."""
|
||||
from sqlalchemy import and_, or_
|
||||
from models.order import OrderItem
|
||||
return or_(OrderItem.status == "split", and_(OrderItem.status.in_(statuses), OrderItem.split_bill_id.is_(None)))
|
||||
|
||||
|
||||
def refuse_parts(items) -> None:
|
||||
if any(is_part(i) for i in items):
|
||||
raise XeniaError("split.part_locked")
|
||||
|
||||
|
||||
def live_bills(db, order_id: int) -> list:
|
||||
from models.order import SplitBill
|
||||
return db.query(SplitBill).filter(SplitBill.order_id == order_id, SplitBill.undone_at.is_(None)).order_by(SplitBill.id).all()
|
||||
|
||||
|
||||
def has_unpaid_parts(db, order_id: int) -> bool:
|
||||
from models.order import OrderItem
|
||||
return db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.split_bill_id.isnot(None),
|
||||
OrderItem.status.in_(("active", "ready"))).first() is not None
|
||||
|
||||
|
||||
def create(db, order, items, *, mode: str, parts: int, first: float | None, user) -> object:
|
||||
"""Settle `items` (unpaid lines of `order`) into a split bill with `parts` part lines.
|
||||
The caller checked the key; this checks the venue's level, the lines and fiscal."""
|
||||
from core.i18n import t, venue_language
|
||||
from core.timeutil import utcnow
|
||||
from models.order import OrderItem, SplitBill
|
||||
from services import system_products
|
||||
from services.sales import gross
|
||||
|
||||
if mode not in ("equal", "custom"):
|
||||
raise XeniaError("validation.choice", field="mode", value=mode)
|
||||
if not allowed(level(db), mode, parts, max_parts(db)):
|
||||
raise XeniaError("split.not_allowed")
|
||||
if not items or any(i.order_id != order.id or i.status not in ("active", "ready") for i in items):
|
||||
raise XeniaError("split.lines_changed")
|
||||
refuse_parts(items)
|
||||
total = round(sum(gross(i) for i in items), 2)
|
||||
if total < 0.01 * parts:
|
||||
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
|
||||
split = amounts(total, mode, parts, first)
|
||||
from services.fiscal import is_fiscal_enabled, validate_items_for_fiscal
|
||||
if is_fiscal_enabled(db):
|
||||
missing = validate_items_for_fiscal(items, db)
|
||||
if missing:
|
||||
raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
|
||||
|
||||
now = utcnow()
|
||||
bill = SplitBill(order_id=order.id, total=total, mode=mode, parts=parts, amounts=json.dumps(split),
|
||||
created_by=user.id, created_at=now, business_day_id=order.business_day_id)
|
||||
db.add(bill)
|
||||
db.flush()
|
||||
for i in items:
|
||||
i.status = "split"
|
||||
i.split_bill_id = bill.id
|
||||
i.paid_at = now
|
||||
i.paid_by = user.id
|
||||
i.payment_method = None
|
||||
i.paid_in_shift_id = None
|
||||
product = system_products.get(db, PART_KEY)
|
||||
lang = venue_language()
|
||||
for n, amount in enumerate(split, start=1):
|
||||
db.add(OrderItem(order_id=order.id, product_id=product.id, added_by=user.id, quantity=1, unit_price=amount,
|
||||
price_adjustment=0.0, status="active", printed=True, kds_status="served", split_bill_id=bill.id,
|
||||
product_name=t("split.part_name", lang, n=n, of=parts), source=items[0].source))
|
||||
db.flush()
|
||||
return bill
|
||||
|
||||
|
||||
def undo(db, order, bill, user) -> list[int]:
|
||||
"""Undo a split while no part was paid or put on a tab (Q-2). Returns the lines given back."""
|
||||
from core.timeutil import utcnow
|
||||
from models.order import OrderItem
|
||||
if bill.undone_at is not None or bill.order_id != order.id:
|
||||
raise XeniaError("split.not_found")
|
||||
rows = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id).all()
|
||||
parts = [i for i in rows if i.status != "split"]
|
||||
if any(p.status not in ("active", "ready", "cancelled") for p in parts):
|
||||
raise XeniaError("split.paid_already")
|
||||
now = utcnow()
|
||||
for p in parts:
|
||||
if p.status != "cancelled":
|
||||
p.status = "cancelled"
|
||||
p.cancelled_at = now
|
||||
p.cancelled_by = user.id
|
||||
p.cancel_reason = "split undone"
|
||||
back = []
|
||||
for i in rows:
|
||||
if i.status == "split":
|
||||
i.status = "active"
|
||||
i.split_bill_id = None
|
||||
i.paid_at = None
|
||||
i.paid_by = None
|
||||
back.append(i.id)
|
||||
bill.undone_at = now
|
||||
bill.undone_by = user.id
|
||||
db.flush()
|
||||
return back
|
||||
|
||||
|
||||
def receipts_due(db, paid_items) -> list[dict]:
|
||||
"""After parts were paid: the split bills whose last part is now paid get their fiscal receipt
|
||||
(marked issued here). [{"bill", "lines", "payments": [{"method", "amount"}]}]."""
|
||||
from core.timeutil import utcnow
|
||||
from models.order import OrderItem, SplitBill
|
||||
ids = {i.split_bill_id for i in paid_items if is_part(i)}
|
||||
out = []
|
||||
for bill in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all() if ids else []:
|
||||
if bill.undone_at is not None or bill.receipt_issued_at is not None:
|
||||
continue
|
||||
rows = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id).order_by(OrderItem.id).all()
|
||||
parts = [i for i in rows if i.status not in ("split", "cancelled")]
|
||||
if not parts or any(p.status != "paid" for p in parts):
|
||||
continue # unpaid, or on a tab: no receipt from the split (open point, plan 6F.6)
|
||||
by_method: dict[str, float] = {}
|
||||
for p in parts:
|
||||
m = p.payment_method or "cash"
|
||||
by_method[m] = round(by_method.get(m, 0.0) + (p.unit_price or 0.0) * p.quantity, 2)
|
||||
bill.receipt_issued_at = utcnow()
|
||||
out.append({"bill": bill, "lines": [i for i in rows if i.status == "split"],
|
||||
"payments": [{"method": m, "amount": a} for m, a in by_method.items()]})
|
||||
return out
|
||||
|
||||
|
||||
def bill_out(bill, rows) -> dict:
|
||||
"""What the apps show: the bill, its settled lines and its parts (with how each was paid)."""
|
||||
parts = [i for i in rows if i.split_bill_id == bill.id and i.status != "split" and i.status != "cancelled"]
|
||||
return {
|
||||
"id": bill.id, "total": bill.total, "mode": bill.mode, "parts": bill.parts,
|
||||
"amounts": json.loads(bill.amounts or "[]"),
|
||||
"created_by": bill.created_by,
|
||||
"created_at": bill.created_at.isoformat() + "Z" if bill.created_at and bill.created_at.tzinfo is None else (bill.created_at.isoformat() if bill.created_at else None),
|
||||
"line_ids": [i.id for i in rows if i.split_bill_id == bill.id and i.status == "split"],
|
||||
"part_ids": [p.id for p in parts],
|
||||
"paid": round(sum((p.unit_price or 0.0) * p.quantity for p in parts if p.status == "paid"), 2),
|
||||
"can_undo": all(p.status in ("active", "ready") for p in parts),
|
||||
"receipt_issued": bill.receipt_issued_at is not None,
|
||||
}
|
||||
Reference in New Issue
Block a user