Files
xenia-pos-local/local_backend/core/modules/device_config.py
T
bonaminandClaude Opus 5.5 27d7bbb976 feat(backend): customer display looks on the media library, one per display (platform-v2 step 5.3)
- display_looks (Alembic 0028): named idle screens, one default; config is
  the 3.4 design with pictures as media library ids. 0028 turns the setting
  customer_display.idle into the look "Main" and moves its data/display_media
  pictures into the library (the old folder stays on disk).
- A display shows the look in its device config `look` (ref ConfigField,
  choices_from "display_looks", validated in device_config) or the default.
- /api/display/looks (GET also for core.devices.manage), POST, PUT,
  POST /{id}/default, DELETE (not the default; its displays go back to it);
  /api/display/displays and PUT /displays/{id}/look. A change sends
  display.settings only to the displays showing that look.
- /api/display/settings, /api/display/media* and their error codes are gone;
  GET /api/display/state keeps its shape (logo card size, image/slides full).
- Looks register their media usage (a picture in a look can't be deleted).
- tests: test_customer_display.py (7, incl. two displays two slideshows and
  the 0028 data move); 501 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:50:51 +02:00

137 lines
5.4 KiB
Python

"""Per-device settings of an app (plan step 3.1a): what the manager may store in
devices.config and what the device reads back.
- validate(fields, config, db) -> dict | None: the cleaned config to store. Unknown keys,
wrong types, values outside choices/min/max and refs to missing rows raise
validation.device_config {key}. None/{} -> None (all defaults).
- effective(fields, stored, db=None) -> dict: every field, its stored value when still
valid, else its default. What GET /api/devices/me returns, so a screen never handles
a missing or stale value (an old free-form config, a prep zone that was deleted).
- for_app(app_key) -> the app's ConfigFields (from its manifest's DeviceApp.config).
Agent notes:
- Fields are declared in the app's manifest (core/modules/model.py ConfigField). A new
field needs its label in packages/i18n/locales/{en,el}/modules.json
(`<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), "categories" (Category ids), "printers" (active
Printer 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:
from core.access.context import device_app
da = device_app(app_key)
return tuple(da.config) if da else ()
def _bad(key: str):
return XeniaError("validation.device_config", key=key)
def _ref_exists(source: str, value: int, db) -> bool:
if source == "prep_zones":
from models.prep_zone import PrepZone
return db.get(PrepZone, value) is not None
if source == "categories":
from models.product import Category
return db.get(Category, value) is not None
if source == "printers":
from models.printer import Printer
p = db.get(Printer, value)
return p is not None and bool(p.is_active)
if source == "display_looks":
from models.display_look import DisplayLook
return db.get(DisplayLook, value) is not None
if source.startswith("devices:"):
from models.device import Device
d = db.get(Device, value)
return d is not None and d.revoked_at is None and d.app_key == source.split(":", 1)[1]
return False
def _clean(f, value, db, *, strict: bool):
"""The value as stored, or raise (strict) / return the default (not strict)."""
def bad():
if strict:
raise _bad(f.key)
return f.default
if f.type == "bool":
return value if isinstance(value, bool) else bad()
if f.type == "int":
if isinstance(value, bool) or not isinstance(value, int):
return bad()
if (f.choices and value not in f.choices) or (f.min is not None and value < f.min) \
or (f.max is not None and value > f.max):
return bad()
return value
if f.type == "str":
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
if isinstance(value, bool) or not isinstance(value, int):
return bad()
if db is not None and not _ref_exists(f.choices_from or "", value, db):
return bad()
return value
return bad()
def validate(fields, config, db) -> dict | None:
if config is None:
return None
if not isinstance(config, dict):
raise _bad("config")
by_key = {f.key: f for f in fields}
out = {}
for key, value in config.items():
f = by_key.get(key)
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 {}
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, "group": f.group, "after": f.after}
for f in fields]