Files
xenia-pos-local/local_backend/tests/test_pos_tables.py
T
bonaminandClaude Opus 5.5 988d413d8e feat(backend,terminal): tables at the counter, shared live with the waiter phones (platform-v2 3.3c)
- POS: GET /api/pos/tables (the cashier's zones as in the waiter app, each open order's
  totals, people, ready items, flags, reservation), POST /api/pos/tables/{id}/items (into
  the table's order or a new one via orders.open_order + add_items), POST
  /api/pos/orders/{id}/pay (chosen items, cash/card/split, drawer on cash), POST
  /api/pos/orders/{id}/close (only when nothing is unpaid). Quote takes order_id so the
  order's items count for cart conditions (shared pos_cart.order_cart, used by add_items).
- New codes pos.table_not_found, pos.table_not_yours, pos.items_changed, pos.order_unpaid.
- Fix: item cancels (DELETE item, cancel-items) now broadcast order_updated, so phones and
  kitchen screens see them at once.
- Terminal: Sale | Tables switch, zone list, table cards by zone, TablePanel (order lines,
  new lines, send, pay selected/all, cancel with approval, close), generic PaymentDialog.
- Tests: test_pos_tables.py (8), terminal unit, terminal.mjs +17 with a live phone socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 02:15:54 +02:00

200 lines
12 KiB
Python

"""Counter POS: tables at the counter (plan step 3.3c). The counter works on tables with the
waiter app's rules and functions; these tests prove both sides see and change the same order."""
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)
@pytest.fixture
def floor(db, till):
"""Two zones: Terrace (T1, T2) for the cashier and Inside (T3) that isn't theirs."""
from models.table import Table, TableGroup
from models.user import WaiterZone
terrace, inside = TableGroup(name="Terrace", sort_order=1), TableGroup(name="Inside", sort_order=2)
db.add_all([terrace, inside])
db.flush()
t1, t2 = Table(number=1, group_id=terrace.id, seat_count=4), Table(number=2, label="Corner", group_id=terrace.id)
t3 = Table(number=3, group_id=inside.id)
db.add_all([t1, t2, t3])
db.add(WaiterZone(waiter_id=till["cashier"].id, group_id=terrace.id))
db.commit()
return {"terrace": terrace, "inside": inside, "t1": t1, "t2": t2, "t3": t3}
@pytest.fixture
def phone(db, make_user, login, floor, on_shift):
"""A waiter on their phone, working the terrace too, with their own shift."""
from models.shift import WaiterShift
from models.user import WaiterZone
maria = make_user(role="waiter", nickname="Maria")
db.add(WaiterZone(waiter_id=maria.id, group_id=floor["terrace"].id))
db.add(WaiterShift(waiter_id=maria.id, business_day_id=on_shift.business_day_id))
db.commit()
return {"user": maria, "h": login(maria, "waiter")}
@pytest.fixture
def events(monkeypatch):
"""Order events broadcast by routers/orders.py (what phones, the KDS and the counter hear)."""
import routers.orders as orders
got = []
real = orders.broadcast_sync
monkeypatch.setattr(orders, "broadcast_sync", lambda kind, data, **kw: (got.append((kind, data)), real(kind, data, **kw)))
return got
def tables(client, till):
r = client.get("/api/pos/tables", headers=till["h"])
assert r.status_code == 200, r.text
return {t["name"]: t for t in r.json()["tables"]}, r.json()["groups"]
def send(client, till, table, lines):
return client.post(f"/api/pos/tables/{table.id}/items", headers=till["h"], json={"lines": lines})
def test_tables_follow_the_cashiers_zones(client, db, till, floor, phone, menu):
from models.flag import TableFlagAssignment, TableFlagDef
flag = TableFlagDef(name="VIP", emoji="⭐", color="#aa0000")
db.add(flag)
db.flush()
db.add(TableFlagAssignment(table_id=floor["t2"].id, flag_id=flag.id))
db.commit()
by_name, groups = tables(client, till)
assert set(by_name) == {"T1", "Corner"} and [g["name"] for g in groups] == ["Terrace"]
assert by_name["T1"]["order"] is None and by_name["T1"]["seats"] == 4
assert by_name["Corner"]["flags"] == [{"id": flag.id, "name": "VIP", "emoji": "⭐", "color": "#aa0000", "text_color": None}]
# the waiter opens T1 on the phone; the counter sees it with totals and who is on it
o = client.post("/api/orders/", headers=phone["h"], json={"table_id": floor["t1"].id}).json()
client.post(f"/api/orders/{o['id']}/items", headers=phone["h"], json={"items": [{"product_id": menu["coffee"].id, "quantity": 2}]})
t1 = tables(client, till)[0]["T1"]["order"]
assert t1["id"] == o["id"] and t1["total"] == 6.0 and t1["unpaid"] == 6.0 and t1["items"] == 1
assert t1["people"] == ["Maria"] and t1["mine"] is False
def test_counter_and_phone_share_a_table(client, db, till, floor, phone, menu, events):
"""The done-when of 3.3c at the API level: both sides add to one order and see the other's
changes; every change is broadcast."""
m = menu
r = send(client, till, floor["t1"], [{"product_id": m["coffee"].id}])
assert r.status_code == 201, r.text
oid = r.json()["order_id"]
assert ("order_updated", {"order_id": oid, "table_id": floor["t1"].id, "status": "open", "action": "opened"}) in events
# the phone sees the counter's order and adds to it
seen = client.get(f"/api/orders/{oid}", headers=phone["h"]).json()
assert [i["product_name"] for i in seen["items"]] == ["Freddo"]
assert client.post(f"/api/orders/{oid}/items", headers=phone["h"],
json={"items": [{"product_id": m["coffee"].id, "quantity": 1}]}).status_code == 200
# the counter adds a burger to the same order (not a second one)
assert send(client, till, floor["t1"], [burger_line(m)]).json()["order_id"] == oid
t1 = tables(client, till)[0]["T1"]["order"]
assert t1["total"] == 16.0 and t1["mine"] is True and t1["people"] == [till["cashier"].full_name]
detail = client.get(f"/api/orders/{oid}", headers=till["h"]).json()
assert sorted(i["product_name"] for i in detail["items"]) == ["Burger", "Freddo", "Freddo"]
def test_quote_for_a_table_counts_its_items(client, db, till, floor, menu, on_shift):
"""The table's items already on the order count for cart conditions, as in add_items."""
import json as _json
from models.order import OrderItem
from models.pricing import PriceModifier, PriceModifierCondition
mod = PriceModifier(name="2nd coffee", scope="item", item_id=menu["coffee"].id, action_type="add_percent", action_value=-10, is_active=1)
db.add(mod)
db.flush()
db.add(PriceModifierCondition(modifier_id=mod.id, condition_type="min_item_quantity", params=_json.dumps({"min": 2})))
db.commit()
line = [{"product_id": menu["coffee"].id}]
oid = send(client, till, floor["t1"], line).json()["order_id"]
assert client.post("/api/pos/quote", headers=till["h"], json={"lines": line}).json()["total"] == 3.0
q = client.post("/api/pos/quote", headers=till["h"], json={"order_id": oid, "lines": line}).json()
assert q["order_type"] == "here" and q["total"] == 2.7
send(client, till, floor["t1"], line)
prices = [i.unit_price for i in db.query(OrderItem).filter(OrderItem.order_id == oid).order_by(OrderItem.id)]
assert prices == [3.0, 2.7] # the order charged what the quote said
def test_tables_outside_the_zones_are_refused(client, db, till, floor, menu, on_shift, make_user, login):
from models.shift import WaiterShift
from models.user import WaiterZone
assert err(send(client, till, floor["t3"], [{"product_id": menu["coffee"].id}])) == "pos.table_not_yours"
# an order inside, opened by someone else, can't be quoted, paid or closed from here
nikos = make_user(role="waiter")
db.add(WaiterZone(waiter_id=nikos.id, group_id=floor["inside"].id))
db.add(WaiterShift(waiter_id=nikos.id, business_day_id=on_shift.business_day_id))
db.commit()
h = login(nikos, "waiter")
o = client.post("/api/orders/", headers=h, json={"table_id": floor["t3"].id}).json()
client.post(f"/api/orders/{o['id']}/items", headers=h, json={"items": [{"product_id": menu["coffee"].id, "quantity": 1}]})
item = client.get(f"/api/orders/{o['id']}", headers=h).json()["items"][0]["id"]
assert err(client.post("/api/pos/quote", headers=till["h"], json={"order_id": o["id"], "lines": []})) == "pos.table_not_yours"
assert err(client.post(f"/api/pos/orders/{o['id']}/pay", headers=till["h"],
json={"payments": [{"method": "cash", "item_ids": [item]}]})) == "pos.table_not_yours"
assert err(client.post(f"/api/pos/orders/{o['id']}/close", headers=till["h"])) == "pos.table_not_yours"
assert err(client.post("/api/pos/tables/999999/items", headers=till["h"], json={"lines": [{"product_id": menu["coffee"].id}]})) == "pos.table_not_found"
def test_sending_needs_a_shift_and_checks_lines_first(client, db, till, floor, menu):
from models.order import Order
assert err(send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}])) == "pos.shift_required"
assert db.query(Order).count() == 0
def test_pay_some_add_more_pay_the_rest_close(client, db, till, floor, menu, on_shift, drawer_printer, events):
from models.order import Order
m = menu
oid = send(client, till, floor["t1"], [{"product_id": m["coffee"].id, "quantity": 2}, burger_line(m)]).json()["order_id"]
items = {i["product_name"]: i["id"] for i in client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"]}
# pay the coffees in cash: change, drawer
r = client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"],
json={"payments": [{"method": "cash", "item_ids": [items["Freddo"]]}], "cash_given": 10})
assert r.status_code == 200, r.text
assert (r.json()["total"], r.json()["change"], r.json()["drawer"], r.json()["status"]) == (6.0, 4.0, "opened", "partially_paid")
assert any(k == "order_paid" and d["order_id"] == oid for k, d in events)
# paying them again (someone else did) → nothing happens
assert err(client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"],
json={"payments": [{"method": "card", "item_ids": [items["Freddo"], items["Burger"]]}]})) == "pos.items_changed"
# can't close with the burger unpaid
r = client.post(f"/api/pos/orders/{oid}/close", headers=till["h"])
assert err(r) == "pos.order_unpaid" and r.json()["error"]["params"] == {"count": 1}
# add more, then pay the rest split: burger by card, the new coffee in cash
send(client, till, floor["t1"], [{"product_id": m["coffee"].id}])
rest = [i for i in client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"] if i["status"] == "active"]
burger = next(i["id"] for i in rest if i["product_name"] == "Burger")
coffee = next(i["id"] for i in rest if i["product_name"] == "Freddo")
r = client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"],
json={"payments": [{"method": "card", "item_ids": [burger]}, {"method": "cash", "item_ids": [coffee]}]})
assert r.status_code == 200 and r.json()["status"] == "paid" and r.json()["change"] is None
assert [(p["method"], p["amount"]) for p in r.json()["payments"]] == [("card", 10.0), ("cash", 3.0)]
shift = client.get("/api/shifts/my", headers=till["h"]).json()
assert (shift["cash_sales"], shift["card_sales"]) == (9.0, 10.0)
assert client.post(f"/api/pos/orders/{oid}/close", headers=till["h"]).json() == {"status": "closed"}
assert db.get(Order, oid).status == "closed" and tables(client, till)[0]["T1"]["order"] is None
def test_pay_checks(client, till, floor, menu, on_shift):
oid = send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}]).json()["order_id"]
item = client.get(f"/api/orders/{oid}", headers=till["h"]).json()["items"][0]["id"]
pay = lambda body: client.post(f"/api/pos/orders/{oid}/pay", headers=till["h"], json=body) # noqa: E731
assert err(pay({"payments": [{"method": "cash", "item_ids": [item]}], "cash_given": 1})) == "pos.payment_invalid"
assert err(pay({"payments": [{"method": "cash", "item_ids": [item]}, {"method": "card", "item_ids": [item]}]})) == "pos.payment_invalid"
assert err(pay({"payments": [{"method": "cash", "item_ids": [999999]}]})) == "pos.items_changed"
def test_cancel_from_the_counter_needs_a_manager_and_is_broadcast(client, db, till, floor, menu, on_shift, pair, make_user, events):
from models.order import OrderItem
oid = send(client, till, floor["t1"], [{"product_id": menu["coffee"].id}, {"product_id": menu["coffee"].id, "notes": "iced"}]).json()["order_id"]
ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == oid).order_by(OrderItem.id)]
# a waiter-role cashier can't cancel sent items alone: the manager-approval dialog
r = client.post(f"/api/orders/{oid}/cancel-items", headers=till["h"], json={"item_ids": [ids[0]]})
assert err(r) == "access.override_possible"
# a manager at the counter can; everyone hears about it
token, _ = pair("pos_counter", "Till 3")
boss = make_user(role="owner")
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"}
r = client.post(f"/api/orders/{oid}/cancel-items", headers=h, json={"item_ids": [ids[0]]})
assert r.status_code == 200 and r.json()["cancelled"] == [ids[0]]
assert ("order_updated", {"order_id": oid, "table_id": floor["t1"].id, "status": "open",
"action": "items_cancelled", "item_ids": [ids[0]]}) in events
assert tables(client, till)[0]["T1"]["order"]["total"] == 3.0