feat(terminal): the customer display, with an idle screen each venue designs

Plan step 3.4. Owner (2026-11-16): the idle screen is configurable per venue.
- routers/customer_display.py (module customer_display, /api/display): the counter POS
  pushes its state (POST /api/display/state: idle | cart | paid with lines, total, paid,
  change); only the displays linked to that POS get `display.state`; the last state is kept
  in memory for a display that reconnects (GET /api/display/state). pos_counter's device
  scope includes customer_display.state.
- The idle screen: setting customer_display.idle (name, logo, logo + name, blank, one
  image, slideshow, QR code to the online ordering / QR menu / any link; a line of text;
  dark or light); images uploaded to /app/data/display_media (JPG/PNG/WebP/GIF ≤ 5 MB,
  random names, served publicly on the LAN); a change sends `display.settings` to every
  display. New key customer_display.manage (owners, store managers; migration 0022).
- Terminal: CustomerDisplayApp (cart with a large total, "Thank you" with the change for
  12 s, the venue's idle screen, its theme), logic.js (unit-tested); the POS pushes from the
  sale cart and the payment dialog (tables, online orders too) via useDisplay().
  qrcode.react added to the terminal (already in the workspace).
- Manager: Settings → Customer display (style cards, venue name, text, look, slide seconds,
  QR target/link/caption, image upload/pick/order/delete).
- Tests: tests/test_customer_display.py (3), terminal display.test.mjs (3); e2e terminal
  (linked vs unlinked display, < 1 s, paid, QR and slideshow idle screens), manager (the
  settings tab).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 08:34:05 +02:00
co-authored by Claude Opus 5.5
parent 18d580d87c
commit 88a9703902
27 changed files with 1073 additions and 25 deletions
+4
View File
@@ -85,6 +85,10 @@ CODES: dict[str, tuple[int, str]] = {
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
"online.not_found": (404, "Online order {order_id} not found."),
"online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."),
"display.media_unknown": (404, "Image {name} not found."),
"display.media_type": (422, "Upload a JPG, PNG, WebP or GIF image."),
"display.media_too_big": (413, "The image is too big (at most {max_mb} MB)."),
"display.qr_url_missing": (422, "Enter the link the QR code opens."),
"reservation.not_found": (404, "Booking {reservation_id} not found."),
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
"reservation.table_unknown": (404, "Table {table_id} not found."),
@@ -0,0 +1,25 @@
"""key customer_display.manage for owners and store managers (plan step 3.4)
The idle screen is a setting (customer_display.idle) and its images are files, so no table.
Revision ID: 0022_customer_display_key
Revises: 0021_table_qr_token
Create Date: 2026-11-17 10:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0022_customer_display_key'
down_revision = '0021_table_qr_token'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'customer_display.manage' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'customer_display.manage'"))
@@ -1,14 +1,23 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import DeviceApp, Limit, Module
from core.modules.model import DeviceApp, Limit, Module, Mount, Perm, SettingDef
MODULE = Module(
key='customer_display',
kind='app',
name='Customer display',
description='Screen facing the customer at a counter POS (phase 3).',
description='Screen facing the customer at a counter POS: the sale, the total, the change, and an idle screen the venue designs (plan step 3.4).',
depends=('pos_counter',),
permissions=(
Perm('customer_display.manage', 'Set up the customer display (idle screen, images)', roles=('owner', 'store_manager')),
),
limits=(
Limit('devices', 'Number of customer displays', free=0, licensed_default=1),
),
settings=(
SettingDef('customer_display.idle', '{}', 'What customer displays show between sales: style (name, logo, name_logo, blank, image, slideshow, qr), message, images, slide seconds, QR target, theme. Edited in Settings > Customer display.', type='json'),
),
routers=(
Mount('routers.customer_display', '/api/display'),
),
device_app=DeviceApp(login_modes=('none',), scope=()),
)
@@ -27,7 +27,8 @@ MODULE = Module(
limits=(
Limit('devices', 'Number of counter terminals', free=0, licensed_default=1),
),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*', 'connect_orders.*'),
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*', 'connect_orders.*',
'customer_display.state'), # 3.4: it tells its display what to show
config=POS_CONFIG),
routers=(
Mount('routers.pos', '/api/pos'),
+258
View File
@@ -0,0 +1,258 @@
"""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 <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"})
@@ -0,0 +1,107 @@
"""The customer display (plan step 3.4): a POS pushes what its customer sees, only its own
displays hear it; the idle screen is the venue's design (name, logo, both, blank, an image, a
slideshow, a QR code), with images the venue uploads."""
import io
import pytest
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
PNG = (b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
b"\x00\x00\x00\rIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82")
@pytest.fixture(autouse=True)
def media_dir(tmp_path, monkeypatch):
import routers.customer_display as cd
monkeypatch.setattr(cd, "MEDIA_DIR", str(tmp_path / "media"))
cd._last.clear()
return tmp_path / "media"
@pytest.fixture
def counters(client, owner_h, pair):
"""Two counters, each with its own customer display."""
out = {}
for n in (1, 2):
pos_token, pos = pair("pos_counter", f"Till {n}")
disp_token, disp = pair("customer_display", f"Display {n}", linked_device_id=pos.json()["id"])
assert disp.status_code == 201, disp.text
out[n] = {"pos": {"X-Xenia-Device": pos_token}, "display": {"X-Xenia-Device": disp_token},
"pos_id": pos.json()["id"], "display_id": disp.json()["id"]}
return out
@pytest.fixture
def sent(monkeypatch):
import routers.customer_display as cd
got = []
real = cd.broadcast_sync
monkeypatch.setattr(cd, "broadcast_sync", lambda kind, data, **kw: (got.append((kind, data, kw)), real(kind, data, **kw)))
return got
CART = {"mode": "cart", "lines": [{"name": "Freddo", "quantity": 2, "total": 6.0}, {"name": "Toast", "quantity": 1, "total": 3.5,
"options": ["no ham"]}], "total": 9.5}
def test_a_sale_shows_only_on_its_own_display(client, counters, sent):
one, two = counters[1], counters[2]
assert client.post("/api/display/state", headers=one["pos"], json=CART).status_code == 204
assert [(k, kw["device_ids"]) for k, _, kw in sent] == [("display.state", [one["display_id"]])]
s1 = client.get("/api/display/state", headers=one["display"]).json()
assert s1["linked"] is True and s1["state"]["mode"] == "cart" and s1["state"]["total"] == 9.5
assert [line["name"] for line in s1["state"]["lines"]] == ["Freddo", "Toast"]
assert client.get("/api/display/state", headers=two["display"]).json()["state"]["mode"] == "idle"
# the same state again: nothing new to send
client.post("/api/display/state", headers=one["pos"], json=CART)
assert len(sent) == 1
client.post("/api/display/state", headers=one["pos"], json={"mode": "paid", "total": 9.5, "paid": 20, "change": 10.5})
assert sent[-1][1]["change"] == 10.5
# only a POS pushes, only a display reads
assert err(client.post("/api/display/state", headers=one["display"], json=CART)) == "device.out_of_scope"
assert err(client.get("/api/display/state", headers=one["pos"])) == "device.out_of_scope"
assert err(client.post("/api/display/state", json=CART)) == "device.not_paired"
assert client.post("/api/display/state", headers=one["pos"], json={"mode": "dance"}).status_code == 422
def test_the_idle_screen_is_the_venues_design(client, owner_h, counters, sent, media_dir, monkeypatch):
from services import cloud_sync
monkeypatch.setitem(cloud_sync.license_state, "apps_url", "https://menu.example.com")
monkeypatch.setattr(cloud_sync.settings, "SITE_ID", "taverna-1")
s = client.get("/api/display/settings", headers=owner_h).json()
assert s["idle"]["style"] == "name" and s["media"] == []
up = lambda data, ctype="image/png": client.post("/api/display/media", headers=owner_h, # noqa: E731
files={"file": ("x.png", io.BytesIO(data), ctype)})
logo, photo = up(PNG).json(), up(PNG).json()
assert logo["url"].startswith("/api/display/media/") and len(list(media_dir.iterdir())) == 2
assert err(up(b"hello", "text/plain")) == "display.media_type"
assert client.get(logo["url"]).content == PNG # the displays load it with <img>
assert client.get("/api/display/media/../../secret.png").status_code == 404
# a slideshow of the two photos, with a line of text
body = {"style": "slideshow", "slides": [logo["name"], photo["name"]], "slide_seconds": 5, "message": "Kalimera!"}
r = client.put("/api/display/settings", headers=owner_h, json=body)
assert r.status_code == 200, r.text
assert sorted(kw["device_ids"] for k, _, kw in sent if k == "display.settings")[0] == sorted([counters[1]["display_id"], counters[2]["display_id"]])
idle = client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]
assert idle["style"] == "slideshow" and idle["slide_urls"] == [logo["url"], photo["url"]] and idle["message"] == "Kalimera!"
# a QR code: the venue's ordering link, or any link
client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "ordering", "qr_caption": "Order online"})
assert client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]["qr_link"] == "https://menu.example.com/order/taverna-1"
assert err(client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "custom"})) == "display.qr_url_missing"
assert client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "custom", "qr_url": "javascript:x"}).status_code == 422
# an image that isn't there; deleting one takes it off the screen
assert err(client.put("/api/display/settings", headers=owner_h, json={"style": "logo", "logo": "0" * 32 + ".png"})) == "display.media_unknown"
client.put("/api/display/settings", headers=owner_h, json={"style": "name_logo", "logo": logo["name"], "theme": "light"})
assert client.delete(f"/api/display/media/{logo['name']}", headers=owner_h).status_code == 204
after = client.get("/api/display/settings", headers=owner_h).json()
assert after["idle"]["logo"] is None and [m["name"] for m in after["media"]] == [photo["name"]] and after["idle"]["theme"] == "light"
def test_settings_need_the_key(client, make_user):
from tests.conftest import TEST_PASSWORD
waiter = make_user(role="waiter", username="w_display")
tok = client.post("/api/auth/login", json={"client": "manager", "username": "w_display", "password": TEST_PASSWORD}).json().get("access_token")
h = {"Authorization": f"Bearer {tok}"} if tok else {}
assert client.get("/api/display/settings", headers=h).status_code in (401, 403)
assert waiter.id