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>
This commit is contained in:
@@ -1,53 +1,50 @@
|
||||
"""The customer display (plan step 3.4): a screen facing the customer, linked to a counter POS.
|
||||
"""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,
|
||||
the idle screen, the venue's name
|
||||
its 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):
|
||||
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/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
|
||||
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 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 fastapi import APIRouter, Depends, Response
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.access.deps import public, require, require_device
|
||||
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"
|
||||
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
|
||||
@@ -59,9 +56,9 @@ _lock = threading.Lock()
|
||||
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)
|
||||
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)
|
||||
@@ -82,6 +79,21 @@ class IdleBody(BaseModel):
|
||||
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")
|
||||
@@ -97,7 +109,7 @@ class StateBody(BaseModel):
|
||||
change: Optional[float] = Field(default=None, ge=0, le=100000)
|
||||
|
||||
|
||||
# ── helpers ────────────────────────────────────────────────────────────────────
|
||||
# ── looks ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _setting(db, key: str, default: str = "") -> str:
|
||||
from models.settings import PosSettings
|
||||
@@ -105,26 +117,49 @@ def _setting(db, key: str, default: str = "") -> str:
|
||||
return row.value if row and row.value is not None else default
|
||||
|
||||
|
||||
def idle_settings(db) -> dict:
|
||||
def config_of(look: DisplayLook | None) -> dict:
|
||||
raw = (look.config if look is not None else None) or {}
|
||||
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()
|
||||
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 _media_names() -> list[str]:
|
||||
try:
|
||||
return sorted(n for n in os.listdir(MEDIA_DIR) if NAME.match(n))
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
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 media_url(name: str | None) -> str | None:
|
||||
return f"/api/display/media/{name}" if name else None
|
||||
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:
|
||||
@@ -137,29 +172,77 @@ def _qr_link(cfg: dict) -> str | None:
|
||||
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 _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))]
|
||||
|
||||
|
||||
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."""
|
||||
@@ -182,77 +265,100 @@ def display_state(db: Session = Depends(get_db), dev=Depends(require_device("cus
|
||||
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),
|
||||
"idle": idle_out(db, look_of(db, dev)),
|
||||
"state": state or {"mode": "idle", "lines": [], "total": 0.0, "paid": None, "change": None}}
|
||||
|
||||
|
||||
# ── the venue's settings and images ────────────────────────────────────────────
|
||||
# ── the venue's looks ──────────────────────────────────────────────────────────
|
||||
|
||||
@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.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.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))
|
||||
@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:
|
||||
row.value = value
|
||||
cfg = IdleBody()
|
||||
_check(db, cfg)
|
||||
look = DisplayLook(name=body.name.strip(), config=cfg.model_dump(), is_default=False)
|
||||
db.add(look)
|
||||
db.commit()
|
||||
displays = _all_displays(db)
|
||||
if displays:
|
||||
broadcast_sync("display.settings", {}, device_ids=displays)
|
||||
return get_settings(db, user)
|
||||
db.refresh(look)
|
||||
return _look_out(db, look)
|
||||
|
||||
|
||||
@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.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.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.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.get("/media/{name}", dependencies=[Depends(public())])
|
||||
def get_media(name: str):
|
||||
"""The image itself: the displays load it with a plain <img> (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"})
|
||||
@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}
|
||||
|
||||
Reference in New Issue
Block a user