Files
bonaminandClaude Opus 5.5 3eeafb565a 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>
2026-11-23 10:57:54 +02:00

223 lines
9.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""How every report counts sales (plan step 6.12a). One set of rules, so a day adds up the same
in every report, on screen, printed and exported.
- **Sold** = order lines that are `active` (ordered, not paid yet), `paid`, or on a customer's tab
(`tabbed`: sold, not paid; owner 2026-11-19, plan step 6.13c). Cancelled lines and lines written
off at closing (`closed`) are not sales. `on_tab` says how much of the sales is on tabs.
- A line's **value** = (unit price + its price change) × quantity, then **minus what was refunded**
of it (services/refunds.py: refunds are per line and quantity, so they come off the line, the
product, the category, the table, the hour and the day they belong to).
- **A split bill** (6F.6, services/split_bills.py): the lines it settled (`split`) are sold like
paid lines; its **part lines** are the money for them, never a sale (left out here; the shifts'
drawers, payment methods and tabs count them). A refund of a part comes off the settled lines
by their share of the bill.
- **Fees** (lines the system adds, `system_key` set: the delivery fee) are counted apart: they are
money taken, but not a product sold. `revenue` everywhere is products only; `fees` is beside it;
`takings` = revenue + fees.
- **Cost / profit**: a line with a cost snapshot adds its cost (for the quantity kept) and its
profit; a line without one makes the total a lower bound (`has_gap`).
"""
from __future__ import annotations
from dataclasses import dataclass
SOLD = ("active", "paid", "tabbed", "split")
def gross(item, quantity: float | None = None) -> float:
q = item.quantity if quantity is None else quantity
return ((item.unit_price or 0.0) + (item.price_adjustment or 0.0)) * q
def is_fee(item) -> bool:
return getattr(item, "system_key", None) is not None
def _fee_products(db) -> set[int]:
"""The system products (the delivery fee…): one query, instead of loading each line's product."""
from models.product import Product
return {pid for (pid,) in db.query(Product.id).filter(Product.system_key.isnot(None)).all()}
@dataclass
class Line:
item: object
quantity: float # sold minus refunded
value: float # its value minus the refunded part
refunded: float # the refunded value
fee: bool
@property
def kept(self) -> bool:
"""Something of it was kept (not refunded in full)."""
return self.quantity > 1e-9
@property
def cost(self) -> float | None:
uc = getattr(self.item, "unit_cost", None)
return None if uc is None else uc * self.quantity
def lines(db, items) -> list[Line]:
"""Sold lines (see the module doc) with their refunds taken off. A line refunded in full
stays (quantity 0, value 0) so its refund is counted; `sold()` leaves it out of lists."""
from services.refunds import refunded_quantities
from services.split_bills import is_part
sold = [i for i in items if i.status in SOLD and not is_part(i)]
back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"])
shares = _split_refunds(db, {i.split_bill_id for i in sold if i.status == "split"})
fees = _fee_products(db) if sold else set()
out = []
for i in sold:
if i.status == "split":
r = i.quantity * shares.get(i.split_bill_id, 0.0)
else:
r = min(back.get(i.id, 0.0), i.quantity)
q = max(i.quantity - r, 0.0)
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=i.product_id in fees))
return out
def _split_refunds(db, bill_ids) -> dict[int, float]:
"""{split_bill_id: the share of the bill refunded} from its parts' refunds (6F.6)."""
from models.order import OrderItem, SplitBill
from services.refunds import refunded_quantities
ids = {b for b in bill_ids if b is not None}
if not ids:
return {}
parts = db.query(OrderItem).filter(OrderItem.split_bill_id.in_(ids), OrderItem.status == "paid").all()
back = refunded_quantities(db, [p.id for p in parts])
if not back:
return {}
totals = {b.id: b.total for b in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all()}
value: dict[int, float] = {}
for p in parts:
value[p.split_bill_id] = value.get(p.split_bill_id, 0.0) + gross(p, min(back.get(p.id, 0.0), p.quantity))
return {b: min(v / totals[b], 1.0) for b, v in value.items() if totals.get(b)}
@dataclass
class Totals:
revenue: float = 0.0 # products, net of refunds
fees: float = 0.0 # delivery fees (and other system lines), net of refunds
refunded: float = 0.0 # what was refunded of these lines (already taken off)
cost: float = 0.0
profit: float = 0.0
has_gap: bool = False
units: float = 0.0 # products' quantity
on_tab: float = 0.0 # the part of revenue + fees on customers' tabs (sold, not paid)
@property
def takings(self) -> float:
return self.revenue + self.fees
def add(self, line: Line) -> "Totals":
self.refunded += line.refunded
if line.item.status == "tabbed":
self.on_tab += line.value
if line.fee:
self.fees += line.value
return self
self.revenue += line.value
self.units += line.quantity
c = line.cost
if c is None:
self.has_gap = self.has_gap or line.kept
else:
self.cost += c
self.profit += line.value - c
return self
def out(self) -> dict:
r = lambda v: round(v + 0.0, 2) # noqa: E731 (-0.0 → 0.0)
return {"revenue": r(self.revenue), "fees": r(self.fees), "takings": r(self.takings), "refunded": r(self.refunded),
"total_cost": r(self.cost), "trackable_profit": r(self.profit), "has_gap": self.has_gap,
"on_tab": r(self.on_tab)}
def totals(ls) -> Totals:
t = Totals()
for line in ls:
t.add(line)
return t
def order_totals(db, orders) -> dict[int, Totals]:
"""{order_id: Totals} for orders (their items loaded through the relationship)."""
all_items = [i for o in orders for i in o.items]
by_order: dict[int, Totals] = {o.id: Totals() for o in orders}
for line in lines(db, all_items):
by_order[line.item.order_id].add(line)
return by_order
# ── summaries shared by the screens, the printed reports and the exports ─────
def products(db, items, category_id: int | None = None) -> dict:
"""{product_id: {...}} for product lines (fees left out), names and categories as sold (D-18)."""
pnames = _names(items)
out: dict = {}
for line in lines(db, items):
if line.fee or not line.kept:
continue
it = line.item
if category_id and it.category_id != category_id:
continue
e = out.setdefault(it.product_id, {
"product_id": it.product_id, "product_name": pnames.get(it.product_id) or f"#{it.product_id}",
"category_id": it.category_id, "qty_sold": 0.0, "revenue": 0.0, "refunded": 0.0, "total_cost": 0.0,
"trackable_profit": 0.0, "uncosted_revenue": 0.0, "uncosted_items": 0.0, "order_ids": set(),
})
e["qty_sold"] += line.quantity
e["revenue"] += line.value
e["refunded"] += line.refunded
e["order_ids"].add(it.order_id)
c = line.cost
if c is None:
e["uncosted_revenue"] += line.value
e["uncosted_items"] += line.quantity
else:
e["total_cost"] += c
e["trackable_profit"] += line.value - c
return out
def categories(db, items) -> dict:
"""{category_id: {...}} for product lines, with each category's products."""
pnames = _names(items)
cnames = _names(items, "category")
out: dict = {}
for line in lines(db, items):
if line.fee or not line.kept:
continue
it = line.item
cid = it.category_id
e = out.setdefault(cid, {"category_id": cid, "category_name": cnames.get(cid) or "—", "units_sold": 0.0, "revenue": 0.0,
"refunded": 0.0, "total_cost": 0.0, "trackable_profit": 0.0, "uncosted_revenue": 0.0,
"has_gap": False, "products": {}})
e["units_sold"] += line.quantity
e["revenue"] += line.value
e["refunded"] += line.refunded
c = line.cost
if c is None:
e["uncosted_revenue"] += line.value
e["has_gap"] = True
else:
e["total_cost"] += c
e["trackable_profit"] += line.value - c
p = e["products"].setdefault(it.product_id, {"name": pnames.get(it.product_id) or f"#{it.product_id}", "qty": 0.0, "revenue": 0.0})
p["qty"] += line.quantity
p["revenue"] += line.value
return out
def _names(items, kind: str = "product") -> dict:
"""Names as sold; if renamed within the period, the newest wins (D-18, CS-4)."""
out = {}
for it in sorted(items, key=lambda i: (i.added_at is None, i.added_at, i.id)):
if kind == "product":
out[it.product_id] = it.product_name
elif it.category_id is not None:
out[it.category_id] = it.category_name
return out