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:
2026-11-23 10:57:54 +02:00
co-authored by Claude Opus 5.5
parent 72e175ab73
commit 3eeafb565a
54 changed files with 1707 additions and 105 deletions
+237
View File
@@ -0,0 +1,237 @@
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
- POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status split) and adds part
lines (the system product split_part), paid like any line; the venue's level and the key decide.
- Undo while no part is paid; parts can't be cancelled, moved or re-priced on their own.
- Counting: the settled lines are the sales, the parts are the money (drawers), never both.
- Fiscal: one receipt with the settled lines, when the last part is paid, with each method's amount.
- The counter: a quick sale split and paid at once (Q-4).
"""
import json
import pytest
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import burger_line, drawer_printer, menu, on_shift, sale, till # noqa: F401 (fixtures)
from tests.test_pos_refunds import fiscal_on, refund, shift_of, wait_for
def setting(db, key, value):
from models.settings import PosSettings
row = db.get(PosSettings, key)
if row is None:
db.add(PosSettings(key=key, value=value))
else:
row.value = value
db.commit()
@pytest.fixture
def table_order(db, till, menu, on_shift):
"""The cashier's order with a 10.00 burger and a 5.00 (two coffees at 2.50), nothing paid."""
from models.order import Order, OrderItem, OrderWaiter
o = Order(opened_by=till["cashier"].id, order_type="here", status="open", business_day_id=on_shift.business_day_id)
db.add(o)
db.flush()
db.add(OrderWaiter(order_id=o.id, waiter_id=till["cashier"].id))
items = [OrderItem(order_id=o.id, product_id=menu["burger"].id, added_by=till["cashier"].id, quantity=1, unit_price=10.0,
printed=True, kds_status="preparing", unit_cost=3.5),
OrderItem(order_id=o.id, product_id=menu["coffee"].id, added_by=till["cashier"].id, quantity=2, unit_price=2.5,
printed=True)]
db.add_all(items)
db.commit()
return {"order": o, "items": items}
def split(client, till, order_id, ids, **body):
return client.post(f"/api/orders/{order_id}/split-bills", headers=till["h"], json={"item_ids": ids, **body})
def rows(db, order_id):
from models.order import OrderItem
db.expire_all()
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
def pay(client, till, order_id, method, ids):
return client.post(f"/api/pos/orders/{order_id}/pay", headers=till["h"], json={"payments": [{"method": method, "item_ids": ids}]})
def test_amounts_and_levels():
from services.split_bills import allowed, amounts
assert amounts(10.0, "equal", 3) == [3.33, 3.33, 3.34]
assert amounts(15.0, "equal", 2) == [7.5, 7.5]
assert amounts(15.0, "custom", 2, 4.5) == [4.5, 10.5]
assert sum(amounts(17.21, "equal", 7)) == pytest.approx(17.21)
# each level includes the ones before; multiple ways are equal parts only (Q-1)
assert not allowed("off", "equal", 2, 10)
assert allowed("two_equal", "equal", 2, 10) and not allowed("two_equal", "custom", 2, 10)
assert allowed("two_custom", "custom", 2, 10) and not allowed("two_custom", "equal", 3, 10)
assert allowed("multiple_equal", "equal", 10, 10) and not allowed("multiple_equal", "equal", 11, 10)
assert allowed("multiple_equal", "custom", 2, 10) and not allowed("multiple_equal", "custom", 3, 10)
def test_split_30_70_paid_cash_and_card(client, db, till, table_order):
"""10 + 5 into 4.50 + 10.50: the lines settled, two parts paid apart; the drawer counts the
parts, the sales count the lines, never both."""
from services import sales
o, items = table_order["order"], table_order["items"]
ids = [i.id for i in items]
assert err(split(client, till, o.id, ids, mode="custom", first_amount=4.5)) == "split.not_allowed" # off by default
setting(db, "payments.split_amount", "two_custom")
r = split(client, till, o.id, ids, mode="custom", first_amount=4.5)
assert r.status_code == 200, r.text
bill = r.json()
assert (bill["total"], bill["amounts"], bill["parts"], bill["can_undo"]) == (15.0, [4.5, 10.5], 2, True)
lines = rows(db, o.id)
settled = [i for i in lines if i.status == "split"]
parts = [i for i in lines if i.split_bill_id and i.status != "split"]
assert {i.id for i in settled} == set(ids) and all(i.paid_in_shift_id is None and i.payment_method is None for i in settled)
assert [(p.product_name, p.unit_price, p.status, p.printed, p.kds_status) for p in parts] == [
("Split bill 1/2", 4.5, "active", True, "served"), ("Split bill 2/2", 10.5, "active", True, "served")]
assert parts[0].product.system_key == "split_part"
# the settled burger is still cooking: the kitchen state is untouched
assert next(i for i in settled if i.unit_price == 10.0).kds_status == "preparing"
got = client.get(f"/api/orders/{o.id}", headers=till["h"]).json()
assert got["split_bills"][0]["part_ids"] == [p.id for p in parts]
assert pay(client, till, o.id, "cash", [parts[0].id]).status_code == 200
# undo refused once a part is paid (Q-2)
assert err(client.post(f"/api/orders/{o.id}/split-bills/{bill['id']}/undo", headers=till["h"])) == "split.paid_already"
r = pay(client, till, o.id, "card", [parts[1].id])
assert r.status_code == 200 and r.json()["status"] in ("paid", "closed"), r.text
s = shift_of(client, till)
assert (s["cash_sales"], s["card_sales"]) == (4.5, 10.5)
money = sales.totals(sales.lines(db, rows(db, o.id))).out()
assert (money["revenue"], money["fees"], money["takings"], money["total_cost"]) == (15.0, 0.0, 15.0, 3.5)
assert {p["product_name"] for p in sales.products(db, rows(db, o.id)).values()} == {"Burger", "Freddo"}
def test_equal_parts_levels_and_the_key(client, db, till, table_order, login, make_user):
o, items = table_order["order"], table_order["items"]
ids = [i.id for i in items]
setting(db, "payments.split_amount", "two_equal")
assert err(split(client, till, o.id, ids, parts=3)) == "split.not_allowed"
assert err(split(client, till, o.id, ids, mode="custom", first_amount=5)) == "split.not_allowed"
setting(db, "payments.split_amount", "multiple_equal")
setting(db, "payments.split_max_parts", "4")
assert err(split(client, till, o.id, ids, parts=5)) == "split.not_allowed"
# the key: someone without it is refused (a manager could approve it, D-10)
from models.user import WaiterZone
w = make_user(role="waiter", remove=("ordering.payments.split_amount",))
db.add(WaiterZone(waiter_id=w.id, group_id=None))
db.commit()
r = client.post(f"/api/orders/{o.id}/split-bills", headers=login(w, client="waiter"), json={"item_ids": ids, "parts": 3})
assert err(r) in ("access.denied", "access.override_possible")
r = split(client, till, o.id, ids, parts=4)
assert r.status_code == 200 and r.json()["amounts"] == [3.75, 3.75, 3.75, 3.75]
# the same lines can't be split twice
assert err(split(client, till, o.id, ids, parts=2)) == "split.lines_changed"
def test_locks_close_and_undo(client, db, till, table_order):
from models.order import OrderAuditLog
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "multiple_equal")
bill = split(client, till, o.id, [i.id for i in items], parts=3).json()
assert bill["amounts"] == [5.0, 5.0, 5.0]
part = bill["part_ids"][0]
h = till["h"]
assert err(client.delete(f"/api/orders/{o.id}/items/{part}", headers=h)) in ("split.part_locked", "access.override_possible")
assert err(client.patch(f"/api/orders/{o.id}/items/{part}/price-adjust", headers=h, json={"price_adjustment": -1})) == "split.part_locked"
assert err(client.post(f"/api/orders/{o.id}/items/combine", headers=h, json={"item_ids": bill["part_ids"][:2]})) == "split.part_locked"
assert err(client.patch(f"/api/orders/{o.id}/items/{items[0].id}/price-adjust", headers=h, json={"price_adjustment": -1})) == "order.item_not_active"
setting(db, "orders.close_with_unpaid", "true")
assert err(client.post(f"/api/orders/{o.id}/close", headers=h)) == "split.parts_unpaid" # never written off
# undo: the parts cancelled, the lines unpaid again
r = client.post(f"/api/orders/{o.id}/split-bills/{bill['id']}/undo", headers=h)
assert r.status_code == 200, r.text
lines = rows(db, o.id)
assert [i.status for i in lines if i.id in (items[0].id, items[1].id)] == ["active", "active"]
assert all(i.split_bill_id is None and i.paid_at is None for i in lines if i.id in (items[0].id, items[1].id))
assert [(i.status, i.cancel_reason) for i in lines if i.id in bill["part_ids"]] == [("cancelled", "split undone")] * 3
assert client.get(f"/api/orders/{o.id}", headers=h).json()["split_bills"] == []
events = [a.event_type for a in db.query(OrderAuditLog).filter(OrderAuditLog.order_id == o.id).order_by(OrderAuditLog.id)]
assert events[-2:] == ["SPLIT_CREATED", "SPLIT_UNDONE"]
def test_the_fiscal_receipt_is_the_lines_when_the_last_part_is_paid(client, db, till, menu, table_order, tmp_path, monkeypatch):
from services import fiscal
from services.fiscal.base import FiscalDriver
issued = []
class Machine(FiscalDriver):
key = "test_machine"
def prepare_receipt(self, db, items, method, total, payments=None):
issued.append((items, method, total, payments))
return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
monkeypatch.setitem(fiscal.DRIVERS, "test_machine", Machine())
monkeypatch.setattr(fiscal, "_set_status", lambda *a: None)
fiscal_on(db, tmp_path)
setting(db, "fiscal.type", "test_machine")
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "two_custom")
assert err(split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5)) == "pos.fiscal_vat_missing"
menu["burger"].fiscal_vat_group_id = 1
menu["coffee"].fiscal_vat_group_id = 2
db.commit()
bill = split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5).json()
r = pay(client, till, o.id, "cash", [bill["part_ids"][0]])
assert r.status_code == 200 and r.json()["fiscal"] is None and issued == [] # part 1: no receipt yet
r = pay(client, till, o.id, "card", [bill["part_ids"][1]])
assert r.status_code == 200 and r.json()["fiscal"] == "pending"
assert wait_for(lambda: issued)
lines, _method, total, payments = issued[0]
assert sorted((x["name"], x["qty"], x["unit_price"], x["vat_group_id"]) for x in lines) == [("Burger", 1, 10.0, 1), ("Freddo", 2, 2.5, 2)]
assert total == 15.0 and sorted((p["method"], p["amount"]) for p in payments) == [("card", 10.5), ("cash", 4.5)]
assert sum(x["qty"] * x["unit_price"] for x in lines) == pytest.approx(sum(p["amount"] for p in payments))
assert len(issued) == 1
def test_the_text_file_closes_with_card_then_cash(db, tmp_path):
from services.fiscal.txt_file import _build_command_file
fiscal_on(db, tmp_path)
out = _build_command_file([{"name": "Burger", "qty": 1, "unit_price": 10.0, "vat_group_id": 1}], "cash", 10.0, db,
payments=[{"method": "cash", "amount": 4.5}, {"method": "card", "amount": 5.5}])
assert out.split("\r\n")[-3:] == ["CD|2|1|1|5.50", "CR|2", ""]
out = _build_command_file([{"name": "Burger", "qty": 1, "unit_price": 10.0, "vat_group_id": 1}], "cash", 10.0, db,
payments=[{"method": "card", "amount": 10.0}])
assert out.split("\r\n")[-2:] == ["CD|2|1|1|10.00", ""]
def test_a_refunded_part_comes_off_the_settled_lines(client, db, till, table_order, drawer_printer):
from services import sales
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "two_custom")
bill = split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5).json()
assert pay(client, till, o.id, "cash", bill["part_ids"]).status_code == 200
r = refund(client, till, o.id, [{"item_id": bill["part_ids"][0], "quantity": 1}], reason="Overcharged")
assert r.status_code == 201, r.text
money = sales.totals(sales.lines(db, rows(db, o.id))).out()
assert (money["revenue"], money["refunded"]) == (10.5, 4.5)
assert shift_of(client, till)["cash_refunds"] == 4.5
def test_a_quick_sale_split_and_paid_at_once(client, db, till, menu, on_shift, drawer_printer):
"""Q-4: the counter splits a quick sale into equal parts, each paid its own way now."""
from models.order import Order
setting(db, "payments.split_amount", "multiple_equal")
lines = [{"product_id": menu["coffee"].id, "quantity": 3}, burger_line(menu)]
r = sale(client, till, lines, [], split={"mode": "equal", "parts": 3, "methods": ["cash", "card", "cash"]}, cash_given=20)
assert r.status_code == 201, r.text
body = r.json()
assert body["total"] == 19.0 and body["split"]["amounts"] == [6.33, 6.33, 6.34]
assert sorted((p["method"], p["amount"]) for p in body["payments"]) == [("card", 6.33), ("cash", 12.67)]
assert body["change"] == 7.33
db.expire_all()
assert db.get(Order, body["order_id"]).status in ("paid", "closed")
s = shift_of(client, till)
assert (s["cash_sales"], s["card_sales"]) == (12.67, 6.33)
# off at this venue → refused before anything is written
setting(db, "payments.split_amount", "two_equal")
n = db.query(Order).count()
r = sale(client, till, lines, [], split={"mode": "equal", "parts": 3, "methods": ["cash", "card", "cash"]})
assert err(r) == "split.not_allowed" and db.query(Order).count() == n