Files
bonaminandClaude Opus 5.5 6b237fd169 feat(backend): KDS item claims across screens; zone screens only touch their own items (platform-v2 3.2c)
- order_items.claimed_by / claimed_at (Alembic 0015). POST/DELETE
  /api/kds/orders/{id}/items/{item}/claim (kds.bump): someone else's claim is refused
  (kds.item_claimed), letting go works for anyone with kds.bump; live kds_item_claimed.
  In progress claims for whoever did it; done/served/pending/declined clear the claim.
- Fix: order-level status and decline from a zone screen changed every zone's items;
  now only the screen's zone, and a zone screen sees the order status of its own items.
- Terminal: "I'm on it" / "Let go" on the selected card, the cook's name on claimed items.
- Tests: backend +6, terminal unit +1, terminal.mjs +6 with a second screen and cook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:25:34 +02:00

228 lines
13 KiB
Python

"""Kitchen screens: device settings and the KDS's own scope (plan step 3.2a).
A paired KDS device sees its prep zone only, gets what it needs through /api/kds (context,
retry-print) and never needs a route outside its scope; a manager may change the screen's
settings from the screen itself (PATCH /api/devices/me/config).
"""
import pytest
from core.modules import device_config
from tests.test_live import err, pair, owner_h, terminal_login # noqa: F401 (fixtures)
@pytest.fixture
def kitchen(db, make_user):
"""Two prep zones (Grill, Bar), one order with an item for each, a waiter on it."""
from models.order import Order, OrderItem, OrderWaiter
from models.prep_zone import PrepZone
from models.product import Category, Product
from models.settings import PosSettings
waiter = make_user(role="waiter")
grill, bar = PrepZone(name="Grill", notification_name="Grill station"), PrepZone(name="Bar")
cat = Category(name="Food")
db.add_all([grill, bar, cat])
db.flush()
steak = Product(name="Steak", base_price=20.0, primary_category_id=cat.id)
beer = Product(name="Beer", base_price=5.0, primary_category_id=cat.id)
steak.prep_zones, beer.prep_zones = [grill], [bar]
db.add_all([steak, beer])
db.flush()
order = Order(opened_by=waiter.id, order_type="takeaway")
db.add(order)
db.flush()
db.add(OrderWaiter(order_id=order.id, waiter_id=waiter.id))
db.add_all([OrderItem(order_id=order.id, product_id=p.id, added_by=waiter.id, quantity=1, unit_price=p.base_price)
for p in (steak, beer)])
for key, value in (("orders.courses_enabled", "true"), ("orders.courses", '[{"id": 1, "name": "Starters"}]')):
row = db.get(PosSettings, key)
if row is None:
db.add(PosSettings(key=key, value=value))
else:
row.value = value
db.commit()
return {"grill": grill, "bar": bar, "order": order, "waiter": waiter}
@pytest.fixture
def screen(client, pair, make_user, kitchen):
"""The 'Grill' screen with a chef signed in on it: headers for its calls."""
token, r = pair("kds", "Grill screen", config={"prep_zone_id": kitchen["grill"].id})
assert r.status_code == 201, r.text
chef = make_user(role="chef")
jwt = terminal_login(client, token, chef)
return {"id": r.json()["id"], "token": token,
"h": {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}}
def names(orders):
return sorted(it["product_name"] for o in orders for it in o["items"])
def test_screen_sees_only_its_zone(client, screen, kitchen, owner_h): # "done when" 1
h = screen["h"]
assert names(client.get("/api/kds/orders", headers=h).json()["orders"]) == ["Steak"]
# choosing another zone on the screen doesn't work
assert names(client.get(f"/api/kds/orders?zone_id={kitchen['bar'].id}", headers=h).json()["orders"]) == ["Steak"]
# the manager's page still chooses (no device)
assert names(client.get(f"/api/kds/orders?zone_id={kitchen['bar'].id}", headers=owner_h).json()["orders"]) == ["Beer"]
assert names(client.get("/api/kds/orders", headers=owner_h).json()["orders"]) == ["Beer", "Steak"]
# a screen without a zone sees every zone
assert client.patch(f"/api/devices/{screen['id']}", headers=owner_h,
json={"config": {"prep_zone_id": None}}).status_code == 200
assert names(client.get("/api/kds/orders", headers=h).json()["orders"]) == ["Beer", "Steak"]
def test_context_gives_settings_zone_and_courses(client, screen, kitchen, owner_h):
ctx = client.get("/api/kds/context", headers=screen["h"]).json()
assert ctx["device"] == {"id": screen["id"], "name": "Grill screen"}
assert ctx["zone"]["name"] == "Grill" and ctx["zone"]["notification_name"] == "Grill station"
assert {z["name"] for z in ctx["prep_zones"]} >= {"Grill", "Bar"}
assert ctx["settings"]["prep_zone_id"] == kitchen["grill"].id and ctx["settings"]["font_scale"] == 100
assert ctx["courses_enabled"] is True and ctx["courses"] == [{"id": 1, "name": "Starters"}]
# the manager's page: default settings, no device
page = client.get("/api/kds/context", headers=owner_h).json()
assert page["device"] is None and page["zone"] is None
assert page["settings"] == {f.key: f.default for f in device_config.for_app("kds")}
def test_no_kds_call_is_refused_by_the_scope(client, screen, kitchen): # "done when" 2
h, oid = screen["h"], kitchen["order"].id
item = client.get("/api/kds/orders", headers=h).json()["orders"][0]["items"][0]["id"]
calls = [
("get", "/api/devices/me", None),
("get", "/api/kds/context", None),
("get", "/api/kds/orders", None),
("get", "/api/kds/on-shift-waiters", None),
("put", f"/api/kds/orders/{oid}/items/{item}/kds_status", {"status": "preparing"}),
("put", f"/api/kds/orders/{oid}/kds_status", {"status": "preparing"}),
("post", f"/api/kds/orders/{oid}/notify-items-ready", {"ready_count": 1, "total_count": 2}),
("post", f"/api/kds/orders/{oid}/notify-complete", {}),
("post", f"/api/kds/orders/{oid}/call-waiter", {}),
("post", "/api/kds/call-waiter-general", {"waiter_ids": [kitchen["waiter"].id]}),
("post", f"/api/kds/orders/{oid}/retry-print", None),
("post", f"/api/kds/orders/{oid}/print", {"mode": "primary"}),
("put", f"/api/kds/orders/{oid}/items/{item}/decline", {"decline_note": "out of stock"}),
]
for method, url, body in calls:
r = getattr(client, method)(url, headers=h, **({"json": body} if body is not None else {}))
assert r.status_code < 400, f"{method} {url} -> {r.status_code} {r.text}"
# what the old page used instead is out of scope for a kitchen screen
assert err(client.get("/api/prep-zones", headers=h)) == "device.out_of_scope"
assert err(client.post(f"/api/orders/{oid}/retry-print", headers=h)) == "device.out_of_scope"
def test_messages_are_signed_by_the_screen(client, db, screen, kitchen, owner_h):
from models.message import StaffMessage
oid = kitchen["order"].id
client.post(f"/api/kds/orders/{oid}/call-waiter", headers=screen["h"], json={"kds_zone": "Fake"})
assert db.query(StaffMessage).order_by(StaffMessage.id.desc()).first().kds_zone == "Grill station"
assert client.patch(f"/api/devices/{screen['id']}", headers=owner_h,
json={"config": {"prep_zone_id": None}}).status_code == 200
client.post(f"/api/kds/orders/{oid}/call-waiter", headers=screen["h"], json={})
assert db.query(StaffMessage).order_by(StaffMessage.id.desc()).first().kds_zone == "Grill screen"
client.post(f"/api/kds/orders/{oid}/call-waiter", headers=owner_h, json={"kds_zone": "Pass"})
assert db.query(StaffMessage).order_by(StaffMessage.id.desc()).first().kds_zone == "Pass"
def test_settings_changed_from_the_screen(client, screen, make_user, kitchen):
# the chef doesn't hold core.devices.manage
r = client.patch("/api/devices/me/config", headers=screen["h"], json={"config": {"font_scale": 140}})
assert err(r) == "access.denied"
# a manager signed in on the same screen does; sent keys are merged
boss = make_user(role="store_manager")
h = {"X-Xenia-Device": screen["token"], "Authorization": f"Bearer {terminal_login(client, screen['token'], boss)}"}
r = client.patch("/api/devices/me/config", headers=h, json={"config": {"font_scale": 140, "sound": False}})
assert r.status_code == 200, r.text
cfg = r.json()["config"]
assert cfg["font_scale"] == 140 and cfg["sound"] is False and cfg["prep_zone_id"] == kitchen["grill"].id
assert client.get("/api/kds/context", headers=h).json()["settings"]["font_scale"] == 140
assert err(client.patch("/api/devices/me/config", headers=h,
json={"config": {"age_late_minutes": 2}})) == "validation.device_config"
assert err(client.patch("/api/devices/me/config", headers=h,
json={"config": {"colour_late": "red"}})) == "validation.device_config"
# without a device it's not a screen
assert err(client.patch("/api/devices/me/config", headers={"Authorization": h["Authorization"]},
json={"config": {}})) in ("device.not_paired", "device.required")
def test_item_back_to_pending_reopens_the_order(client, screen, kitchen):
"""Undo on the screen (3.2b): an item done → back to pending puts the order back too."""
h, oid = screen["h"], kitchen["order"].id
item = client.get("/api/kds/orders", headers=h).json()["orders"][0]["items"][0]["id"]
for status, expected in (("done", "done"), ("pending", "pending")): # as far as this zone goes (3.2c)
assert client.put(f"/api/kds/orders/{oid}/items/{item}/kds_status", headers=h, json={"status": status}).status_code == 200
order = next(o for o in client.get("/api/kds/orders", headers=h).json()["orders"] if o["id"] == oid)
assert order["kds_status"] == expected
# ── claims (3.2c) ────────────────────────────────────────────────────────────
@pytest.fixture
def second_screen(client, pair, make_user, kitchen):
token, r = pair("kds", "Grill screen 2", config={"prep_zone_id": kitchen["grill"].id})
chef = make_user(role="chef", nickname="Nikos")
jwt = terminal_login(client, token, chef)
return {"id": r.json()["id"], "h": {"X-Xenia-Device": token, "Authorization": f"Bearer {jwt}"}, "chef": chef}
def steak(client, h, oid):
order = next(o for o in client.get("/api/kds/orders", headers=h).json()["orders"] if o["id"] == oid)
return order["items"][0]
def test_two_screens_claim_without_stepping_on_each_other(client, screen, second_screen, kitchen): # "done when"
oid = kitchen["order"].id
item = steak(client, screen["h"], oid)["id"]
url = f"/api/kds/orders/{oid}/items/{item}/claim"
r = client.post(url, headers=second_screen["h"])
assert r.status_code == 200 and r.json()["claimed_by_name"] == "Nikos"
# the other screen sees it and can't take it
assert steak(client, screen["h"], oid)["claimed_by_name"] == "Nikos"
r = client.post(url, headers=screen["h"])
assert r.status_code == 409 and r.json()["error"] == {"code": "kds.item_claimed", "params": {"name": "Nikos"}, "message": "Nikos is already on this item."}
# claiming again is harmless; letting go works from any screen (a cook who left)
assert client.post(url, headers=second_screen["h"]).status_code == 200
assert client.delete(url, headers=screen["h"]).json()["claimed_by"] is None
assert client.post(url, headers=screen["h"]).status_code == 200
def test_in_progress_claims_and_bumping_clears(client, screen, second_screen, kitchen):
oid = kitchen["order"].id
item = steak(client, screen["h"], oid)["id"]
status = f"/api/kds/orders/{oid}/items/{item}/kds_status"
assert client.put(status, headers=second_screen["h"], json={"status": "preparing"}).status_code == 200
assert steak(client, screen["h"], oid)["claimed_by_name"] == "Nikos"
# in progress again from the other screen: still Nikos's
client.put(status, headers=screen["h"], json={"status": "preparing"})
assert steak(client, screen["h"], oid)["claimed_by_name"] == "Nikos"
assert client.put(status, headers=screen["h"], json={"status": "done"}).status_code == 200
assert steak(client, screen["h"], oid)["claimed_by"] is None
def test_claims_need_kds_bump(client, pair, make_user, kitchen, screen):
oid = kitchen["order"].id
item = steak(client, screen["h"], oid)["id"]
token, _ = pair("kds", "Pass", config={"prep_zone_id": kitchen["grill"].id})
viewer = make_user(role="chef", remove=("kds.bump",))
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, viewer)}"}
assert err(client.post(f"/api/kds/orders/{oid}/items/{item}/claim", headers=h)) == "access.denied"
def test_order_actions_on_a_zone_screen_leave_other_zones_alone(client, screen, kitchen, owner_h):
oid = kitchen["order"].id
r = client.put(f"/api/kds/orders/{oid}/kds_status", headers=screen["h"], json={"status": "done"})
assert r.status_code == 200 and r.json()["kds_status"] == "preparing" # the Bar's beer is still to do
everything = next(o for o in client.get("/api/kds/orders", headers=owner_h).json()["orders"] if o["id"] == oid)
assert {i["product_name"]: i["kds_status"] for i in everything["items"]} == {"Steak": "done", "Beer": "pending"}
client.put(f"/api/kds/orders/{oid}/decline", headers=screen["h"], json={"decline_note": "x"})
everything = next(o for o in client.get("/api/kds/orders", headers=owner_h).json()["orders"] if o["id"] == oid)
assert {i["product_name"]: i["kds_status"] for i in everything["items"]} == {"Steak": "declined", "Beer": "pending"}
def test_a_zone_screen_sees_how_far_its_own_items_are(client, screen, kitchen, owner_h):
oid = kitchen["order"].id
client.put(f"/api/kds/orders/{oid}/kds_status", headers=screen["h"], json={"status": "done"})
mine = next(o for o in client.get("/api/kds/orders", headers=screen["h"]).json()["orders"] if o["id"] == oid)
everything = next(o for o in client.get("/api/kds/orders", headers=owner_h).json()["orders"] if o["id"] == oid)
assert (mine["kds_status"], everything["kds_status"]) == ("done", "preparing")