feat(waiter): close with unpaid items as a setting, combine lines, seats (platform-v2 step 4.8a)

The owner's choices for 4.8 (2026-11-18), all configurable:
- Setting orders.close_with_unpaid (default off): when off, the server refuses to close
  an order with unpaid items (pos.order_unpaid) and the phone's CLOSE takes the payment
  first ("instant-pay close"); when on, CLOSE confirms and the items stay unpaid. Manager
  Settings → Operation, next to "auto-close after full payment" (unchanged).
- POST /api/orders/{id}/items/combine: unpaid lines of the same item (choices, note,
  price, course, kitchen state; no discount / deal / tab) become one line; the phone
  offers "Combine into one line" for selected lines or a grouped line. The grouping
  views (identical / same item) stay as they were.
- Seats: the table's seats next to its name on the cards (waiter Settings → Layout, on by
  default) and in the guests dialog, where more guests than seats only shows a hint.
- The table screen's last English-only labels (ADD, PAY, CLOSE, ACTIONS, SERVED, CLEAR,
  ALL) are keys too.
- Tests: test_close_and_combine.py (5), waiter e2e +5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 09:54:37 +02:00
co-authored by Claude Opus 5.5
parent beb53c65bb
commit 198f8ff571
18 changed files with 376 additions and 39 deletions
+1
View File
@@ -74,6 +74,7 @@ CODES: dict[str, tuple[int, str]] = {
"pos.table_not_yours": (403, "{table} isn't in your zones. A manager can add the zone to your account."),
"pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."),
"pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."),
"order.items_not_combinable": (422, "These lines can't be combined: only unpaid lines of the same item, with the same choices, note, price and kitchen state, and no discount, deal or tab."),
"order.not_sold_here": (422, "{name} isn't sold for this kind of order."),
"order.lines_required": (422, "This app sent the order in an old format. Update the app and send it again."),
"order.line.product_unavailable": (422, "{name} isn't available any more (line {line})."),
@@ -20,6 +20,7 @@ MODULE = Module(
SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'),
SettingDef('business_day.rollover_hour', '6', 'Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.', type='int'),
SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'),
SettingDef('orders.close_with_unpaid', 'false', "Allow closing an order that still has unpaid items (they are written off as unpaid): 'true' | 'false'. When 'false', closing asks for the payment first (plan step 4.8).", type='bool'),
SettingDef('orders.bypass_kds_serve', 'false', "Skip KDS pending/serve flow — new orders and items are immediately marked as served: 'true' | 'false'", type='bool'),
SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'),
SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'),
+72
View File
@@ -50,6 +50,9 @@ class MoveItemsRequest(BaseModel):
item_ids: List[int]
target_order_id: int
class CombineItemsRequest(BaseModel):
item_ids: List[int] = Field(min_length=2, max_length=200)
class RevertPaymentRequest(BaseModel):
item_ids: List[int]
@@ -1095,6 +1098,12 @@ def close_order(order_id: int, request: Request, db: Session = Depends(get_db),
OrderItem.order_id == order_id,
OrderItem.status == "active",
).all()
# 4.8: the venue decides whether an order may be closed with unpaid items (written off);
# when not, the apps take the payment first ("instant-pay close")
if active_items:
row = db.query(PosSettings).filter(PosSettings.key == "orders.close_with_unpaid").first()
if not (row and row.value == "true"):
raise XeniaError("pos.order_unpaid", count=len(active_items))
closed_item_ids = []
for item in active_items:
item.status = "closed"
@@ -2064,3 +2073,66 @@ def put_item_on_tab(
db.commit()
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "status": order.status, "action": "item_tabbed"})
return {"status": "tabbed", "tab_id": tab.id, "entry_amount": entry.amount}
# ── Combine selected items (plan step 4.8) ────────────────────────────────────
def _combine_key(i: OrderItem):
"""What must be the same for two lines to become one: the product, every choice, the note,
the price, the course, the kitchen state, and nothing attached to the line on its own."""
import json as _json
def norm(raw):
try:
return _json.dumps(_json.loads(raw), sort_keys=True) if raw else "[]"
except ValueError:
return raw
return (i.product_id, norm(i.selected_options), norm(i.removed_ingredients), (i.notes or "").strip(),
round(i.unit_price or 0.0, 4), round(i.price_adjustment or 0.0, 4), i.course_id, i.kds_status or "pending")
@router.post("/{order_id}/items/combine")
def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""Combine unpaid lines of the same item into one (2 + 2 + 2 beers ordered at different
times → one line of 6): the first line keeps its id and gets the quantities, the others are
removed, their price events move to it. Only lines that are the same in every way that
matters (_combine_key), unpaid, without a discount, a deal, a tab or a linked line.
Needs ordering.orders.open (like moving and splitting)."""
from models.pricing import PriceEventLog
from models.tabs import TabEntry
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
_need(request, db, user, "ordering.orders.open", target=f"order:{order_id}")
if not _can_access_order(order, user, db):
raise HTTPException(status_code=403, detail="Access denied")
ids = sorted(set(body.item_ids))
items = db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.id.in_(ids)).order_by(OrderItem.id).all()
if len(items) != len(ids) or len(items) < 2:
raise XeniaError("order.items_not_combinable", reason="not_found")
if any(i.status != "active" for i in items):
raise XeniaError("order.items_not_combinable", reason="not_unpaid")
if any(i.deal_id or i.linked_item_id for i in items) or \
db.query(OrderItem).filter(OrderItem.linked_item_id.in_(ids)).first() is not None:
raise XeniaError("order.items_not_combinable", reason="deal")
if db.query(OrderDiscount).filter(OrderDiscount.item_id.in_(ids)).first() is not None:
raise XeniaError("order.items_not_combinable", reason="discount")
if db.query(TabEntry).filter(TabEntry.order_item_id.in_(ids)).first() is not None:
raise XeniaError("order.items_not_combinable", reason="tab")
if len({_combine_key(i) for i in items}) != 1:
raise XeniaError("order.items_not_combinable", reason="different")
keep, rest = items[0], items[1:]
keep.quantity = round(sum(i.quantity for i in items), 3)
keep.printed = all(i.printed for i in items)
rest_ids = [i.id for i in rest]
db.query(PriceEventLog).filter(PriceEventLog.order_item_id.in_(rest_ids)).update(
{PriceEventLog.order_item_id: keep.id}, synchronize_session=False)
for i in rest:
db.delete(i)
_audit(db, order_id, "ITEMS_COMBINED", waiter_id=user.id, item_ids=[keep.id] + rest_ids,
note=f"into #{keep.id}, quantity {keep.quantity:g}")
db.commit()
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
"action": "items_combined", "item_ids": [keep.id]})
return {"item_id": keep.id, "quantity": keep.quantity, "removed": rest_ids}
@@ -0,0 +1,68 @@
"""Owner's choices of plan step 4.8: closing with unpaid items is a venue setting, and unpaid
lines of the same item can be combined into one."""
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, till # noqa: F401 (fixtures)
from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures)
@pytest.fixture(autouse=True)
def _no_printing(monkeypatch):
import routers.orders as orders
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
def order_with(client, phone, floor, lines):
oid = client.post("/api/orders/", headers=phone["h"], json={"table_id": floor["t1"].id, "order_type": "here"}).json()["id"]
for line in lines:
assert client.post(f"/api/orders/{oid}/items", headers=phone["h"], json={"lines": [line]}).status_code == 200
return oid
def items(db, oid):
from models.order import OrderItem
db.expire_all()
return db.query(OrderItem).filter(OrderItem.order_id == oid).order_by(OrderItem.id).all()
def test_closing_with_unpaid_items_follows_the_setting(client, db, menu, phone, floor, owner_h):
beer = {"product_id": menu["coffee"].id, "quantity": 2}
oid = order_with(client, phone, floor, [beer])
r = client.post(f"/api/orders/{oid}/close", headers=phone["h"])
assert r.status_code == 409 and err(r) == "pos.order_unpaid" and r.json()["error"]["params"]["count"] == 1
assert client.put("/api/settings/orders.close_with_unpaid", headers=owner_h, json={"value": "true"}).status_code == 200
assert client.post(f"/api/orders/{oid}/close", headers=phone["h"]).status_code == 200
assert [i.status for i in items(db, oid)] == ["closed"]
def test_combine_the_same_item_ordered_at_different_times(client, db, menu, phone, floor):
from models.order import OrderAuditLog
beer = {"product_id": menu["coffee"].id, "quantity": 2}
oid = order_with(client, phone, floor, [beer, beer, beer])
ids = [i.id for i in items(db, oid)]
r = client.post(f"/api/orders/{oid}/items/combine", headers=phone["h"], json={"item_ids": ids})
assert r.status_code == 200, r.text
left = items(db, oid)
assert [(i.id, i.quantity) for i in left] == [(ids[0], 6)]
assert db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "ITEMS_COMBINED").count() == 1
@pytest.mark.parametrize("second,reason", [
(lambda m: {"product_id": m["coffee"].id, "quantity": 1, "notes": "no ice"}, "different"),
(lambda m: burger_line(m), "different"),
])
def test_only_lines_that_are_the_same(client, db, menu, phone, floor, second, reason):
oid = order_with(client, phone, floor, [{"product_id": menu["coffee"].id, "quantity": 1}, second(menu)])
r = client.post(f"/api/orders/{oid}/items/combine", headers=phone["h"], json={"item_ids": [i.id for i in items(db, oid)]})
assert r.status_code == 422 and err(r) == "order.items_not_combinable" and r.json()["error"]["params"]["reason"] == reason
assert len(items(db, oid)) == 2
def test_paid_lines_are_not_combined(client, db, menu, phone, floor):
beer = {"product_id": menu["coffee"].id, "quantity": 1}
oid = order_with(client, phone, floor, [beer, beer])
first, second = items(db, oid)
assert client.post(f"/api/orders/{oid}/pay", headers=phone["h"], json={"item_ids": [first.id], "payment_method": "cash"}).status_code == 200
r = client.post(f"/api/orders/{oid}/items/combine", headers=phone["h"], json={"item_ids": [first.id, second.id]})
assert err(r) == "order.items_not_combinable" and r.json()["error"]["params"]["reason"] == "not_unpaid"