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
+27 -2
View File
@@ -15,12 +15,19 @@ Agent notes:
(`<app>.config.<key>.label`, plus `.choices.<value>` per choice); test_module_texts fails
otherwise. The manager renders the fields generically (DeviceConfigFields.jsx).
- `ref` sources: "prep_zones" (PrepZone ids), "devices:<app_key>" (live devices of that app).
- `color` = "#rrggbb" (lower-cased when stored). `after="<key>"` (int fields): the value must be
greater than that field's (stored or default) value, e.g. KDS age thresholds; a stored
config that breaks the order reads back as the defaults of every ordered field (3.2a).
- `group` only sections the manager's dialogs (modules:<app>.config_groups.<group>).
"""
from __future__ import annotations
import re
from core.errors import XeniaError
MAX_STR = 200
_COLOR = re.compile(r"^#[0-9a-fA-F]{6}$")
def for_app(app_key: str) -> tuple:
@@ -63,6 +70,8 @@ def _clean(f, value, db, *, strict: bool):
return value.strip() if isinstance(value, str) and len(value) <= MAX_STR else bad()
if f.type == "enum":
return value if value in f.choices else bad()
if f.type == "color":
return value.lower() if isinstance(value, str) and _COLOR.match(value) else bad()
if f.type == "ref":
if value is None:
return None
@@ -86,15 +95,31 @@ def validate(fields, config, db) -> dict | None:
if f is None:
raise _bad(key)
out[key] = _clean(f, value, db, strict=True)
merged = {f.key: out.get(f.key, f.default) for f in fields}
for f in fields:
if f.after and not _ordered(f, merged):
raise _bad(f.key)
return out or None
def _ordered(f, values: dict) -> bool:
a, b = values.get(f.key), values.get(f.after)
return not (isinstance(a, int) and isinstance(b, int)) or a > b
def effective(fields, stored, db=None) -> dict:
stored = stored if isinstance(stored, dict) else {}
return {f.key: (_clean(f, stored[f.key], db, strict=False) if f.key in stored else f.default) for f in fields}
out = {f.key: (_clean(f, stored[f.key], db, strict=False) if f.key in stored else f.default) for f in fields}
ordered = [f for f in fields if f.after]
if any(not _ordered(f, out) for f in ordered):
for f in ordered:
out[f.key] = f.default
out[f.after] = next((g.default for g in fields if g.key == f.after), out[f.after])
return out
def describe(fields) -> list[dict]:
"""The fields for the manager (module catalogue)."""
return [{"key": f.key, "type": f.type, "default": f.default, "choices": list(f.choices),
"min": f.min, "max": f.max, "choices_from": f.choices_from} for f in fields]
"min": f.min, "max": f.max, "choices_from": f.choices_from, "group": f.group, "after": f.after}
for f in fields]
+5 -2
View File
@@ -54,7 +54,7 @@ class SettingDef:
choices: tuple[str, ...] = () # for type "enum"
ConfigType = Literal["bool", "int", "str", "enum", "ref"]
ConfigType = Literal["bool", "int", "str", "enum", "ref", "color"]
@dataclass(frozen=True)
@@ -62,7 +62,8 @@ class ConfigField:
"""One setting of a device running an app (plan step 3.1a). Stored in devices.config,
validated by core/modules/device_config.py, edited in the manager's pair/edit dialogs.
Texts: modules:<app>.config.<key>.label (+ .hint optional, + .choices.<value> for each
choice), checked by tests/test_module_texts.py."""
choice, + .none for a ref's empty choice; groups: modules:<app>.config_groups.<group>),
checked by tests/test_module_texts.py."""
key: str
type: ConfigType
default: object = None
@@ -70,6 +71,8 @@ class ConfigField:
min: Optional[int] = None # int
max: Optional[int] = None # int
choices_from: Optional[str] = None # ref: "prep_zones" | "devices:<app_key>"; value = id or None
group: Optional[str] = None # section in the manager's dialogs (3.2a)
after: Optional[str] = None # int: must be greater than this other field (age thresholds)
@dataclass(frozen=True)
+36 -2
View File
@@ -5,6 +5,41 @@ from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Per
# the terminal from step 3.1c.
AUTO_SIGN_OUT = ConfigField('auto_sign_out_minutes', 'int', default=0, choices=(0, 2, 5, 10, 30, 60))
# A kitchen screen's settings (plan step 3.2a). They were the KDS page's localStorage settings
# (manager_dashboard KdsPage.jsx, `xenia_kds_settings_v2`); now they belong to the device, are
# edited on the Devices page or on the screen (PATCH /api/devices/me/config), and the screen
# reads them from GET /api/kds/context. prep_zone_id also scopes the backend: a KDS device
# with a zone only ever gets that zone's orders (routers/kds.py).
KDS_CONFIG = (
ConfigField('prep_zone_id', 'ref', default=None, choices_from='prep_zones', group='zone'),
# board
ConfigField('card_width', 'int', default=272, min=200, max=800, group='board'),
ConfigField('font_scale', 'int', default=100, min=60, max=200, group='board'),
ConfigField('font_weight', 'int', default=600, choices=(300, 400, 500, 600, 700, 800), group='board'),
ConfigField('batch_mode', 'enum', default='merged', choices=('merged', 'grouped', 'split'), group='board'),
ConfigField('group_items', 'enum', default='off',
choices=('off', 'floating', 'right_sidebar', 'left_sidebar', 'topbar_button'), group='board'),
ConfigField('group_by_course', 'bool', default=False, group='board'),
ConfigField('combine_modifiers', 'bool', default=False, group='board'),
ConfigField('categories_as_filters', 'bool', default=True, group='board'),
# how late an order is: minutes and colours
ConfigField('age_warning_minutes', 'int', default=5, min=1, max=120, group='age'),
ConfigField('age_late_minutes', 'int', default=10, min=2, max=120, after='age_warning_minutes', group='age'),
ConfigField('age_flash_minutes', 'int', default=15, min=3, max=120, after='age_late_minutes', group='age'),
ConfigField('flash_late', 'bool', default=True, group='age'),
ConfigField('colour_fresh', 'color', default='#34b56a', group='age'),
ConfigField('colour_warning', 'color', default='#f0a52a', group='age'),
ConfigField('colour_late', 'color', default='#e8513f', group='age'),
ConfigField('colour_done', 'color', default='#3d4757', group='age'),
# behaviour
ConfigField('triple_state', 'bool', default=False, group='behaviour'),
ConfigField('sound', 'bool', default=True, group='behaviour'),
ConfigField('notify_order_complete', 'bool', default=False, group='behaviour'),
ConfigField('notify_item_complete', 'bool', default=False, group='behaviour'),
ConfigField('refresh_seconds', 'int', default=30, choices=(10, 15, 20, 30, 45, 60, 90, 120), group='behaviour'),
AUTO_SIGN_OUT,
)
MODULE = Module(
key='kds',
kind='app',
@@ -18,8 +53,7 @@ MODULE = Module(
limits=(
Limit('devices', 'Number of kitchen screens', free=0, licensed_default=1),
),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('kds.*',),
config=(AUTO_SIGN_OUT,)),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('kds.*',), config=KDS_CONFIG),
routers=(
Mount('routers.kds', '/api/kds'),
),
+29
View File
@@ -24,6 +24,9 @@ Agent notes:
- Live (3.1a): an edit sends `device.updated` to the device's open sockets; reassign sends
`device.updated` and closes them; revoke sends `device.revoked` and closes them
(services/ws_bus.py). The screen re-reads GET /me or goes back to pairing.
- A screen may change its own settings (PATCH /me/config, 3.2a, e.g. the KDS settings
panel) when the person signed in on it holds core.devices.manage. That one key is checked
without the device scope: the call can only ever change the calling device.
"""
from __future__ import annotations
@@ -47,6 +50,7 @@ from core.errors import XeniaError
from core.modules.registry import registry
from core.timeutil import iso_z, utcnow
from database import get_db
from routers.deps import get_current_user
from models.device import Device, DevicePairRequest
from services import ws_bus
@@ -310,6 +314,31 @@ def device_users(db: Session = Depends(get_db), device=Depends(require_device())
for u in users if u.role != "superadmin"]
class SelfConfigPatch(BaseModel):
config: dict
@router.patch("/me/config")
def update_own_config(body: SelfConfigPatch, request: Request, db: Session = Depends(get_db),
device=Depends(require_device()), user=Depends(get_current_user)):
"""The screen changes its own settings (sent keys are merged into the stored ones).
Needs a signed-in person holding core.devices.manage on this screen."""
from core.access.check import check
from core.access.context import context_for
ctx = context_for(request, user, db)
ctx.device = None # this key on this route acts on the calling device only (see Agent notes)
check(ctx, MANAGE, db)
if device.revoked_at is not None:
raise XeniaError("device.revoked")
fields = device_config.for_app(device.app_key)
current = _effective_config(device, db)
kept = {k: v for k, v in (device.config or {}).items() if k in current and current[k] == v}
device.config = _config(device.app_key, {**kept, **body.config}, db)
db.commit()
ws_bus.notify_device([device.id])
return {"config": device_config.effective(fields, device.config, db)}
@router.get("/{device_id}")
def get_device(device_id: int, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
return _out(_get(db, device_id), db)
+107 -89
View File
@@ -16,14 +16,24 @@ PUT /api/kds/orders/{order_id}/items/{item_id}/kds_status
PUT /api/kds/orders/{order_id}/order_type
Update an order's type (here|takeaway|delivery).
--- Legacy endpoint kept for backward compat (printer-zone grouped items) ---
GET /api/kds/items (unchanged)
PUT /api/kds/orders/{order_id}/items/{item_id}/status (unchanged)
GET /api/kds/context
What a kitchen screen needs besides its orders: its settings (device config), its prep
zone, the prep zones and the courses (plan step 3.2a).
POST /api/kds/orders/{order_id}/retry-print
Print the order's unprinted items again (the KDS can't reach /api/orders, 3.2a).
Kitchen screens (plan step 3.2a): a call from a paired device running the KDS uses that
device's settings. GET /orders returns the screen's prep zone (every zone when it has none;
a zone_id sent by the screen is ignored), /print defaults to it, and messages to waiters are signed
with the zone's notification name (else its name, else the screen's name). Calls from the
manager's KDS page (no device) keep choosing the zone themselves.
"""
from core.access.queries import holders_filter
from core.errors import XeniaError
from core.timeutil import utcnow
import json
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from datetime import datetime, timezone
from sqlalchemy.orm import Session, joinedload
from pydantic import BaseModel
@@ -33,11 +43,12 @@ from database import get_db
from models.order import Order, OrderItem, OrderWaiter
from models.product import Product, ProductPreferenceSet
from models.prep_zone import PrepZone
from models.printer import Printer
from models.table import Table
from models.user import User
from models.message import StaffMessage, StaffMessageAck
from models.shift import WaiterShift
from core.access.context import current_device
from core.modules import device_config
from routers.deps import get_current_user, require_kds
from services.sse_bus import broadcast_sync
@@ -49,6 +60,34 @@ VALID_ORDER_TYPES = {"here", "takeaway", "delivery"}
# ─────────────────────────── helpers ───────────────────────────────────────
def _kds_device(request: Request, db: Session):
"""The calling kitchen screen (a paired device running the KDS), or None."""
dev = current_device(request, db)
return dev if dev is not None and dev.app_key == "kds" else None
def _screen_settings(dev, db: Session) -> dict:
"""A KDS device's effective settings; the defaults when there is no device."""
return device_config.effective(device_config.for_app("kds"), dev.config if dev else None, db)
def _device_zone_id(request: Request, db: Session) -> Optional[int]:
dev = _kds_device(request, db)
return _screen_settings(dev, db)["prep_zone_id"] if dev else None
def _sender(request: Request, db: Session, sent: Optional[str]) -> str:
"""How waiters see who sent a KDS message. A kitchen screen signs with its zone's
notification name (else the zone's name, else the screen's name); the manager's page
sends its own."""
dev = _kds_device(request, db)
if dev is None:
return sent or "Κουζίνα"
zid = _screen_settings(dev, db)["prep_zone_id"]
zone = db.get(PrepZone, zid) if zid else None
return (zone.notification_name or zone.name) if zone else dev.name
def _resolve_item_modifiers(item: OrderItem, product: Product | None, db: Session):
"""
Returns a dict with four lists:
@@ -209,14 +248,18 @@ def _sync_order_kds_status(order: Order):
@router.get("/orders")
def kds_orders(
request: Request,
zone_id: Optional[int] = Query(default=None, description="Filter orders to only those containing items in this prep zone"),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Return all open/partially_paid/paid orders that still have unserved items.
If zone_id is provided, only orders containing at least one item belonging to that prep zone are returned,
and items not in that zone are stripped from the payload.
and items not in that zone are stripped from the payload. A kitchen screen with a prep zone
gets its own zone, or every zone when it has none (zone_id is ignored).
"""
if _kds_device(request, db) is not None:
zone_id = _device_zone_id(request, db)
open_orders = (
db.query(Order)
.filter(Order.status.in_(["open", "partially_paid", "paid"]))
@@ -433,13 +476,17 @@ class KdsPrintBody(BaseModel):
def kds_print_order(
order_id: int,
body: KdsPrintBody,
request: Request,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Print order to zone printers. mode=primary prints to first printer, mode=all prints to all."""
"""Print order to zone printers. mode=primary prints to first printer, mode=all prints to all.
A kitchen screen's own zone is the default zone."""
from services import printer_service
if body.mode == "none":
return {"printed": 0}
if body.zone_id is None:
body.zone_id = _device_zone_id(request, db)
if body.printer_id is not None:
# Direct printer specified
result = printer_service.print_to_printer(order_id, body.item_ids, body.printer_id, body.copies, db)
@@ -589,6 +636,7 @@ class KdsCallWaiterBody(BaseModel):
def kds_notify_order_complete(
order_id: int,
body: KdsNotifyBody,
request: Request,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
@@ -605,7 +653,7 @@ def kds_notify_order_complete(
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
table_name = tables_map.get(order.table_id, str(order.table_id)) if order.table_id else "Takeaway"
zone = body.kds_zone or "Κουζίνα"
zone = _sender(request, db, body.kds_zone)
msg_body = (
f"Η παραγγελία #{order.id} για το τραπέζι {table_name} "
@@ -629,6 +677,7 @@ class KdsNotifyItemsBody(BaseModel):
def kds_notify_items_ready(
order_id: int,
body: KdsNotifyItemsBody,
request: Request,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
@@ -645,7 +694,7 @@ def kds_notify_items_ready(
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
table_name = tables_map.get(order.table_id, str(order.table_id)) if order.table_id else "Takeaway"
zone = body.kds_zone or "Κουζίνα"
zone = _sender(request, db, body.kds_zone)
msg_body = (
f"{body.ready_count} αντικείμενα από την παραγγελία #{order.id} "
@@ -663,6 +712,7 @@ def kds_notify_items_ready(
def kds_call_waiter_order(
order_id: int,
body: KdsNotifyBody,
request: Request,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
@@ -679,7 +729,7 @@ def kds_call_waiter_order(
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
table_name = tables_map.get(order.table_id, str(order.table_id)) if order.table_id else "Takeaway"
zone = body.kds_zone or "Κουζίνα"
zone = _sender(request, db, body.kds_zone)
msg_body = (
f"Παραγγελία #{order.id} - τραπέζι {table_name} "
@@ -696,6 +746,7 @@ def kds_call_waiter_order(
@router.post("/call-waiter-general")
def kds_call_waiter_general(
body: KdsCallWaiterBody,
request: Request,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
@@ -703,7 +754,7 @@ def kds_call_waiter_general(
if not body.waiter_ids:
raise HTTPException(status_code=400, detail="waiter_ids must not be empty")
zone = body.kds_zone or "Κουζίνα"
zone = _sender(request, db, body.kds_zone)
msg_body = f"Κλήση από {zone}"
_save_and_broadcast_message(
db, user.id, msg_body, body.waiter_ids,
@@ -733,93 +784,60 @@ def kds_on_shift_waiters(
]
# ─────────────────────────── legacy endpoints ──────────────────────────────
# ─────────────────────────── kitchen screens (3.2a) ────────────────────────
class ItemStatusUpdate(BaseModel):
status: str # only "ready" is accepted
@router.get("/items")
def kds_items(
@router.get("/context")
def kds_context(
request: Request,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Legacy: return active order items grouped by printer zone."""
open_orders = db.query(Order).filter(Order.status.in_(["open", "partially_paid"])).all()
order_ids = [o.id for o in open_orders]
if not order_ids:
return {"zones": []}
"""What a kitchen screen needs besides its orders, through the KDS's own scope: its
settings (device config, effective), its zone, the prep zones (names, sorting, bypass
flags) and the courses. The screen used /api/prep-zones (manager only) and
/api/settings/ for these. On the manager's page (no device): the default settings."""
from models.settings import PosSettings
dev = _kds_device(request, db)
settings = _screen_settings(dev, db)
zones = db.query(PrepZone).order_by(PrepZone.id).all()
stored = {r.key: r.value for r in db.query(PosSettings).filter(
PosSettings.key.in_(("orders.courses_enabled", "orders.courses"))).all()}
courses_enabled = stored.get("orders.courses_enabled", "false") == "true"
try:
courses = json.loads(stored.get("orders.courses") or "[]") if courses_enabled else []
except ValueError:
courses = []
order_map = {o.id: o for o in open_orders}
items = db.query(OrderItem).filter(
OrderItem.order_id.in_(order_ids),
OrderItem.status == "active",
).order_by(OrderItem.added_at.asc()).all()
def zone_out(z):
return {"id": z.id, "name": z.name, "notification_name": z.notification_name,
"sort_items_by": z.sort_items_by or "order_time", "bypass_pending": bool(z.bypass_pending),
"auto_ready_to_served": bool(z.auto_ready_to_served)}
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
printers_map = {p.id: p.name for p in db.query(Printer).all()}
zones: dict = {}
def _zone_key(zone_id):
return 0 if zone_id is None else zone_id
def _zone_name(zone_id):
if zone_id is None:
return "Χωρίς Ζώνη"
return printers_map.get(zone_id, f"Ζώνη #{zone_id}")
for item in items:
product = item.product
zone_id = None # legacy per-product printer is gone (routing is by prep zone); one group, as before
zkey = _zone_key(zone_id)
if zkey not in zones:
zones[zkey] = {"zone_id": zone_id, "zone_name": _zone_name(zone_id), "items": []}
order = order_map.get(item.order_id)
table_name = tables_map.get(order.table_id) if order and order.table_id else None
zones[zkey]["items"].append({
"id": item.id,
"order_id": item.order_id,
"table_name": table_name,
"product_name": product.name if product else f"#{item.product_id}",
"quantity": item.quantity,
"notes": item.notes,
"added_at": item.added_at,
"status": item.status,
})
zone_list = sorted(zones.values(), key=lambda z: (z["zone_id"] is None, z["zone_id"] or 0))
return {"zones": zone_list}
zone = next((z for z in zones if z.id == settings["prep_zone_id"]), None)
return {
"device": {"id": dev.id, "name": dev.name} if dev else None,
"settings": settings,
"zone": zone_out(zone) if zone else None,
"prep_zones": [zone_out(z) for z in zones],
"courses_enabled": courses_enabled,
"courses": courses if isinstance(courses, list) else [],
}
@router.put("/orders/{order_id}/items/{item_id}/status")
def update_item_status_legacy(
@router.post("/orders/{order_id}/retry-print")
def kds_retry_print(
order_id: int,
item_id: int,
body: ItemStatusUpdate,
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Legacy: mark an item ready (active → ready)."""
if body.status != "ready":
raise HTTPException(status_code=400, detail="Only 'ready' is a valid status transition via this endpoint")
item = db.query(OrderItem).filter(
OrderItem.id == item_id,
OrderItem.order_id == order_id,
).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if item.status != "active":
raise HTTPException(status_code=400, detail=f"Item is '{item.status}' — only active items can be marked ready")
item.status = "ready"
db.commit()
broadcast_sync("item_status_changed", {
"order_id": order_id,
"item_id": item_id,
"status": "ready",
})
return {"status": "ready", "item_id": item_id}
"""Print the order's unprinted items again (routed by prep zone, like when they were
ordered). The kitchen's copy of POST /api/orders/{id}/retry-print, which a kitchen
screen can't reach (its scope is kds.*)."""
from services.printer_service import route_and_print_sync
order = db.query(Order).filter(Order.id == order_id).first()
if not order:
raise XeniaError("order.not_found", order_id=order_id)
unprinted_ids = [item.id for item in order.items if not item.printed and item.status == "active"]
if not unprinted_ids:
return {"print_results": []}
return {"print_results": route_and_print_sync(order_id, unprinted_ids, db)}
+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
@@ -1,12 +1,13 @@
// Per-device settings of an app, rendered from its manifest (plan step 3.1a): the
// Per-device settings of an app, rendered from its manifest (plan steps 3.1a, 3.2a): the
// fields come from GET /api/platform/modules → device_app.config, the texts from
// modules:<app>.config.<key>.{label,hint,choices.<value>}. The backend validates them
// (validation.device_config). Used by the pair and edit dialogs of DevicesPage.
// modules:<app>.config.<key>.{label,hint,choices.<value>,none} and section headings from
// modules:<app>.config_groups.<group>. The backend validates them (validation.device_config).
// Used by the pair and edit dialogs of DevicesPage.
import { useEffect, useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import { Field, Input, Select, Switch } from '@xenia/ui'
import client from '../../api/client'
import { configValue, refOptions } from './devicesLogic'
import { configGroups, configValue, refOptions } from './devicesLogic'
export default function DeviceConfigFields({ appKey, fields = [], value, onChange, devices = [], selfId = null }) {
const { t } = useTranslation('manager')
@@ -24,38 +25,59 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
const base = key => `modules:${appKey}.config.${key}`
const set = (f, raw) => onChange({ ...value, [f.key]: configValue(f, raw) })
const control = f => {
const label = t(`${base(f.key)}.label`, { defaultValue: f.key })
const hint = t(`${base(f.key)}.hint`, { defaultValue: '' }) || undefined
const v = value?.[f.key]
if (f.type === 'bool') {
return <Switch key={f.key} checked={!!v} onChange={on => set(f, on)} label={label} description={hint} data-config={f.key} />
}
if (f.choices?.length) {
return (
<Field key={f.key} label={label} hint={hint}>
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
options={f.choices.map(c => ({ value: String(c), label: t(`${base(f.key)}.choices.${c}`, { defaultValue: String(c) }) }))} />
</Field>
)
}
if (f.type === 'ref') {
return (
<Field key={f.key} label={label} hint={hint}>
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
options={[{ value: '', label: t(`${base(f.key)}.none`, { defaultValue: t('devices.form.none') }) },
...refOptions(f, { zones, devices, selfId })]} />
</Field>
)
}
if (f.type === 'color') {
return (
<Field key={f.key} label={label} hint={hint}>
<input type="color" value={v || '#000000'} onChange={e => set(f, e.target.value)} data-config={f.key}
className="h-10 w-16 rounded-control border border-line bg-surface cursor-pointer" />
</Field>
)
}
return (
<Field key={f.key} label={label} hint={hint}>
<Input type={f.type === 'int' ? 'number' : 'text'} value={v ?? ''} min={f.min ?? undefined} max={f.max ?? undefined}
onChange={e => set(f, e.target.value)} data-config={f.key} />
</Field>
)
}
const groups = configGroups(fields)
return (
<div className="grid gap-4" data-testid="device-config">
{fields.map(f => {
const label = t(`${base(f.key)}.label`, { defaultValue: f.key })
const hint = t(`${base(f.key)}.hint`, { defaultValue: '' }) || undefined
const v = value?.[f.key]
if (f.type === 'bool') {
return <Switch key={f.key} checked={!!v} onChange={on => set(f, on)} label={label} description={hint} data-config={f.key} />
}
if (f.choices?.length) {
return (
<Field key={f.key} label={label} hint={hint}>
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
options={f.choices.map(c => ({ value: String(c), label: t(`${base(f.key)}.choices.${c}`, { defaultValue: String(c) }) }))} />
</Field>
)
}
if (f.type === 'ref') {
return (
<Field key={f.key} label={label} hint={hint}>
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
options={[{ value: '', label: t('devices.form.none') }, ...refOptions(f, { zones, devices, selfId })]} />
</Field>
)
}
return (
<Field key={f.key} label={label} hint={hint}>
<Input type={f.type === 'int' ? 'number' : 'text'} value={v ?? ''} min={f.min ?? undefined} max={f.max ?? undefined}
onChange={e => set(f, e.target.value)} data-config={f.key} />
</Field>
)
})}
<div className="grid gap-5" data-testid="device-config">
{groups.map(g => (
<section key={g.group ?? '_'} className="grid gap-4" data-config-group={g.group ?? ''}>
{g.group && groups.length > 1 && g.fields.length > 1 && (
<h3 className="text-label font-semibold text-ink-2 uppercase tracking-wide">
{t(`modules:${appKey}.config_groups.${g.group}`, { defaultValue: g.group })}
</h3>
)}
{g.fields.map(control)}
</section>
))}
</div>
)
}
@@ -72,6 +72,19 @@ export function configValue(field, raw) {
return raw == null ? '' : String(raw)
}
/** Fields in sections, in manifest order of each group's first field: [{group, fields}]
* (fields without a group form their own section, 3.2a). */
export function configGroups(fields = []) {
const out = []
for (const f of fields) {
const g = f.group ?? null
let sec = out.find(s => s.group === g)
if (!sec) { sec = { group: g, fields: [] }; out.push(sec) }
sec.fields.push(f)
}
return out
}
/** Options of a `ref` field: prep zones, or live devices of one app ("devices:<app>"). */
export function refOptions(field, { zones = [], devices = [], selfId = null } = {}) {
if (field.choices_from === 'prep_zones') return zones.map(z => ({ value: String(z.id), label: z.name }))
+9 -1
View File
@@ -1,7 +1,7 @@
// Pure logic of the platform pages (plan steps 2.6c, 2.6d, 2.6e).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { configInitial, configValue, deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode, refOptions } from '../src/pages/platform/devicesLogic.js'
import { configGroups, configInitial, configValue, deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode, refOptions } from '../src/pages/platform/devicesLogic.js'
import { moduleState, stoppedBy } from '../src/pages/platform/modulesLogic.js'
import {
approvalState, approvalTarget, canEndSession, canGive, diff, differsFromRole, editorGroups, permLabelKey, resetToRole,
@@ -136,3 +136,11 @@ test('device settings: starting values, typed values, ref options (3.1a)', () =>
assert.deepEqual(refOptions(fields[2], { devices }), [{ value: '1', label: 'Till' }])
assert.deepEqual(refOptions(fields[2], { devices, selfId: 1 }), [])
})
test('config fields in sections, in the order their groups first appear (3.2a)', () => {
const f = (key, group) => ({ key, type: 'bool', default: false, group })
const groups = configGroups([f('zone', 'zone'), f('w', 'board'), f('c', 'age'), f('s', 'board'), f('auto', undefined)])
assert.deepEqual(groups.map(g => [g.group, g.fields.map(x => x.key)]),
[['zone', ['zone']], ['board', ['w', 's']], ['age', ['c']], [null, ['auto']]])
assert.equal(configValue({ type: 'color' }, '#aabbcc'), '#aabbcc')
})
+118
View File
@@ -127,6 +127,118 @@
"bump": "Σήμανση πιάτων ως έτοιμων"
},
"config": {
"prep_zone_id": {
"label": "Ζώνη προετοιμασίας",
"hint": "Η οθόνη δείχνει μόνο τα αντικείμενα αυτής της ζώνης.",
"none": "Όλες οι ζώνες"
},
"card_width": {
"label": "Πλάτος κάρτας",
"hint": "Πλάτος κάθε κάρτας παραγγελίας, σε pixel (200–800)."
},
"font_scale": {
"label": "Μέγεθος κειμένου",
"hint": "Σε ποσοστό: 100 είναι το κανονικό (60–200)."
},
"font_weight": {
"label": "Βάρος γραμματοσειράς",
"hint": "Πάχος γραμμάτων ονομάτων προϊόντων.",
"choices": {
"300": "Λεπτά",
"400": "Κανονικά",
"500": "Μεσαία",
"600": "Ημιέντονα",
"700": "Έντονα",
"800": "Πολύ έντονα"
}
},
"batch_mode": {
"label": "Συγκέντρωση κοινής παραγγελίας",
"hint": "Πώς εμφανίζονται οι παρτίδες όταν ένα τραπέζι παραγγέλνει πολλές φορές στην ίδια παραγγελία.",
"choices": {
"merged": "Μία κάρτα, όλα μαζί",
"grouped": "Μία κάρτα με διαχωριστικά ανά παρτίδα",
"split": "Ξεχωριστή κάρτα ανά παρτίδα"
}
},
"group_items": {
"label": "Ομαδοποίηση αντικειμένων",
"hint": "Συνολική εικόνα των ίδιων αντικειμένων όλων των παραγγελιών (σε αναμονή και σε προετοιμασία).",
"choices": {
"off": "Απενεργοποιημένο",
"floating": "Αιωρούμενο (πάντα ορατό)",
"right_sidebar": "Πλαϊνή στήλη δεξιά",
"left_sidebar": "Πλαϊνή στήλη αριστερά",
"topbar_button": "Κουμπί στη γραμμή τίτλου"
}
},
"group_by_course": {
"label": "Ομαδοποίηση ανά πιάτο σερβιρίσματος",
"hint": "Τα αντικείμενα χωρίς πιάτο εμφανίζονται τελευταία."
},
"combine_modifiers": {
"label": "Συγχώνευση αλλαγών ίδιου τύπου",
"hint": "Π.χ. «− ντομάτα · σάλτσα» σε μία γραμμή."
},
"categories_as_filters": {
"label": "Κατηγορίες ως φίλτρα",
"hint": "Ναι: πολλές κατηγορίες μαζί. Όχι: μία κατηγορία κάθε φορά."
},
"age_warning_minutes": {
"label": "Προειδοποίηση μετά από (λεπτά)",
"hint": "Η κάρτα παίρνει το χρώμα προειδοποίησης."
},
"age_late_minutes": {
"label": "Καθυστέρηση μετά από (λεπτά)",
"hint": "Η κάρτα παίρνει το χρώμα καθυστέρησης. Περισσότερα από την προειδοποίηση."
},
"age_flash_minutes": {
"label": "Αναβόσβημα μετά από (λεπτά)",
"hint": "Η κεφαλίδα της κάρτας αναβοσβήνει. Περισσότερα από την καθυστέρηση."
},
"flash_late": {
"label": "Αναβόσβημα αργοπορημένων παραγγελιών"
},
"colour_fresh": {
"label": "Χρώμα: νέα"
},
"colour_warning": {
"label": "Χρώμα: προειδοποίηση"
},
"colour_late": {
"label": "Χρώμα: καθυστέρηση"
},
"colour_done": {
"label": "Χρώμα: ολοκληρωμένη"
},
"triple_state": {
"label": "Τρία βήματα ανά παραγγελία",
"hint": "Αναμονή → Προετοιμασία → Έτοιμη. Όχι: παραλείπεται η Προετοιμασία."
},
"sound": {
"label": "Ήχος για νέες παραγγελίες"
},
"notify_order_complete": {
"label": "Ειδοποίηση σερβιτόρου όταν ολοκληρωθεί η παραγγελία"
},
"notify_item_complete": {
"label": "Ειδοποίηση σερβιτόρου όταν ολοκληρωθεί αντικείμενο",
"hint": "Πριν ολοκληρωθεί όλη η παραγγελία."
},
"refresh_seconds": {
"label": "Έλεγχος για παραγγελίες κάθε",
"hint": "Σε περίπτωση που χαθεί μια ζωντανή ενημέρωση.",
"choices": {
"10": "10 δευτερόλεπτα",
"15": "15 δευτερόλεπτα",
"20": "20 δευτερόλεπτα",
"30": "30 δευτερόλεπτα",
"45": "45 δευτερόλεπτα",
"60": "1 λεπτό",
"90": "90 δευτερόλεπτα",
"120": "2 λεπτά"
}
},
"auto_sign_out_minutes": {
"label": "Αποσύνδεση μετά από",
"hint": "Επιστροφή στην οθόνη σύνδεσης όταν κανείς δεν έχει χρησιμοποιήσει την οθόνη για τόσο χρόνο.",
@@ -139,6 +251,12 @@
"60": "1 ώρα"
}
}
},
"config_groups": {
"zone": "Ζώνη προετοιμασίας",
"board": "Πίνακας",
"age": "Χρόνος αναμονής",
"behaviour": "Συμπεριφορά"
}
},
"menu_tablet": {
+118
View File
@@ -127,6 +127,118 @@
"bump": "Mark items ready"
},
"config": {
"prep_zone_id": {
"label": "Prep zone",
"hint": "The screen shows only the items of this zone.",
"none": "All zones"
},
"card_width": {
"label": "Card width",
"hint": "Width of each order card, in pixels (200–800)."
},
"font_scale": {
"label": "Text size",
"hint": "In percent: 100 is normal (60–200)."
},
"font_weight": {
"label": "Text weight",
"hint": "How bold product names are.",
"choices": {
"300": "Light",
"400": "Regular",
"500": "Medium",
"600": "Semibold",
"700": "Bold",
"800": "Extra bold"
}
},
"batch_mode": {
"label": "Repeat orders from one table",
"hint": "How a table's later rounds on the same order are shown.",
"choices": {
"merged": "One card, everything together",
"grouped": "One card, a divider per round",
"split": "A separate card per round"
}
},
"group_items": {
"label": "Item totals",
"hint": "A summary of the same items across all orders (to do and in progress).",
"choices": {
"off": "Off",
"floating": "Floating panel",
"right_sidebar": "Panel on the right",
"left_sidebar": "Panel on the left",
"topbar_button": "Button in the top bar"
}
},
"group_by_course": {
"label": "Group items by course",
"hint": "Items without a course come last."
},
"combine_modifiers": {
"label": "Combine changes of the same kind",
"hint": "For example \"no tomato · sauce\" on one line."
},
"categories_as_filters": {
"label": "Categories as filters",
"hint": "On: several categories at once. Off: one category at a time."
},
"age_warning_minutes": {
"label": "Warning after (minutes)",
"hint": "The card turns to the warning colour."
},
"age_late_minutes": {
"label": "Late after (minutes)",
"hint": "The card turns to the late colour. More than the warning."
},
"age_flash_minutes": {
"label": "Flash after (minutes)",
"hint": "The card header flashes. More than late."
},
"flash_late": {
"label": "Flash late orders"
},
"colour_fresh": {
"label": "Colour: new"
},
"colour_warning": {
"label": "Colour: warning"
},
"colour_late": {
"label": "Colour: late"
},
"colour_done": {
"label": "Colour: done"
},
"triple_state": {
"label": "Three steps per order",
"hint": "To do → In progress → Done. Off: In progress is skipped."
},
"sound": {
"label": "Sound for new orders"
},
"notify_order_complete": {
"label": "Tell the waiter when an order is done"
},
"notify_item_complete": {
"label": "Tell the waiter when an item is done",
"hint": "Before the whole order is done."
},
"refresh_seconds": {
"label": "Check for orders every",
"hint": "In case a live update is missed.",
"choices": {
"10": "10 seconds",
"15": "15 seconds",
"20": "20 seconds",
"30": "30 seconds",
"45": "45 seconds",
"60": "1 minute",
"90": "90 seconds",
"120": "2 minutes"
}
},
"auto_sign_out_minutes": {
"label": "Sign out after",
"hint": "Back to the sign-in screen when nobody has used the screen for this long.",
@@ -139,6 +251,12 @@
"60": "1 hour"
}
}
},
"config_groups": {
"zone": "Prep zone",
"board": "Board",
"age": "Waiting time",
"behaviour": "Behaviour"
}
},
"menu_tablet": {
+6 -1
View File
@@ -186,6 +186,11 @@ try {
r.check('devices: the code is normalized as typed (lower case, dash)', await dlg.getByLabel('Code shown on the device').inputValue() === req.code)
await dlg.getByLabel('How staff sign in').selectOption('pin')
await dlg.getByLabel('Sign out after').selectOption('10')
r.check('devices: the kitchen screen settings come in sections, prep zone "All zones" by default (3.2a)',
await dlg.locator('[data-config-group]').count() >= 4
&& (await dlg.getByLabel('Prep zone').locator('option:checked').textContent()) === 'All zones'
&& await dlg.locator('input[type="color"]').count() === 4)
await dlg.getByLabel('Text size').fill('110')
await dlg.getByRole('button', { name: 'Pair a device' }).click()
await page.waitForFunction(() => document.querySelectorAll('[data-testid^="device-"][data-status]').length === 1, null, { timeout: 8000 }).catch(() => {})
const row = page.locator('[data-testid^="device-"][data-status]').first()
@@ -193,7 +198,7 @@ try {
const deviceToken = await devicePicksUpToken(req)
const me = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
r.check('devices: the device got its token and runs the kitchen display', me.app_key === 'kds' && me.name === 'Kitchen' && me.login_mode === 'pin', JSON.stringify(me))
r.check('devices: the app setting chosen when pairing reaches the device (3.1a)', me.config?.auto_sign_out_minutes === 10, JSON.stringify(me.config))
r.check('devices: the app setting chosen when pairing reaches the device (3.1a)', me.config?.auto_sign_out_minutes === 10 && me.config?.font_scale === 110, JSON.stringify(me.config))
await page.reload()
await row.waitFor({ timeout: 10_000 })
r.check('devices: after it connected → "Online", sign-in PIN', await row.getAttribute('data-status') === 'online' && (await row.textContent()).includes('PIN'))
+4
View File
@@ -66,6 +66,10 @@ try {
r.check('not LAN: :8082 refuses (403)', statusFrom(WAN, `http://${wanIp}:8082/`) === 403)
r.check('not LAN: :8081 refuses too (control)', statusFrom(WAN, `http://${wanIp}:8081/`) === 403)
// Leave the non-LAN network first: with it attached, host traffic to the published ports
// can arrive through its gateway after the restart below and get 403 (seen once in 3.2a)
docker('network', 'disconnect', '-f', WAN, proxy)
// An older docker-compose.yml without the terminal service must not take the proxy down
stack.compose('rm', '-sf', 'terminal')
stack.compose('restart', 'proxy')
+56
View File
@@ -3,6 +3,7 @@
// Backend :8059 (demo DB, licensing off), terminal Vite :5187 proxied to it.
// - pairing through the real screen (code shown → paired from the manager's side)
// - sign-in modes: PIN (wrong PIN first), tap your name, password; sign out
// - 3.2a: the screen's prep zone is enforced, and every KDS call passes the device scope
// - app turned off → "turned off" screen → on again, live
// - device moved to another app → its user is signed out
// - a customer display (no sign-in) goes straight into its app
@@ -83,6 +84,61 @@ try {
sessions.some(s => s.user_id === chef.id && s.client === 'terminal' && s.device_id === kitchen.id), JSON.stringify(sessions.map(s => [s.user_id, s.client, s.device_id])))
await page.reload()
r.check('reload keeps the screen paired and the chef signed in', await shown(page, 'app-kds'))
// ── 3.2a: the screen's prep zone and the KDS's own scope ─────────────────
const grill = await api('POST', '/api/prep-zones', { token: boss, body: { name: 'Grill', notification_name: 'Grill station' } })
const bar = await api('POST', '/api/prep-zones', { token: boss, body: { name: 'Bar' } })
// a waiter orders one product for each zone (the demo's orders are all closed)
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
const maria = (await api('POST', '/api/auth/login', { body: { client: 'waiter', username: 'demo_maria', pin: '3302' } })).access_token
await api('POST', '/api/shifts/start', { token: maria, body: {} }).catch(() => {})
const table = (await api('GET', '/api/tables/', { token: boss })).find(t => !t.open_order_id && !t.current_order_id)
const opened = await api('POST', '/api/orders/', { token: maria, body: { table_id: table.id } })
const [p1, p2] = (await api('GET', '/api/products/', { token: boss })).filter(p => p.is_active !== false)
await api('POST', '/api/products/bulk-prep-zones', { token: boss, body: { product_ids: [p1.id], prep_zone_ids: [grill.id] } })
await api('POST', '/api/products/bulk-prep-zones', { token: boss, body: { product_ids: [p2.id], prep_zone_ids: [bar.id] } })
await api('POST', `/api/orders/${opened.id}/items`, { token: maria, body: { items: [p1, p2].map(p => ({ product_id: p.id, quantity: 1 })) } })
await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { config: { prep_zone_id: grill.id, font_scale: 120 } } })
const order = (await api('GET', '/api/kds/orders', { token: boss })).orders.find(o => o.id === opened.id)
const calls = [
['get', '/api/kds/context'],
['get', '/api/kds/orders'],
['get', `/api/kds/orders?zone_id=${bar.id}`],
['get', '/api/kds/on-shift-waiters'],
['put', `/api/kds/orders/${order.id}/items/${order.items[0].id}/kds_status`, { status: 'preparing' }],
['put', `/api/kds/orders/${order.id}/kds_status`, { status: 'preparing' }],
['post', `/api/kds/orders/${order.id}/notify-items-ready`, { ready_count: 1, total_count: 2 }],
['post', `/api/kds/orders/${order.id}/notify-complete`, {}],
['post', `/api/kds/orders/${order.id}/call-waiter`, {}],
['post', `/api/kds/orders/${order.id}/retry-print`],
['put', `/api/kds/orders/${order.id}/kds_status`, { status: 'pending' }],
]
// every call the kitchen screen makes, through the screen's own client (device header + chef's session)
const answers = await page.evaluate(async list => {
const out = []
for (const [method, url, body] of list) {
try {
const res = await window.__xeniaClient[method](url, body)
out.push({ url, status: res.status, data: res.data })
} catch (e) {
out.push({ url, status: e.response?.status ?? 0, code: e.response?.data?.error?.code })
}
}
return out
}, calls)
const refused = answers.filter(a => a.status >= 400)
r.check('3.2a: no call the kitchen screen makes is refused (device scope kds.*)', refused.length === 0, JSON.stringify(refused))
const ctx = answers[0].data ?? {}
r.check('3.2a: the screen gets its zone and settings from /api/kds/context',
ctx.zone?.name === 'Grill' && ctx.settings?.font_scale === 120 && ctx.prep_zones?.length >= 2, JSON.stringify(ctx).slice(0, 300))
const items = answers.slice(1, 3).flatMap(a => (a.data?.orders ?? []).flatMap(o => o.items))
r.check('3.2a: it only ever gets its own zone\'s items, even when it asks for another zone',
items.length > 0 && items.every(i => i.prep_zone_ids.includes(grill.id)), `${items.length} items`)
const outside = await page.evaluate(async () => {
try { await window.__xeniaClient.get('/api/prep-zones'); return 'allowed' } catch (e) { return e.response?.data?.error?.code }
})
r.check('3.2a: what the old page used instead (/api/prep-zones) stays out of its scope', outside === 'device.out_of_scope', outside)
await page.getByRole('button', { name: 'Sign out' }).click()
r.check('sign out → back to the names', await shown(page, 'user-grid'))