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
+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)}