Files
xenia-pos-local/local_backend/routers/customer_display.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

365 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The customer display (plan steps 3.4, 5.3): a screen facing the customer, linked to a counter POS.
The POS pushes what the customer should see; the display (paired, sign-in "none") shows it:
POST /api/display/state (the POS screen) {mode: idle|cart|paid, lines, total, paid, change}
→ event `display.state` to the displays linked to this POS only
GET /api/display/state (a display) what to show now: the linked POS's last state,
its idle screen, the venue's name
What a display shows while idle is a **look** the venue designs (owner, 2026-11-16: "configurable,
so each venue can choose their style"; 5.3: each display its own): the name, the logo, both,
nothing, one image, a slideshow of photos, or a QR code (the venue's ordering link, its QR menu,
or any link), with an optional line of text, light or dark. Looks are named (models/display_look.py);
one is the venue's default, and each display shows the look in its device config (`look`) or the
default. Pictures come from the media library (ids; services/media.py), which keeps them while a
look uses them.
GET /api/display/looks the looks (with a preview and the displays using each)
POST /api/display/looks a new look {name, config?, copy_of?}
PUT /api/display/looks/{id} rename / redesign → `display.settings` to its displays
POST /api/display/looks/{id}/default make it the venue's default
DELETE /api/display/looks/{id} not the default; its displays go back to the default
GET /api/display/displays the paired displays and their look
PUT /api/display/displays/{id}/look {look_id | null (= the default)}
The POS's last state is kept in memory (a display that reconnects asks for it); after a restart
the displays show the idle screen until the next sale.
"""
from __future__ import annotations
import re
import threading
from typing import List, Literal, Optional
from fastapi import APIRouter, Depends, Response
from pydantic import BaseModel, Field, field_validator
from sqlalchemy.orm import Session
from core.access.deps import require, require_any, require_device
from core.errors import XeniaError
from database import get_db
from models.display_look import DisplayLook
from services import media as media_store
from services.ws_bus import broadcast_sync
router = APIRouter()
KEY = "customer_display.manage"
STYLES = ("name", "logo", "name_logo", "blank", "image", "slideshow", "qr")
_last: dict[int, dict] = {} # POS device id → its last state
_lock = threading.Lock()
# ── shapes ─────────────────────────────────────────────────────────────────────
class IdleBody(BaseModel):
style: Literal["name", "logo", "name_logo", "blank", "image", "slideshow", "qr"] = "name"
message: Optional[str] = Field(default=None, max_length=120) # a line under the name/logo/QR
logo: Optional[int] = None # media library ids (pictures)
image: Optional[int] = None
slides: List[int] = Field(default_factory=list, max_length=30)
slide_seconds: int = Field(default=8, ge=3, le=120)
qr_target: Literal["ordering", "menu", "custom"] = "ordering"
qr_url: Optional[str] = Field(default=None, max_length=300)
qr_caption: Optional[str] = Field(default=None, max_length=80)
theme: Literal["dark", "light"] = "dark"
@field_validator("qr_url")
@classmethod
def _url(cls, v):
v = (v or "").strip() or None
if v and not re.match(r"^https?://", v):
raise ValueError("a link starts with http:// or https://")
return v
@field_validator("message", "qr_caption")
@classmethod
def _text(cls, v):
return (v or "").strip() or None
class LookCreate(BaseModel):
name: str = Field(min_length=1, max_length=60)
config: Optional[IdleBody] = None
copy_of: Optional[int] = None # start from another look
class LookUpdate(BaseModel):
name: Optional[str] = Field(default=None, min_length=1, max_length=60)
config: Optional[IdleBody] = None
class LookChoice(BaseModel):
look_id: Optional[int] = None # None: the venue's default
class Line(BaseModel):
name: str = Field(max_length=120)
quantity: Optional[float] = Field(default=None, ge=0, le=9999) # None: the name says it ("2× Burger")
total: float = Field(ge=-100000, le=100000)
options: List[str] = Field(default_factory=list, max_length=20)
class StateBody(BaseModel):
mode: Literal["idle", "cart", "paid"]
lines: List[Line] = Field(default_factory=list, max_length=200)
total: float = Field(default=0.0, ge=-100000, le=100000)
paid: Optional[float] = Field(default=None, ge=0, le=100000)
change: Optional[float] = Field(default=None, ge=0, le=100000)
# ── looks ──────────────────────────────────────────────────────────────────────
def _setting(db, key: str, default: str = "") -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row and row.value is not None else default
def config_of(look: DisplayLook | None) -> dict:
raw = (look.config if look is not None else None) or {}
try:
return IdleBody(**{k: v for k, v in raw.items() if k in IdleBody.model_fields}).model_dump()
except Exception:
return IdleBody().model_dump()
def default_look(db) -> DisplayLook:
"""The venue's default look (made if there is none, e.g. a fresh database before 0028's row)."""
look = db.query(DisplayLook).filter(DisplayLook.is_default.is_(True)).first()
if look is None:
look = db.query(DisplayLook).order_by(DisplayLook.id).first()
if look is None:
look = DisplayLook(name="Main", config={})
db.add(look)
look.is_default = True
db.commit()
db.refresh(look)
return look
def look_of(db, dev) -> DisplayLook:
"""The look a display shows: its own (device config `look`) or the venue's default."""
lid = (dev.config or {}).get("look") if dev is not None else None
look = db.get(DisplayLook, lid) if lid else None
return look or default_look(db)
def _pictures(db, ids) -> dict:
from models.media import Media
ids = [i for i in ids if i]
return {m.id: m for m in db.query(Media).filter(Media.id.in_(ids))} if ids else {}
def idle_out(db, look: DisplayLook | None) -> dict:
"""The idle screen as a display shows it: the look with picture addresses and the QR link."""
cfg = config_of(look)
pics = _pictures(db, [cfg["logo"], cfg["image"], *cfg["slides"]])
url = lambda i, size: (media_store.image_of(pics[i]) or {}).get(size) if i in pics else None # noqa: E731
return {**cfg, "logo_url": url(cfg["logo"], "card"), "image_url": url(cfg["image"], "full"),
"slide_urls": [u for u in (url(i, "full") for i in cfg["slides"]) if u],
"qr_link": _qr_link(cfg) if cfg["style"] == "qr" else None}
def _qr_link(cfg: dict) -> str | None:
if cfg["qr_target"] == "custom":
return cfg["qr_url"]
from config import settings
from services.table_qr import apps_url, menu_url
if cfg["qr_target"] == "menu":
return menu_url()
return f"{apps_url()}/order/{settings.SITE_ID or ''}"
def _check(db, cfg: IdleBody) -> None:
pics = _pictures(db, [cfg.logo, cfg.image, *cfg.slides])
for i in [cfg.logo, cfg.image, *cfg.slides]:
if i is None:
continue
if i not in pics:
raise XeniaError("media.not_found", media_id=i)
if pics[i].kind != "image":
raise XeniaError("media.not_a_picture")
if cfg.style == "qr" and cfg.qr_target == "custom" and not cfg.qr_url:
raise XeniaError("display.qr_url_missing")
def _displays(db):
from models.device import Device
return db.query(Device).filter(Device.app_key == "customer_display", Device.revoked_at.is_(None)).order_by(Device.name).all()
def _displays_showing(db, look: DisplayLook) -> list[int]:
"""The displays that show this look (their own, or the default when they have none)."""
out = []
for d in _displays(db):
lid = (d.config or {}).get("look")
mine = lid == look.id or (look.is_default and (not lid or db.get(DisplayLook, lid) is None))
if mine:
out.append(d.id)
return out
def _tell(ids: list[int]) -> None:
if ids:
broadcast_sync("display.settings", {}, device_ids=ids)
def _look_out(db, look: DisplayLook) -> dict:
showing = set(_displays_showing(db, look))
cfg = config_of(look)
pics = _pictures(db, [cfg["logo"], cfg["image"], *cfg["slides"]])
return {"id": look.id, "name": look.name, "is_default": bool(look.is_default), "config": cfg,
"pictures": {str(i): media_store.image_of(m) for i, m in pics.items()}, # for the editor: {id: {name, thumb…}}
"preview": idle_out(db, look),
"displays": [{"id": d.id, "name": d.name} for d in _displays(db) if d.id in showing]}
def _get(db, look_id: int) -> DisplayLook:
look = db.get(DisplayLook, look_id)
if look is None:
raise XeniaError("display.look_unknown", look_id=look_id)
return look
def _uses(db, media_id: int) -> list:
out = []
for look in db.query(DisplayLook).order_by(DisplayLook.name):
cfg = config_of(look)
if media_id in (cfg["logo"], cfg["image"]) or media_id in cfg["slides"]:
out.append({"id": look.id, "name": look.name})
return out
media_store.register_usage("display_look", _uses)
# ── the POS and the display ────────────────────────────────────────────────────
def _displays_of(db, pos_id: int) -> list[int]:
from models.device import Device
return [i for (i,) in db.query(Device.id).filter(Device.app_key == "customer_display", Device.linked_device_id == pos_id,
Device.revoked_at.is_(None))]
@router.post("/state", status_code=204)
def push_state(body: StateBody, db: Session = Depends(get_db), dev=Depends(require_device("pos_counter"))):
"""The counter POS says what its customer should see. Only its own displays hear it."""
state = body.model_dump()
with _lock:
if _last.get(dev.id) == state:
return None
_last[dev.id] = state
displays = _displays_of(db, dev.id)
if displays:
broadcast_sync("display.state", state, device_ids=displays)
return None
@router.get("/state")
def display_state(db: Session = Depends(get_db), dev=Depends(require_device("customer_display"))):
from models.device import Device
pos = db.get(Device, dev.linked_device_id) if dev.linked_device_id else None
with _lock:
state = _last.get(pos.id) if pos is not None else None
return {"venue_name": _setting(db, "venue.name", "") or None,
"linked": pos is not None and pos.revoked_at is None,
"idle": idle_out(db, look_of(db, dev)),
"state": state or {"mode": "idle", "lines": [], "total": 0.0, "paid": None, "change": None}}
# ── the venue's looks ──────────────────────────────────────────────────────────
@router.get("/looks")
def list_looks(db: Session = Depends(get_db), user=Depends(require_any(KEY, "core.devices.manage"))):
"""The looks, default first (also the choices of a display's `look` in the Devices page)."""
default_look(db)
looks = db.query(DisplayLook).order_by(DisplayLook.is_default.desc(), DisplayLook.name).all()
return [_look_out(db, x) for x in looks]
@router.post("/looks", status_code=201)
def create_look(body: LookCreate, db: Session = Depends(get_db), user=Depends(require(KEY))):
default_look(db)
if body.config is not None:
cfg = body.config
elif body.copy_of is not None:
cfg = IdleBody(**config_of(_get(db, body.copy_of)))
else:
cfg = IdleBody()
_check(db, cfg)
look = DisplayLook(name=body.name.strip(), config=cfg.model_dump(), is_default=False)
db.add(look)
db.commit()
db.refresh(look)
return _look_out(db, look)
@router.put("/looks/{look_id}")
def update_look(look_id: int, body: LookUpdate, db: Session = Depends(get_db), user=Depends(require(KEY))):
look = _get(db, look_id)
if body.name is not None:
look.name = body.name.strip()
if body.config is not None:
_check(db, body.config)
look.config = body.config.model_dump()
db.commit()
db.refresh(look)
_tell(_displays_showing(db, look))
return _look_out(db, look)
@router.post("/looks/{look_id}/default")
def make_default(look_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
look = _get(db, look_id)
old = default_look(db)
before = set(_displays_showing(db, old))
for x in db.query(DisplayLook).filter(DisplayLook.is_default.is_(True)):
x.is_default = False
look.is_default = True
db.commit()
_tell(sorted(before | set(_displays_showing(db, look))))
return _look_out(db, look)
@router.delete("/looks/{look_id}", status_code=204)
def delete_look(look_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
look = _get(db, look_id)
if look.is_default:
raise XeniaError("display.look_default")
moved = []
for d in _displays(db):
if (d.config or {}).get("look") == look.id:
d.config = {**(d.config or {}), "look": None}
moved.append(d.id)
db.delete(look)
db.commit()
_tell(moved)
return Response(status_code=204)
@router.get("/displays")
def list_displays(db: Session = Depends(get_db), user=Depends(require(KEY))):
out = []
for d in _displays(db):
lid = (d.config or {}).get("look")
look = db.get(DisplayLook, lid) if lid else None
out.append({"id": d.id, "name": d.name, "look_id": look.id if look else None,
"linked_device_id": d.linked_device_id})
return out
@router.put("/displays/{device_id}/look")
def choose_look(device_id: int, body: LookChoice, db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.device import Device
dev = db.get(Device, device_id)
if dev is None or dev.app_key != "customer_display" or dev.revoked_at is not None:
raise XeniaError("display.not_a_display", device_id=device_id)
if body.look_id is not None:
_get(db, body.look_id)
dev.config = {**(dev.config or {}), "look": body.look_id}
db.commit()
_tell([dev.id])
return {"id": dev.id, "name": dev.name, "look_id": body.look_id, "linked_device_id": dev.linked_device_id}