"""The customer display (plan step 3.4): 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, the idle screen, the venue's name What the display shows while idle is the venue's choice (owner, 2026-11-16: "configurable, so each venue can choose their style"): 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. Setting `customer_display.idle` (JSON, IdleBody); images are files the venue uploads here (data/display_media, served to the displays by name): GET /api/display/settings (customer_display.manage) the idle screen + the uploaded images PUT /api/display/settings save it → `display.settings` to every display POST /api/display/media upload an image (jpg/png/webp/gif, ≤ 5 MB) DELETE /api/display/media/{name} GET /api/display/media/{name} (public, LAN) the image itself 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 json import os import re import threading import uuid from typing import List, Literal, Optional from fastapi import APIRouter, Depends, File, UploadFile from fastapi.responses import FileResponse from pydantic import BaseModel, Field, field_validator from sqlalchemy.orm import Session from core.access.deps import public, require, require_device from core.errors import XeniaError from database import get_db from services.ws_bus import broadcast_sync router = APIRouter() KEY = "customer_display.manage" SETTING = "customer_display.idle" MEDIA_DIR = os.environ.get("XENIA_DISPLAY_MEDIA_DIR", "/app/data/display_media") MAX_BYTES = 5 * 1024 * 1024 TYPES = {"image/jpeg": "jpg", "image/png": "png", "image/webp": "webp", "image/gif": "gif"} NAME = re.compile(r"^[0-9a-f]{32}\.(jpg|png|webp|gif)$") 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[str] = None # an uploaded image's name image: Optional[str] = None slides: List[str] = Field(default_factory=list, max_length=20) 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 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) # ── helpers ──────────────────────────────────────────────────────────────────── 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 idle_settings(db) -> dict: try: raw = json.loads(_setting(db, SETTING, "{}") or "{}") except ValueError: raw = {} try: return IdleBody(**{k: v for k, v in (raw or {}).items() if k in IdleBody.model_fields}).model_dump() except Exception: return IdleBody().model_dump() def _media_names() -> list[str]: try: return sorted(n for n in os.listdir(MEDIA_DIR) if NAME.match(n)) except FileNotFoundError: return [] def media_url(name: str | None) -> str | None: return f"/api/display/media/{name}" if name 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 idle_out(db) -> dict: """The idle screen as a display shows it: the settings with image addresses and the QR link.""" cfg = idle_settings(db) have = set(_media_names()) keep = lambda n: n if n in have else None # noqa: E731 (a deleted image just disappears) return {**cfg, "logo_url": media_url(keep(cfg["logo"])), "image_url": media_url(keep(cfg["image"])), "slide_urls": [media_url(n) for n in cfg["slides"] if n in have], "qr_link": _qr_link(cfg) if cfg["style"] == "qr" else None} 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))] def _all_displays(db) -> list[int]: from models.device import Device return [i for (i,) in db.query(Device.id).filter(Device.app_key == "customer_display", Device.revoked_at.is_(None))] # ── the POS and the display ──────────────────────────────────────────────────── @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), "state": state or {"mode": "idle", "lines": [], "total": 0.0, "paid": None, "change": None}} # ── the venue's settings and images ──────────────────────────────────────────── @router.get("/settings") def get_settings(db: Session = Depends(get_db), user=Depends(require(KEY))): return {"idle": idle_settings(db), "media": [{"name": n, "url": media_url(n)} for n in _media_names()], "preview": idle_out(db), "venue_name": _setting(db, "venue.name", "") or None} @router.put("/settings") def put_settings(body: IdleBody, db: Session = Depends(get_db), user=Depends(require(KEY))): from models.settings import PosSettings have = set(_media_names()) for name in [body.logo, body.image, *body.slides]: if name and name not in have: raise XeniaError("display.media_unknown", name=name) if body.style == "qr" and body.qr_target == "custom" and not body.qr_url: raise XeniaError("display.qr_url_missing") row = db.query(PosSettings).filter(PosSettings.key == SETTING).first() value = json.dumps(body.model_dump()) if row is None: db.add(PosSettings(key=SETTING, value=value)) else: row.value = value db.commit() displays = _all_displays(db) if displays: broadcast_sync("display.settings", {}, device_ids=displays) return get_settings(db, user) @router.post("/media", status_code=201) async def upload_media(file: UploadFile = File(...), user=Depends(require(KEY))): ext = TYPES.get((file.content_type or "").lower()) if ext is None: raise XeniaError("display.media_type") data = await file.read(MAX_BYTES + 1) if len(data) > MAX_BYTES: raise XeniaError("display.media_too_big", max_mb=MAX_BYTES // (1024 * 1024)) os.makedirs(MEDIA_DIR, exist_ok=True) name = f"{uuid.uuid4().hex}.{ext}" with open(os.path.join(MEDIA_DIR, name), "wb") as f: f.write(data) return {"name": name, "url": media_url(name)} @router.delete("/media/{name}", status_code=204) def delete_media(name: str, db: Session = Depends(get_db), user=Depends(require(KEY))): if not NAME.match(name) or name not in _media_names(): raise XeniaError("display.media_unknown", name=name) os.remove(os.path.join(MEDIA_DIR, name)) cfg = idle_settings(db) # drop it from the idle screen too if name in (cfg["logo"], cfg["image"]) or name in cfg["slides"]: cfg["logo"] = None if cfg["logo"] == name else cfg["logo"] cfg["image"] = None if cfg["image"] == name else cfg["image"] cfg["slides"] = [n for n in cfg["slides"] if n != name] from models.settings import PosSettings db.query(PosSettings).filter(PosSettings.key == SETTING).update({PosSettings.value: json.dumps(cfg)}) db.commit() displays = _all_displays(db) if displays: broadcast_sync("display.settings", {}, device_ids=displays) return None @router.get("/media/{name}", dependencies=[Depends(public())]) def get_media(name: str): """The image itself: the displays load it with a plain (no headers). Names are random.""" if not NAME.match(name) or not os.path.exists(os.path.join(MEDIA_DIR, name)): raise XeniaError("display.media_unknown", name=name) return FileResponse(os.path.join(MEDIA_DIR, name), headers={"Cache-Control": "public, max-age=86400"})