feat(backend): KDS settings as device config, zone enforced for kitchen screens, KDS-only API (platform-v2 3.2a)

- KDS manifest: 23 typed settings (prep zone, board, waiting-time minutes and colours,
  behaviour) replacing the KDS page's localStorage settings.
- ConfigField: colour type, "after" ordering (warning < late < flash), groups for the
  manager's dialogs, ".none" text for an empty ref choice.
- routers/kds.py: a KDS device gets only its zone's orders, prints to its zone by default
  and signs waiter messages with its zone/name. New GET /api/kds/context and
  POST /api/kds/orders/{id}/retry-print so the screen never leaves its kds.* scope.
  Unused v1 /items and /items/{id}/status endpoints removed (D-21).
- PATCH /api/devices/me/config: a screen changes its own settings when the signed-in
  person holds core.devices.manage.
- Manager Devices dialogs: settings in sections, colour pickers, "All zones".
- Tests: test_kds_device.py, colour/ordered fields; terminal.mjs scope + zone checks;
  manager.mjs settings sections; stack.mjs detaches the non-LAN network before the
  restart check (one flaky 403).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 18:56:59 +02:00
co-authored by Claude Opus 5.5
parent c24cb72640
commit d5c4400fde
17 changed files with 762 additions and 140 deletions
+1 -1
View File
@@ -74,7 +74,7 @@ def test_pairing_flow(client, owner_h):
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
assert poll.status_code == 200
token = poll.json()["device_token"]
assert poll.json()["device"]["config"] == {"auto_sign_out_minutes": 5} and poll.json()["device"]["app_status"] == "ok"
assert poll.json()["device"]["config"]["auto_sign_out_minutes"] == 5 and poll.json()["device"]["app_status"] == "ok"
# the token is handed out exactly once
assert err(client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})) \
== "device.pair_code_invalid"
+145
View File
@@ -0,0 +1,145 @@
"""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")
+25 -6
View File
@@ -187,12 +187,13 @@ def test_config_validated_and_effective(client, pair, owner_h): # "done when" 4
assert err(r) == "validation.device_config"
token, r = pair("kds")
assert r.json()["config"] == {"auto_sign_out_minutes": 0} # defaults filled
defaults = {f.key: f.default for f in device_config.for_app("kds")}
assert r.json()["config"] == defaults # defaults filled
dev_id = r.json()["id"]
r = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"config": {"auto_sign_out_minutes": 5}})
assert r.status_code == 200 and r.json()["config"] == {"auto_sign_out_minutes": 5}
assert r.status_code == 200 and r.json()["config"] == {**defaults, "auto_sign_out_minutes": 5}
assert client.get("/api/devices/me", headers={"X-Xenia-Device": token}).json()["config"] \
== {"auto_sign_out_minutes": 5}
== {**defaults, "auto_sign_out_minutes": 5}
assert err(client.patch(f"/api/devices/{dev_id}", headers=owner_h,
json={"config": {"auto_sign_out_minutes": True}})) == "validation.device_config"
# an app without config fields refuses any key
@@ -203,9 +204,13 @@ def test_config_validated_and_effective(client, pair, owner_h): # "done when" 4
def test_module_catalogue_describes_config(client, owner_h):
mods = {m["key"]: m for m in client.get("/api/platform/modules", headers=owner_h).json()["modules"]}
assert mods["kds"]["device_app"]["config"] == [{"key": "auto_sign_out_minutes", "type": "int", "default": 0,
"choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None,
"choices_from": None}]
assert mods["pos_counter"]["device_app"]["config"] == [{"key": "auto_sign_out_minutes", "type": "int", "default": 0,
"choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None,
"choices_from": None, "group": None, "after": None}]
kds = {f["key"]: f for f in mods["kds"]["device_app"]["config"]}
assert kds["prep_zone_id"] == {"key": "prep_zone_id", "type": "ref", "default": None, "choices": [], "min": None,
"max": None, "choices_from": "prep_zones", "group": "zone", "after": None}
assert kds["age_late_minutes"]["after"] == "age_warning_minutes" and kds["colour_fresh"]["type"] == "color"
assert mods["customer_display"]["device_app"]["config"] == []
@@ -234,3 +239,17 @@ def test_config_field_types(db, pair):
eff = device_config.effective(fields, {"zone": 99999, "layout": "tiles", "scale": 120}, db)
assert eff == {"zone": None, "pos": None, "sound": True, "layout": "grid", "scale": 120, "title": ""}
assert device_config.effective(fields, "junk") == {f.key: f.default for f in fields}
def test_config_colours_and_ordered_fields():
fields = (ConfigField("ink", "color", default="#000000"),
ConfigField("warn", "int", default=5, min=1, max=60),
ConfigField("late", "int", default=10, min=1, max=60, after="warn"))
assert device_config.validate(fields, {"ink": "#A0b1C2"}, None) == {"ink": "#a0b1c2"}
for bad in ({"ink": "red"}, {"ink": "#abc"}, {"ink": 5}, {"late": 4}, {"warn": 10}, {"warn": 8, "late": 8}):
with pytest.raises(Exception) as e:
device_config.validate(fields, bad, None)
assert e.value.code == "validation.device_config"
assert device_config.validate(fields, {"warn": 20, "late": 30}, None) == {"warn": 20, "late": 30}
# a stored config that breaks the order reads back as the defaults of the ordered fields
assert device_config.effective(fields, {"ink": "#ffffff", "warn": 30, "late": 20}) == {"ink": "#ffffff", "warn": 5, "late": 10}
+6 -1
View File
@@ -50,7 +50,8 @@ def test_every_permission_has_a_label(lang):
@pytest.mark.parametrize("lang", ["en", "el"])
def test_every_device_config_field_has_texts(lang):
"""modules:<app>.config.<key>.label, and .choices.<value> for every choice (plan step 3.1a)."""
"""modules:<app>.config.<key>.label, .choices.<value> for every choice (3.1a), .none for a
ref field's empty choice and config_groups.<group> for every group (3.2a)."""
texts = json.loads((LOCALES / lang / "modules.json").read_text(encoding="utf-8"))
missing, known = [], set()
for m in registry().values():
@@ -61,6 +62,10 @@ def test_every_device_config_field_has_texts(lang):
for c in f.choices:
if not t.get("choices", {}).get(str(c)):
missing.append(f"{m.key}.config.{f.key}.choices.{c}")
if f.type == "ref" and not t.get("none"):
missing.append(f"{m.key}.config.{f.key}.none")
if f.group and not texts.get(m.key, {}).get("config_groups", {}).get(f.group):
missing.append(f"{m.key}.config_groups.{f.group}")
known.add((m.key, f.key))
assert missing == []
extra = {(mod, k) for mod, t in texts.items() for k in t.get("config", {})} - known