diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index d30a5dd..217dce1 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -94,10 +94,10 @@ CODES: dict[str, tuple[int, str]] = { "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."), "caller_id.key_invalid": (403, "The phone system's key is missing or wrong."), - "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."), + "display.look_unknown": (404, "Look {look_id} not found."), + "display.look_default": (409, "The default look can't be deleted. Make another look the default first."), + "display.not_a_display": (404, "Device {device_id} isn't a customer display."), "media.not_found": (404, "File {media_id} isn't in the media library."), "media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4 or WebM)."), "media.too_big": (413, "The file is too big (at most {max_mb} MB)."), diff --git a/local_backend/core/modules/device_config.py b/local_backend/core/modules/device_config.py index 50c3cf5..d856120 100644 --- a/local_backend/core/modules/device_config.py +++ b/local_backend/core/modules/device_config.py @@ -52,6 +52,9 @@ def _ref_exists(source: str, value: int, db) -> bool: 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) diff --git a/local_backend/migrations/versions/0028_display_looks.py b/local_backend/migrations/versions/0028_display_looks.py new file mode 100644 index 0000000..048ff2c --- /dev/null +++ b/local_backend/migrations/versions/0028_display_looks.py @@ -0,0 +1,99 @@ +"""display_looks: the customer display's idle screens, named, one per display (plan step 5.3). + +The venue's one idle screen (setting customer_display.idle) becomes the look "Main", the +default; its pictures (files in data/display_media, by name) are processed into the media +library and the look points at them by id. Missing or unreadable files are logged and left +out. The old folder stays on disk. The setting row goes (its SettingDef is gone too). + +Revision ID: 0028_display_looks +Revises: 0027_product_media +Create Date: 2026-11-17 18:00:00 +""" +import json +import logging +import os + +from alembic import op +import sqlalchemy as sa +from core.timeutil import UTCDateTime + +revision = '0028_display_looks' +down_revision = '0027_product_media' +branch_labels = None +depends_on = None + +log = logging.getLogger("alembic.0028") +OLD_DIR = os.environ.get("XENIA_DISPLAY_MEDIA_DIR", "/app/data/display_media") + + +def upgrade() -> None: + op.create_table('display_looks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('is_default', sa.Boolean(), nullable=False), + sa.Column('config', sa.JSON(), nullable=False), + sa.Column('created_at', UTCDateTime(), nullable=False), + sa.Column('updated_at', UTCDateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('display_looks', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_display_looks_id'), ['id'], unique=False) + + conn = op.get_bind() + raw = conn.execute(sa.text("SELECT value FROM pos_settings WHERE key = 'customer_display.idle'")).scalar() + try: + cfg = json.loads(raw or "{}") or {} + except ValueError: + cfg = {} + if not isinstance(cfg, dict): + cfg = {} + names = [n for n in [cfg.get("logo"), cfg.get("image"), *(cfg.get("slides") or [])] if isinstance(n, str) and n] + ids = _move_pictures(conn, names) + cfg["logo"] = ids.get(cfg.get("logo")) + cfg["image"] = ids.get(cfg.get("image")) + cfg["slides"] = [ids[n] for n in (cfg.get("slides") or []) if n in ids] + + from core.timeutil import DB_FORMAT, utcnow + now = utcnow().strftime(DB_FORMAT) + conn.execute(sa.text("INSERT INTO display_looks (name, is_default, config, created_at, updated_at) VALUES ('Main', 1, :c, :t, :t)"), + {"c": json.dumps(cfg), "t": now}) + conn.execute(sa.text("DELETE FROM pos_settings WHERE key = 'customer_display.idle'")) + + +def _move_pictures(conn, names) -> dict: + """{old file name: media id} for the pictures that made it into the library.""" + if not names: + return {} + from core.timeutil import DB_FORMAT, utcnow + from services import media as store + out = {} + for i, name in enumerate(dict.fromkeys(names), 1): + path = os.path.join(OLD_DIR, os.path.basename(name)) + if not os.path.isfile(path): + log.warning("customer display picture %s not found, left out", path) + continue + try: + sha, size, info = store.ingest_path(path) + except Exception as e: + log.warning("customer display picture %s not moved (%s)", path, getattr(e, "code", e)) + continue + mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar() + if mid is None: + if not info: + store.delete_files(sha) + sha, size, info = store.ingest_path(path) + conn.execute(sa.text( + "INSERT INTO media (kind, name, original_name, content_type, sha256, bytes, width, height, duration_ms, created_at) " + "VALUES (:kind, :name, :orig, :ctype, :sha, :bytes, :w, :h, :d, :at)"), + {"kind": info["kind"], "name": f"Customer display {i}", "orig": os.path.basename(path), "ctype": info["content_type"], + "sha": sha, "bytes": size, "w": info.get("width"), "h": info.get("height"), "d": info.get("duration_ms"), + "at": utcnow().strftime(DB_FORMAT)}) + mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar() + out[name] = mid + return out + + +def downgrade() -> None: + with op.batch_alter_table('display_looks', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_display_looks_id')) + op.drop_table('display_looks') diff --git a/local_backend/models/all.py b/local_backend/models/all.py index 6578851..a240f20 100644 --- a/local_backend/models/all.py +++ b/local_backend/models/all.py @@ -39,3 +39,4 @@ import models.notification # noqa: F401 Notification, NotificationRead (step 1 import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3) import models.refund # noqa: F401 Refund, RefundItem (step 3.3e) import models.media # noqa: F401 Media (media library, step 5.1) +import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3) diff --git a/local_backend/models/display_look.py b/local_backend/models/display_look.py new file mode 100644 index 0000000..5fd57d2 --- /dev/null +++ b/local_backend/models/display_look.py @@ -0,0 +1,22 @@ +"""Customer display looks (plan step 5.3): named idle screens a venue designs. + +One look is the venue's default; each customer display shows the look in its device config +(`look`, a ref to this table) or the default. A look's `config` is routers/customer_display.py +IdleBody: style, message, theme, QR target…, and pictures as media library ids (logo, image, +slides). Those ids are protected in the library while a look uses them. +""" +from sqlalchemy import JSON, Boolean, Column, Integer, String + +from core.timeutil import UTCDateTime, utcnow +from database import Base + + +class DisplayLook(Base): + __tablename__ = "display_looks" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String, nullable=False) + is_default = Column(Boolean, nullable=False, default=False) + config = Column(JSON, nullable=False, default=dict) + created_at = Column(UTCDateTime, default=utcnow, nullable=False) + updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False) diff --git a/local_backend/modules/customer_display/manifest.py b/local_backend/modules/customer_display/manifest.py index b1e42c4..bb4eb70 100644 --- a/local_backend/modules/customer_display/manifest.py +++ b/local_backend/modules/customer_display/manifest.py @@ -1,11 +1,11 @@ """Module manifest — see core/modules/model.py and APPS_PLATFORM §4.""" -from core.modules.model import DeviceApp, Limit, Module, Mount, Perm, SettingDef +from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm MODULE = Module( key='customer_display', kind='app', name='Customer display', - 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).', + description='Screen facing the customer at a counter POS: the sale, the total, the change, and an idle screen (a look) the venue designs; each display can show its own (plan steps 3.4, 5.3).', depends=('pos_counter',), permissions=( Perm('customer_display.manage', 'Set up the customer display (idle screen, images)', roles=('owner', 'store_manager')), @@ -13,11 +13,11 @@ MODULE = Module( 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=()), + device_app=DeviceApp(login_modes=('none',), scope=(), config=( + # Its idle screen: one of the venue's looks (Settings > Customer display); none = the default + ConfigField('look', 'ref', default=None, choices_from='display_looks'), + )), ) diff --git a/local_backend/routers/customer_display.py b/local_backend/routers/customer_display.py index 50643c7..990432f 100644 --- a/local_backend/routers/customer_display.py +++ b/local_backend/routers/customer_display.py @@ -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 (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} diff --git a/local_backend/tests/test_customer_display.py b/local_backend/tests/test_customer_display.py index 0541bc3..3bc71f7 100644 --- a/local_backend/tests/test_customer_display.py +++ b/local_backend/tests/test_customer_display.py @@ -1,22 +1,17 @@ -"""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 +"""The customer display (plan steps 3.4, 5.3): a POS pushes what its customer sees, only its own +displays hear it; the idle screen is a look the venue designs (name, logo, both, blank, an image, +a slideshow, a QR code) with pictures from the media library, and each display can show its own.""" 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") +from tests.test_media import jpeg, media_dir, mp4, png_alpha, up # noqa: F401 (fixture + helpers) @pytest.fixture(autouse=True) -def media_dir(tmp_path, monkeypatch): +def _fresh(media_dir): import routers.customer_display as cd - monkeypatch.setattr(cd, "MEDIA_DIR", str(tmp_path / "media")) cd._last.clear() - return tmp_path / "media" @pytest.fixture @@ -65,43 +60,125 @@ def test_a_sale_shows_only_on_its_own_display(client, counters, sent): 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): +def test_the_idle_screen_is_a_look_from_the_library(client, owner_h, counters, sent, 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 - 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) + looks = client.get("/api/display/looks", headers=owner_h).json() + assert [(x["name"], x["is_default"], x["config"]["style"]) for x in looks] == [("Main", True, "name")] + main = looks[0] + assert sorted(d["id"] for d in main["displays"]) == sorted([counters[1]["display_id"], counters[2]["display_id"]]) + logo, photo = up(client, owner_h, jpeg(400, 200, (1, 1, 1))).json(), up(client, owner_h, jpeg(1600, 900, (2, 2, 2))).json() + # a slideshow of two library photos, with a line of text: the displays hear it at once + body = {"style": "slideshow", "slides": [logo["id"], photo["id"]], "slide_seconds": 5, "message": "Kalimera!"} + r = client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": 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!" + assert idle["style"] == "slideshow" and idle["slide_urls"] == [logo["urls"]["full"], photo["urls"]["full"]] 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"}) + client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"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" + assert err(client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "qr", "qr_target": "custom"}})) == "display.qr_url_missing" + assert client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "qr", "qr_target": "custom", "qr_url": "javascript:x"}}).status_code == 422 + # pictures must be library pictures + assert err(client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "logo", "logo": 99999}})) == "media.not_found" + video = up(client, owner_h, mp4(), name="v.mp4", ctype="video/mp4").json() + assert err(client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "image", "image": video["id"]}})) == "media.not_a_picture" + # a picture a look uses can't be deleted from the library + client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "name_logo", "logo": logo["id"], "theme": "light"}}) + r = client.delete(f"/api/media/{logo['id']}", headers=owner_h) + assert r.status_code == 409 and r.json()["error"]["params"]["used_by"] == [{"kind": "display_look", "id": main["id"], "name": "Main"}] + assert client.get("/api/display/state", headers=counters[2]["display"]).json()["idle"]["logo_url"] == logo["urls"]["card"] -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 +def test_two_displays_two_slideshows(client, owner_h, counters, sent): + """Done when (5.3): two displays show two different slideshows from the library.""" + a, b, c = (up(client, owner_h, jpeg(800, 600, (i, i, i))).json() for i in (10, 20, 30)) + main = client.get("/api/display/looks", headers=owner_h).json()[0] + client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "slideshow", "slides": [a["id"], b["id"]]}}) + promo = client.post("/api/display/looks", headers=owner_h, json={"name": "Promo", "config": {"style": "slideshow", "slides": [c["id"]], "slide_seconds": 4}}) + assert promo.status_code == 201, promo.text + promo = promo.json() + assert promo["displays"] == [] and promo["is_default"] is False + two = counters[2]["display_id"] + sent.clear() + r = client.put(f"/api/display/displays/{two}/look", headers=owner_h, json={"look_id": promo["id"]}) + assert r.status_code == 200 and r.json()["look_id"] == promo["id"] + assert [(k, kw["device_ids"]) for k, _, kw in sent] == [("display.settings", [two])] + one_idle = client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"] + two_idle = client.get("/api/display/state", headers=counters[2]["display"]).json()["idle"] + assert one_idle["slide_urls"] == [a["urls"]["full"], b["urls"]["full"]] + assert two_idle["slide_urls"] == [c["urls"]["full"]] and two_idle["slide_seconds"] == 4 + looks = {x["name"]: x for x in client.get("/api/display/looks", headers=owner_h).json()} + assert [d["id"] for d in looks["Promo"]["displays"]] == [two] and [d["id"] for d in looks["Main"]["displays"]] == [counters[1]["display_id"]] + assert {d["id"]: d["look_id"] for d in client.get("/api/display/displays", headers=owner_h).json()} == {counters[1]["display_id"]: None, two: promo["id"]} + # a change to Promo reaches only the display that shows it + sent.clear() + client.put(f"/api/display/looks/{promo['id']}", headers=owner_h, json={"name": "Summer promo"}) + assert [kw["device_ids"] for k, _, kw in sent] == [[two]] + # the default can't be deleted; deleting Promo puts its display back on the default + assert err(client.delete(f"/api/display/looks/{main['id']}", headers=owner_h)) == "display.look_default" + assert client.delete(f"/api/display/looks/{promo['id']}", headers=owner_h).status_code == 204 + assert client.get("/api/display/state", headers=counters[2]["display"]).json()["idle"]["slide_urls"] == one_idle["slide_urls"] + + +def test_a_new_default_and_copies(client, owner_h, counters, sent): + main = client.get("/api/display/looks", headers=owner_h).json()[0] + client.put(f"/api/display/looks/{main['id']}", headers=owner_h, json={"config": {"style": "blank", "theme": "light"}}) + copy = client.post("/api/display/looks", headers=owner_h, json={"name": "Copy", "copy_of": main["id"]}).json() + assert copy["config"]["style"] == "blank" and copy["config"]["theme"] == "light" + client.put(f"/api/display/looks/{copy['id']}", headers=owner_h, json={"config": {"style": "name", "theme": "dark"}}) + sent.clear() + assert client.post(f"/api/display/looks/{copy['id']}/default", headers=owner_h).json()["is_default"] is True + assert sorted(kw["device_ids"] for k, _, kw in sent)[0] == sorted([counters[1]["display_id"], counters[2]["display_id"]]) + assert client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]["style"] == "name" + assert [x["name"] for x in client.get("/api/display/looks", headers=owner_h).json() if x["is_default"]] == ["Copy"] + + +def test_the_devices_page_offers_the_looks(client, owner_h, counters): + """The display's `look` is a device config ref (the Devices page edits it too).""" + promo = client.post("/api/display/looks", headers=owner_h, json={"name": "Promo"}).json() + one = counters[1]["display_id"] + r = client.patch(f"/api/devices/{one}", headers=owner_h, json={"config": {"look": promo["id"]}}) + assert r.status_code == 200, r.text + assert [d["look_id"] for d in client.get("/api/display/displays", headers=owner_h).json() if d["id"] == one] == [promo["id"]] + assert err(client.patch(f"/api/devices/{one}", headers=owner_h, json={"config": {"look": 99999}})) == "validation.device_config" + assert err(client.put(f"/api/display/displays/{counters[1]['pos_id']}/look", headers=owner_h, json={"look_id": None})) == "display.not_a_display" + + +def test_migration_0028_turns_the_idle_setting_into_a_look(tmp_path, monkeypatch, media_dir): + import json + from alembic import command + from sqlalchemy import create_engine, text + from core.schema import alembic_config, upgrade_to_head + old = tmp_path / "display_media" + old.mkdir() + (old / ("a" * 32 + ".jpg")).write_bytes(jpeg(640, 480, (5, 6, 7))) + (old / ("b" * 32 + ".png")).write_bytes(png_alpha(64, 64)) + monkeypatch.setenv("XENIA_DISPLAY_MEDIA_DIR", str(old)) + eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}") + cfg = {"style": "slideshow", "slides": ["a" * 32 + ".jpg", "c" * 32 + ".jpg", "b" * 32 + ".png"], "logo": "a" * 32 + ".jpg", + "message": "Hi", "theme": "light"} + with eng.begin() as conn: + command.upgrade(alembic_config(conn), "0027_product_media") + conn.execute(text("insert into pos_settings (key, value, updated_at) values ('customer_display.idle', :v, '2026-11-01 10:00:00.000000')"), {"v": json.dumps(cfg)}) + upgrade_to_head(eng) + with eng.connect() as conn: + looks = conn.execute(text("select name, is_default, config from display_looks")).fetchall() + media = dict(conn.execute(text("select original_name, id from media")).fetchall()) + left = conn.execute(text("select count(*) from pos_settings where key = 'customer_display.idle'")).scalar() + eng.dispose() + assert len(looks) == 1 and looks[0][0] == "Main" and looks[0][1] + moved = json.loads(looks[0][2]) + a, b = media["a" * 32 + ".jpg"], media["b" * 32 + ".png"] + assert moved["slides"] == [a, b] and moved["logo"] == a and moved["message"] == "Hi" and moved["theme"] == "light" + assert left == 0 + + +def test_looks_need_the_key(client, make_user, login): + waiter = login(make_user(role="waiter")) + assert client.get("/api/display/looks", headers=waiter).status_code == 403 + assert client.post("/api/display/looks", headers=waiter, json={"name": "x"}).status_code == 403 + devices_only = login(make_user(role="waiter", keys=["core.devices.manage"])) + assert client.get("/api/display/looks", headers=devices_only).status_code == 200 diff --git a/local_backend/tests/test_live.py b/local_backend/tests/test_live.py index ef6f69b..3528061 100644 --- a/local_backend/tests/test_live.py +++ b/local_backend/tests/test_live.py @@ -217,7 +217,7 @@ def test_module_catalogue_describes_config(client, owner_h): assert kds["prep_zone_id"] == {"key": "prep_zone_id", "type": "ref", "default": None, "choices": [], "min": None, "max": None, "choices_from": "prep_zones", "group": "zone", "after": None} assert kds["age_late_minutes"]["after"] == "age_warning_minutes" and kds["colour_fresh"]["type"] == "color" - assert mods["customer_display"]["device_app"]["config"] == [] + assert [f["key"] for f in mods["customer_display"]["device_app"]["config"]] == ["look"] # its idle screen (5.3) def test_config_field_types(db, pair): diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 64d557a..b48c57f 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -122,10 +122,10 @@ "table_busy": "Αυτό το τραπέζι έχει ήδη ανοιχτή παραγγελία. Διαλέξτε άλλο τραπέζι ή κλείστε πρώτα εκείνη την παραγγελία." }, "display": { - "media_unknown": "Η εικόνα {{name}} δεν βρέθηκε.", - "media_type": "Ανεβάστε εικόνα JPG, PNG, WebP ή GIF.", - "media_too_big": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mb}} MB).", - "qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός." + "qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός.", + "look_unknown": "Η εμφάνιση {{look_id}} δεν βρέθηκε.", + "look_default": "Η προεπιλεγμένη εμφάνιση δεν διαγράφεται. Ορίστε πρώτα άλλη ως προεπιλογή.", + "not_a_display": "Η συσκευή {{device_id}} δεν είναι οθόνη πελάτη." }, "media": { "not_found": "Το αρχείο {{media_id}} δεν υπάρχει στη βιβλιοθήκη πολυμέσων.", diff --git a/packages/i18n/locales/el/modules.json b/packages/i18n/locales/el/modules.json index 68fcb93..0a81fb2 100644 --- a/packages/i18n/locales/el/modules.json +++ b/packages/i18n/locales/el/modules.json @@ -87,6 +87,13 @@ }, "permissions": { "manage": "Ρύθμιση της οθόνης πελάτη (οθόνη αναμονής, εικόνες)" + }, + "config": { + "look": { + "label": "Οθόνη αναμονής", + "hint": "Ποια εμφάνιση δείχνει ανάμεσα στις πωλήσεις (Ρυθμίσεις → Οθόνη πελάτη).", + "none": "Η προεπιλεγμένη εμφάνιση" + } } }, "expenses": { diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index c63ae1f..1cb67a5 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -122,10 +122,10 @@ "table_busy": "That table already has an open order. Pick another table, or close that order first." }, "display": { - "media_unknown": "Image {{name}} not found.", - "media_type": "Upload a JPG, PNG, WebP or GIF image.", - "media_too_big": "The image is too big (at most {{max_mb}} MB).", - "qr_url_missing": "Enter the link the QR code opens." + "qr_url_missing": "Enter the link the QR code opens.", + "look_unknown": "Look {{look_id}} not found.", + "look_default": "The default look can't be deleted. Make another look the default first.", + "not_a_display": "Device {{device_id}} isn't a customer display." }, "media": { "not_found": "File {{media_id}} isn't in the media library.", diff --git a/packages/i18n/locales/en/modules.json b/packages/i18n/locales/en/modules.json index dc3b032..593b5d6 100644 --- a/packages/i18n/locales/en/modules.json +++ b/packages/i18n/locales/en/modules.json @@ -87,6 +87,13 @@ }, "permissions": { "manage": "Set up the customer display (idle screen, images)" + }, + "config": { + "look": { + "label": "Idle screen", + "hint": "Which look it shows between sales (Settings → Customer display).", + "none": "The default look" + } } }, "expenses": {