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:
@@ -43,7 +43,8 @@ def card(db, customer) -> dict:
|
||||
from models.table import Table
|
||||
orders = db.query(Order).filter(Order.customer_id == customer.id).order_by(Order.opened_at.desc()).all()
|
||||
done = [o for o in orders if o.status in ("closed", "paid")]
|
||||
live = lambda o: [i for i in o.items if i.status in ("active", "paid")] # noqa: E731
|
||||
from services.split_bills import counts_as_sale
|
||||
live = lambda o: [i for i in o.items if counts_as_sale(i)] # noqa: E731 (6F.6: settled lines, not parts)
|
||||
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
return {
|
||||
"id": customer.id, "name": customer.name, "nickname": customer.nickname, "phone": customer.phone,
|
||||
|
||||
@@ -125,13 +125,14 @@ def _in_background(db_factory, model, row_id: int, prepare, timeout_seconds: int
|
||||
|
||||
|
||||
def send_fiscal_receipt_background(items: list[dict], payment_method: str, total: float, db, order_id: int,
|
||||
db_factory, timeout_seconds: int = 60) -> None:
|
||||
db_factory, timeout_seconds: int = 60, payments: list[dict] | None = None) -> None:
|
||||
"""Issue the receipt through the venue's driver in a background thread; order.fiscal_status
|
||||
becomes success or failed when the device answers (or the wait times out)."""
|
||||
becomes success or failed when the device answers (or the wait times out). `payments`
|
||||
[{"method", "amount"}]: a receipt paid in several ways (a split bill's parts, 6F.6)."""
|
||||
from models.order import Order
|
||||
driver = driver_for(db)
|
||||
_in_background(db_factory, Order, order_id, lambda: driver.prepare_receipt(db, items, payment_method, total),
|
||||
timeout_seconds)
|
||||
_in_background(db_factory, Order, order_id,
|
||||
lambda: driver.prepare_receipt(db, items, payment_method, total, payments=payments), timeout_seconds)
|
||||
|
||||
|
||||
def send_credit_note_background(items: list[dict], method: str, total: float, db, refund_id: int, original: dict,
|
||||
|
||||
@@ -28,8 +28,9 @@ class FiscalDriver:
|
||||
# cashier is told to issue the credit note on the machine itself (owner decision 2026-11-15).
|
||||
credit_notes: bool = False
|
||||
|
||||
def prepare_receipt(self, db, items: list[dict], method: str, total: float) -> Send:
|
||||
"""A sales receipt, ready to send."""
|
||||
def prepare_receipt(self, db, items: list[dict], method: str, total: float, payments: list[dict] | None = None) -> Send:
|
||||
"""A sales receipt, ready to send. `payments` [{"method", "amount"}] when it was paid in
|
||||
several ways (a split bill, 6F.6); else all of it by `method`."""
|
||||
raise NotImplementedError
|
||||
|
||||
def prepare_credit_note(self, db, items: list[dict], method: str, total: float, original: dict | None = None) -> Send:
|
||||
|
||||
@@ -62,7 +62,7 @@ def _get_folders(db) -> tuple[str, str]:
|
||||
return out_folder, in_folder
|
||||
|
||||
|
||||
def _build_command_file(items: list[dict], payment_method: str, total: float, db) -> str:
|
||||
def _build_command_file(items: list[dict], payment_method: str, total: float, db, payments: list[dict] | None = None) -> str:
|
||||
"""
|
||||
Build the fiscal command file content as a string.
|
||||
|
||||
@@ -98,7 +98,15 @@ def _build_command_file(items: list[dict], payment_method: str, total: float, db
|
||||
if msg_line.strip():
|
||||
lines.append(f"FM|{i}|{msg_line.upper()}")
|
||||
|
||||
if payment_method == "card":
|
||||
if payments and len(payments) > 1:
|
||||
# Paid in several ways (a split bill, 6F.6; the driver manual's "multiple ways to close"):
|
||||
# each card amount through the EFT/POS first, then cash closes the rest.
|
||||
card = [p for p in payments if p.get("method") == "card" and p.get("amount", 0) > 0]
|
||||
for p in card:
|
||||
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{p['amount']:.2f}")
|
||||
if round(sum(p.get("amount", 0) for p in payments if p not in card), 2) > 0:
|
||||
lines.append(f"CR|{clerk_id}")
|
||||
elif (payments[0].get("method") if payments else payment_method) == "card":
|
||||
total_str = f"{total:.2f}"
|
||||
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{total_str}")
|
||||
else:
|
||||
@@ -177,11 +185,11 @@ class TxtFileDriver(FiscalDriver):
|
||||
name = "dTEC100extra (text-file bridge)"
|
||||
credit_notes = False
|
||||
|
||||
def prepare_receipt(self, db, items, method, total):
|
||||
def prepare_receipt(self, db, items, method, total, payments=None):
|
||||
out_folder, in_folder = _get_folders(db)
|
||||
os.makedirs(out_folder, exist_ok=True)
|
||||
os.makedirs(in_folder, exist_ok=True)
|
||||
content = _build_command_file(items, method, total, db)
|
||||
content = _build_command_file(items, method, total, db, payments)
|
||||
filename = _unique_filename()
|
||||
return lambda timeout_seconds: _write_and_poll(out_folder, in_folder, content, filename, timeout_seconds)
|
||||
|
||||
|
||||
@@ -7,6 +7,10 @@ in every report, on screen, printed and exported.
|
||||
- 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.
|
||||
@@ -17,7 +21,7 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
SOLD = ("active", "paid", "tabbed")
|
||||
SOLD = ("active", "paid", "tabbed", "split")
|
||||
|
||||
|
||||
def gross(item, quantity: float | None = None) -> float:
|
||||
@@ -58,17 +62,40 @@ 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
|
||||
sold = [i for i in items if i.status in SOLD]
|
||||
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:
|
||||
r = min(back.get(i.id, 0.0), i.quantity)
|
||||
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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -21,7 +21,8 @@ from __future__ import annotations
|
||||
from collections import Counter
|
||||
|
||||
DELIVERY_FEE = "delivery_fee"
|
||||
KEYS = (DELIVERY_FEE,)
|
||||
SPLIT_PART = "split_part" # a split bill's part line (6F.6, services/split_bills.py)
|
||||
KEYS = (DELIVERY_FEE, SPLIT_PART)
|
||||
|
||||
|
||||
def _usual_vat_group(db):
|
||||
|
||||
Reference in New Issue
Block a user