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:
@@ -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]
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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'),
|
||||
),
|
||||
|
||||
@@ -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
@@ -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)}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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")
|
||||
@@ -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}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user