Compare commits

...
3 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 51b764fe7e test(e2e): display looks (two displays, two slideshows; looks UI with library pictures); docs
- terminal.mjs: the looks API drives the idle screen; a second look on the
  other display: two displays show two different slideshows from the library.
- manager.mjs: the default look's QR design through Settings.
- media.mjs: a new look with three pictures picked at once, a picture in a look
  can't be deleted.
- pack README: the customer display row; CS-19 (screen designs are records a
  device picks with a ref field).
- run-all --no-android: all passed except terminal's "server unreachable →
  banner" (8 s wait, under load); terminal.mjs alone right after: all passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:50:52 +02:00
bonaminandClaude Opus 5.5 6d84e43330 feat(manager): customer display looks: several, a default, one per display; pictures from the library (platform-v2 step 5.3)
Settings → Customer display lists the looks (default starred, how many
displays each), edits one (logo / picture with MediaField, the slideshow's
pictures picked several at a time, reordered, removed), new look (empty or a
copy), make default, delete, and "Which display shows which look". The Devices
page offers the looks for a display's Idle screen. MediaPicker: `multiple`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:50:52 +02:00
bonaminandClaude Opus 5.5 27d7bbb976 feat(backend): customer display looks on the media library, one per display (platform-v2 step 5.3)
- display_looks (Alembic 0028): named idle screens, one default; config is
  the 3.4 design with pictures as media library ids. 0028 turns the setting
  customer_display.idle into the look "Main" and moves its data/display_media
  pictures into the library (the old folder stays on disk).
- A display shows the look in its device config `look` (ref ConfigField,
  choices_from "display_looks", validated in device_config) or the default.
- /api/display/looks (GET also for core.devices.manage), POST, PUT,
  POST /{id}/default, DELETE (not the default; its displays go back to it);
  /api/display/displays and PUT /displays/{id}/look. A change sends
  display.settings only to the displays showing that look.
- /api/display/settings, /api/display/media* and their error codes are gone;
  GET /api/display/state keeps its shape (logo card size, image/slides full).
- Looks register their media usage (a picture in a look can't be deleted).
- tests: test_customer_display.py (7, incl. two displays two slideshows and
  the 0028 data move); 501 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:50:51 +02:00
24 changed files with 892 additions and 348 deletions
+2 -2
View File
@@ -46,7 +46,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `local_backend/services/online_reservations.py` | Table bookings from the online ordering app (phase 3S): stored as `Reservation` rows (`requested` → `pending` confirmed / `declined`; `arrived`, `cancelled`, `no_show`), food ordered ahead kept on the booking (`items_json`) and turned into an order **only at the fire time** (`fire_worker`, a connect_orders module worker; needs an open business day) or on early arrival. Every step mirrors the cloud status. The counter's Online → Bookings and `/api/connect/bookings/*` use it; the reservations router delegates online bookings to it |
| `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` |
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
| `local_backend/routers/customer_display.py`, `terminal/src/apps/customer-display/` | The customer display (3.4): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is the venue's design (`customer_display.idle`: name, logo, both, blank, image, slideshow, QR, a line of text, dark/light), images in `/app/data/display_media`, served by name at `/api/display/media/{name}` (public, LAN, random names). The POS's last state lives in memory |
| `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory |
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` |
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
@@ -200,7 +200,7 @@ An app makes one client with `createApiClient({ axios, baseURL, getToken, getDev
- A screen with sign-in `none` (customer display) receives **every** broadcast event; send what is meant for one screen with `device_ids=[…]` (the customer display's `display.state` goes only to the displays linked to that POS) and what is meant for a role with `user_ids=[…]` plus the screens that need it (`call_incoming`: users with `caller_id.use` + the counter screens).
- A device app may only reach routes of modules in its `DeviceApp.scope`. When an app must call another module's route, add one pattern for it (the POS has `customer_display.state`), never a wildcard.
- Events are stored and **replayed on reconnect** (24 h). A screen that reacts with something visible must ignore stale ones: check the event's time (`call_incoming`: older than a minute → no popup) or let it expire (`display.state` "paid" → idle after 12 s); state a screen needs after a restart comes from a GET (`/api/display/state`, the KDS list), not from replay.
- What the device itself shows comes from its device config (`ConfigField`s) or a venue setting; the venue-wide look of a screen (the customer display's idle screen) is a setting with its own manager page, not free JSON in the device.
- What the device itself shows comes from its device config (`ConfigField`s) or a venue setting. Designs a venue makes for its screens (the customer display's looks, 5.3; later signage playlists) are their own records with a manager page, and a device picks one with a `ref` config field (none = the venue's default), never free JSON in the device.
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
+3 -3
View File
@@ -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)."),
@@ -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)
@@ -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')
+1
View File
@@ -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)
+22
View File
@@ -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)
@@ -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'),
)),
)
+222 -116
View File
@@ -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.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)})
@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()
displays = _all_displays(db)
if displays:
broadcast_sync("display.settings", {}, device_ids=displays)
return None
db.refresh(look)
_tell(_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.post("/looks/{look_id}/default")
def make_default(look_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
look = _get(db, look_id)
old = default_look(db)
before = set(_displays_showing(db, old))
for x in db.query(DisplayLook).filter(DisplayLook.is_default.is_(True)):
x.is_default = False
look.is_default = True
db.commit()
_tell(sorted(before | set(_displays_showing(db, look))))
return _look_out(db, look)
@router.delete("/looks/{look_id}", status_code=204)
def delete_look(look_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
look = _get(db, look_id)
if look.is_default:
raise XeniaError("display.look_default")
moved = []
for d in _displays(db):
if (d.config or {}).get("look") == look.id:
d.config = {**(d.config or {}), "look": None}
moved.append(d.id)
db.delete(look)
db.commit()
_tell(moved)
return Response(status_code=204)
@router.get("/displays")
def list_displays(db: Session = Depends(get_db), user=Depends(require(KEY))):
out = []
for d in _displays(db):
lid = (d.config or {}).get("look")
look = db.get(DisplayLook, lid) if lid else None
out.append({"id": d.id, "name": d.name, "look_id": look.id if look else None,
"linked_device_id": d.linked_device_id})
return out
@router.put("/displays/{device_id}/look")
def choose_look(device_id: int, body: LookChoice, db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.device import Device
dev = db.get(Device, device_id)
if dev is None or dev.app_key != "customer_display" or dev.revoked_at is not None:
raise XeniaError("display.not_a_display", device_id=device_id)
if body.look_id is not None:
_get(db, body.look_id)
dev.config = {**(dev.config or {}), "look": body.look_id}
db.commit()
_tell([dev.id])
return {"id": dev.id, "name": dev.name, "look_id": body.look_id, "linked_device_id": dev.linked_device_id}
+117 -40
View File
@@ -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 <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)
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
+1 -1
View File
@@ -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):
@@ -1,15 +1,22 @@
// Settings → Customer display (plan step 3.4). What the customer displays show between sales,
// the venue's own style (owner, 2026-11-16): 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, dark or light. Images are uploaded here (JPG/PNG/WebP/GIF, ≤ 5 MB).
// Saving reaches every display at once. Backend: /api/display/settings, /api/display/media.
import { useCallback, useEffect, useRef, useState } from 'react'
// Settings → Customer display (plan steps 3.4, 5.3). What the customer displays show between
// sales is a **look** the venue designs (owner, 2026-11-16: "configurable, so each venue can
// choose their style"): the name, the logo, both, nothing, one picture, a slideshow, or a QR code
// (the venue's ordering link, its QR menu, or any link), with an optional line of text, dark or
// light. A venue can have several looks; one is the default and each display can show its own
// (also its "Idle screen" in Devices). Pictures come from the media library (Management → Media).
// Saving reaches the displays that show the look at once.
// Backend: /api/display/looks, /api/display/displays (routers/customer_display.py).
import { useCallback, useEffect, useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { Check, ImagePlus, Trash2 } from 'lucide-react'
import { ArrowLeft, ArrowRight, Check, Images, Plus, Star, Trash2, X } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Field, IconButton, Input, Select, Spinner } from '@xenia/ui'
import { Button, Dialog, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui'
import client from '../../../api/client'
import MediaField from '../../media/MediaField'
import MediaPicker from '../../media/MediaPicker'
import { imageOf } from '../../media/mediaLogic'
import { MediaThumb } from '../../media/MediaParts'
import { useSettings } from './useSettings'
const STYLES = ['name', 'logo', 'name_logo', 'blank', 'image', 'slideshow', 'qr']
@@ -17,59 +24,53 @@ const STYLES = ['name', 'logo', 'name_logo', 'blank', 'image', 'slideshow', 'qr'
export default function CustomerDisplaySettings() {
const { t } = useTranslation('manager')
const venue = useSettings()
const [data, setData] = useState(null)
const [form, setForm] = useState(null)
const [looks, setLooks] = useState(null)
const [displays, setDisplays] = useState([])
const [current, setCurrent] = useState(null) // the look being edited (id)
const [form, setForm] = useState(null) // its config
const [pics, setPics] = useState({}) // media id → image {id, name, thumb, card, full}
const [lookName, setLookName] = useState('')
const [busy, setBusy] = useState(false)
const [name, setName] = useState(null)
const fileRef = useRef(null)
const [venueName, setVenueName] = useState(null)
const [adding, setAdding] = useState(false)
const [confirmDelete, setConfirmDelete] = useState(false)
const load = useCallback(async () => {
const open = useCallback(look => {
setCurrent(look.id)
setForm(look.config)
setLookName(look.name)
setPics(p => ({ ...p, ...Object.fromEntries(Object.entries(look.pictures || {}).map(([k, v]) => [Number(k), v])) }))
}, [])
const load = useCallback(async (pick) => {
try {
const { data: d } = await client.get('/api/display/settings')
setData(d)
setForm(f => f ?? d.idle)
} catch (err) { toast.error(errorMessage(err, t)) }
}, [t])
useEffect(() => { load() }, [load])
const [{ data: ls }, { data: ds }] = await Promise.all([client.get('/api/display/looks'), client.get('/api/display/displays')])
setLooks(ls)
setDisplays(ds)
const target = ls.find(l => l.id === pick) || null
if (target) open(target)
return ls
} catch (err) { toast.error(errorMessage(err, t)); return null }
}, [t, open])
useEffect(() => { load().then(ls => { if (ls?.length) open(ls[0]) }) }, [load, open])
const look = looks?.find(l => l.id === current)
const dirty = useMemo(() => look && (JSON.stringify(look.config) !== JSON.stringify(form) || lookName.trim() !== look.name), [look, form, lookName])
if (!looks || !form || !look || venue.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
if (!data || !form || venue.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const media = data.media
const needs = { logo: ['logo', 'name_logo'], image: ['image'], slides: ['slideshow'], qr: ['qr'] }
const shows = part => needs[part].includes(form.style)
const shows = part => ({ logo: ['logo', 'name_logo'], image: ['image'], slides: ['slideshow'], qr: ['qr'] })[part].includes(form.style)
const picOf = id => (id ? pics[id] ?? null : null)
const setPic = (key, image) => { if (image) setPics(p => ({ ...p, [image.id]: image })); set(key, image?.id ?? null) }
const save = async () => {
const act = async (fn, done, pick = current) => {
setBusy(true)
try {
const { data: d } = await client.put('/api/display/settings', form)
setData(d)
setForm(d.idle)
toast.success(t('settings.saved'))
} catch (err) { toast.error(errorMessage(err, t)) }
try { await fn(); if (done) toast.success(done); await load(pick) } catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
const upload = async e => {
const files = [...(e.target.files ?? [])]
e.target.value = ''
for (const file of files) {
const body = new FormData()
body.append('file', file)
try {
const { data: m } = await client.post('/api/display/media', body)
setData(d => ({ ...d, media: [...d.media, m] }))
if (form.style === 'slideshow') setForm(f => ({ ...f, slides: [...f.slides, m.name] }))
} catch (err) { toast.error(errorMessage(err, t)) }
}
}
const remove = async m => {
try {
await client.delete(`/api/display/media/${m.name}`)
setData(d => ({ ...d, media: d.media.filter(x => x.name !== m.name) }))
setForm(f => ({ ...f, logo: f.logo === m.name ? null : f.logo, image: f.image === m.name ? null : f.image,
slides: f.slides.filter(n => n !== m.name) }))
} catch (err) { toast.error(errorMessage(err, t)) }
}
const toggleSlide = n => set('slides', form.slides.includes(n) ? form.slides.filter(x => x !== n) : [...form.slides, n])
const save = () => act(() => client.put(`/api/display/looks/${look.id}`, { name: lookName.trim() || look.name, config: form }), t('settings.saved'))
const lookLabel = l => `${l.name}${l.is_default ? ` (${t('display.looks.default')})` : ''}`
const defaultLook = looks.find(l => l.is_default)
return (
<section className="bg-surface border border-line rounded-card shadow-raised grid gap-5 p-5" data-testid="settings-display">
@@ -78,6 +79,39 @@ export default function CustomerDisplaySettings() {
<p className="text-label text-ink-2">{t('display.intro')}</p>
</header>
{/* the looks */}
<div className="grid gap-2">
<span className="text-label font-medium text-ink-2">{t('display.looks.title')}</span>
<div className="flex flex-wrap gap-2" role="tablist" aria-label={t('display.looks.title')}>
{looks.map(l => (
<button key={l.id} type="button" role="tab" aria-selected={l.id === current} data-testid="display-look" data-name={l.name}
onClick={() => (dirty && !window.confirm(t('display.looks.discard')) ? null : open(l))}
className={`px-3 py-2 rounded-control border text-label font-medium flex items-center gap-1.5 transition-colors duration-fast
${l.id === current ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface-2 text-ink hover:bg-surface-3'}`}>
{l.is_default && <Star size={14} aria-label={t('display.looks.default')} />}
{l.name}
<span className="text-caption text-ink-3 font-normal">{t('display.looks.screens', { count: l.displays.length })}</span>
</button>
))}
<Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => setAdding(true)} data-testid="display-look-new">{t('display.looks.new')}</Button>
</div>
</div>
{/* the look being edited */}
<div className="grid gap-5 rounded-card border border-line p-4" data-testid="display-look-editor" data-id={look.id}>
<div className="flex flex-wrap items-end gap-2">
<Field label={t('display.looks.name')} className="flex-1 min-w-[12rem]">
<Input value={lookName} maxLength={60} onChange={e => setLookName(e.target.value)} data-testid="display-look-name" />
</Field>
{look.is_default
? <span className="text-label text-ink-2 flex items-center gap-1 h-control"><Star size={14} aria-hidden="true" />{t('display.looks.isDefault')}</span>
: <>
<Button variant="secondary" disabled={busy} onClick={() => act(() => client.post(`/api/display/looks/${look.id}/default`), t('display.looks.madeDefault'))}
data-testid="display-look-default">{t('display.looks.makeDefault')}</Button>
<IconButton variant="ghost" label={t('fees.delete')} disabled={busy} onClick={() => setConfirmDelete(true)} data-testid="display-look-delete"><Trash2 size={16} /></IconButton>
</>}
</div>
<div className="grid gap-2" role="radiogroup" aria-label={t('display.style')}>
<span className="text-label font-medium text-ink-2">{t('display.style')}</span>
<div className="grid gap-2" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(10rem, 1fr))' }}>
@@ -93,13 +127,6 @@ export default function CustomerDisplaySettings() {
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="flex items-start gap-2">
<Field label={t('display.venueName')} hint={t('display.venueNameHint')} className="flex-1">
<Input value={name ?? venue.get('venue.name', '')} onChange={e => setName(e.target.value)} maxLength={80} data-testid="display-venue-name" />
</Field>
<Button variant="secondary" className="mt-7" disabled={name == null || venue.saving} data-testid="display-venue-name-save"
onClick={() => { venue.save('venue.name', name.trim()); setName(null) }}>{t('fees.save')}</Button>
</div>
{form.style !== 'blank' && (
<Field label={t('display.message')} hint={t('display.messageHint')}>
<Input value={form.message ?? ''} onChange={e => set('message', e.target.value)} maxLength={120} data-testid="display-message" />
@@ -137,42 +164,125 @@ export default function CustomerDisplaySettings() {
</div>
)}
{(shows('logo') || shows('image') || shows('slides')) && (
<div className="grid gap-3">
<div className="flex items-center gap-2">
<span className="flex-1 text-label font-medium text-ink-2">
{t(shows('logo') ? 'display.pickLogo' : shows('image') ? 'display.pickImage' : 'display.pickSlides')}
</span>
<input ref={fileRef} type="file" accept="image/jpeg,image/png,image/webp,image/gif" multiple className="hidden" onChange={upload} data-testid="display-upload" />
<Button size="sm" variant="secondary" icon={<ImagePlus size={16} />} onClick={() => fileRef.current?.click()}>{t('display.upload')}</Button>
{shows('logo') && <MediaField value={picOf(form.logo)} onChange={img => setPic('logo', img)} label={t('display.pickLogo')} testid="display-logo" />}
{shows('image') && <MediaField value={picOf(form.image)} onChange={img => setPic('image', img)} label={t('display.pickImage')} testid="display-image" />}
{shows('slides') && <Slides ids={form.slides} pics={pics} onChange={(ids, more) => { if (more) setPics(p => ({ ...p, ...more })); set('slides', ids) }} />}
<div className="flex gap-2 items-center">
<Button onClick={save} loading={busy} data-testid="display-save">{t('fees.save')}</Button>
{dirty && <span className="text-label text-ink-3">{t('display.looks.unsaved')}</span>}
</div>
{media.length === 0 ? (
<p className="text-label text-ink-3">{t('display.noImages')}</p>
) : (
<ul className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9rem, 1fr))' }} data-testid="display-media">
{media.map(m => {
const chosen = shows('logo') ? form.logo === m.name : shows('image') ? form.image === m.name : form.slides.includes(m.name)
const pick = () => (shows('logo') ? set('logo', m.name) : shows('image') ? set('image', m.name) : toggleSlide(m.name))
return (
<li key={m.name} className={`relative rounded-control border-2 overflow-hidden ${chosen ? 'border-accent' : 'border-line'}`}>
<button type="button" onClick={pick} aria-pressed={chosen} className="block w-full aspect-video bg-surface-2" data-testid="display-media-pick">
<img src={m.url} alt="" className="w-full h-full object-contain" />
</button>
{chosen && shows('slides') && (
<span className="absolute top-1 left-1 min-w-6 h-6 px-1 rounded-full bg-accent text-accent-fg text-caption font-bold flex items-center justify-center">
{form.slides.indexOf(m.name) + 1}
</span>
)}
<IconButton size="sm" variant="secondary" label={t('fees.delete')} className="absolute top-1 right-1" onClick={() => remove(m)}><Trash2 size={14} /></IconButton>
</div>
{/* which display shows which look */}
<div className="grid gap-2" data-testid="display-screens">
<span className="text-label font-medium text-ink-2">{t('display.looks.whichScreen')}</span>
{displays.length === 0 ? <p className="text-label text-ink-3">{t('display.looks.noScreens')}</p> : (
<ul className="grid gap-2">
{displays.map(d => (
<li key={d.id} className="flex flex-wrap items-center gap-3">
<span className="text-body text-ink min-w-[10rem]">{d.name}</span>
<Select value={d.look_id == null ? '' : String(d.look_id)} aria-label={t('display.looks.lookFor', { name: d.name })} data-testid={`display-assign-${d.id}`}
onChange={e => act(() => client.put(`/api/display/displays/${d.id}/look`, { look_id: e.target.value ? Number(e.target.value) : null }), t('settings.saved'))}
options={[{ value: '', label: t('display.looks.followDefault', { name: defaultLook?.name ?? '' }) },
...looks.map(l => ({ value: String(l.id), label: lookLabel(l) }))]} />
</li>
)
})}
))}
</ul>
)}
</div>
)}
<div><Button onClick={save} loading={busy} data-testid="display-save">{t('fees.save')}</Button></div>
<div className="flex items-start gap-2 max-w-xl">
<Field label={t('display.venueName')} hint={t('display.venueNameHint')} className="flex-1">
<Input value={venueName ?? venue.get('venue.name', '')} onChange={e => setVenueName(e.target.value)} maxLength={80} data-testid="display-venue-name" />
</Field>
<Button variant="secondary" className="mt-7" disabled={venueName == null || venue.saving} data-testid="display-venue-name-save"
onClick={() => { venue.save('venue.name', venueName.trim()); setVenueName(null) }}>{t('fees.save')}</Button>
</div>
{adding && <NewLook looks={looks} current={look} onClose={() => setAdding(false)}
onCreate={async body => {
setBusy(true)
try {
const { data } = await client.post('/api/display/looks', body)
setAdding(false)
toast.success(t('display.looks.created'))
await load(data.id)
} catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}} />}
{confirmDelete && (
<Dialog open size="sm" title={t('display.looks.deleteTitle', { name: look.name })} onClose={() => setConfirmDelete(false)}
footer={<>
<Button variant="secondary" onClick={() => setConfirmDelete(false)}>{t('fees.cancel')}</Button>
<Button variant="danger" loading={busy} data-testid="display-look-delete-confirm"
onClick={() => act(() => client.delete(`/api/display/looks/${look.id}`), t('display.looks.deleted'), defaultLook?.id)
.then(() => setConfirmDelete(false))}>{t('fees.delete')}</Button>
</>}>
<p className="text-body text-ink-2">{t('display.looks.deleteBody', { name: defaultLook?.name ?? '' })}</p>
</Dialog>
)}
</section>
)
}
/** The slideshow's pictures, in order: move, remove, add from the library (several at once). */
function Slides({ ids, pics, onChange }) {
const { t } = useTranslation('manager')
const [picking, setPicking] = useState(false)
const move = (i, d) => { const next = [...ids]; [next[i], next[i + d]] = [next[i + d], next[i]]; onChange(next) }
return (
<div className="grid gap-2" data-testid="display-slides">
<div className="flex items-center gap-2">
<span className="flex-1 text-label font-medium text-ink-2">{t('display.pickSlides')}</span>
<Button size="sm" variant="secondary" icon={<Images size={14} />} onClick={() => setPicking(true)} data-testid="display-slides-add">{t('display.addSlides')}</Button>
</div>
{ids.length === 0 ? <p className="text-label text-ink-3">{t('display.noSlides')}</p> : (
<ol className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(8.5rem, 1fr))' }}>
{ids.map((id, i) => (
<li key={`${id}:${i}`} className="relative rounded-control border border-line overflow-hidden bg-surface-2" data-testid="display-slide-item" data-id={id}>
<MediaThumb item={pics[id]} className="w-full aspect-video" />
<span className="absolute top-1 left-1 min-w-6 h-6 px-1 rounded-full bg-accent text-accent-fg text-caption font-bold flex items-center justify-center">{i + 1}</span>
<span className="block px-2 pt-1 text-caption text-ink-2 truncate" title={pics[id]?.name}>{pics[id]?.name}</span>
<div className="flex items-center justify-between px-1 pb-1 gap-1">
<IconButton size="sm" variant="ghost" label={t('display.earlier')} disabled={i === 0} onClick={() => move(i, -1)}><ArrowLeft size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('display.later')} disabled={i === ids.length - 1} onClick={() => move(i, 1)}><ArrowRight size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('media.removePhoto')} onClick={() => onChange(ids.filter((_, j) => j !== i))}><X size={14} /></IconButton>
</div>
</li>
))}
</ol>
)}
{picking && <MediaPicker open multiple onClose={() => setPicking(false)}
onPickMany={items => {
const more = Object.fromEntries(items.map(it => [it.id, imageOf(it)]).filter(([, v]) => v))
onChange([...ids, ...items.map(it => it.id).filter(id => more[id])], more)
setPicking(false)
}} />}
</div>
)
}
/** A new look: a name, empty or a copy of the one on screen. */
function NewLook({ looks, current, onClose, onCreate }) {
const { t } = useTranslation('manager')
const [name, setName] = useState('')
const [copy, setCopy] = useState(true)
const taken = looks.some(l => l.name.toLowerCase() === name.trim().toLowerCase())
return (
<Dialog open size="sm" title={t('display.looks.new')} onClose={onClose}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>
<Button disabled={!name.trim() || taken} data-testid="display-look-create"
onClick={() => onCreate({ name: name.trim(), ...(copy ? { copy_of: current.id } : {}) })}>{t('display.looks.create')}</Button>
</>}>
<div className="grid gap-3">
<Field label={t('display.looks.name')} error={taken ? t('display.looks.taken') : undefined}>
<Input value={name} autoFocus maxLength={60} onChange={e => setName(e.target.value)} placeholder={t('display.looks.namePlaceholder')} data-testid="display-look-new-name" />
</Field>
<Switch checked={copy} onChange={setCopy} label={t('display.looks.copyOf', { name: current.name })} />
</div>
</Dialog>
)
}
@@ -18,16 +18,17 @@ export function MediaThumb({ item, className }) {
return <img src={src} alt="" loading="lazy" onError={() => setBroken(true)} className={cx('object-cover bg-surface-3', className)} />
}
/** A grid of library items; `selectedId` marks one (the picker). */
export function MediaGrid({ items, onOpen, selectedId, testid = 'media-grid' }) {
/** A grid of library items; `selectedId` marks one, `selectedIds` (a Set) several (the picker). */
export function MediaGrid({ items, onOpen, selectedId, selectedIds, testid = 'media-grid' }) {
const meta = useMediaMeta()
return (
<ul className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }} data-testid={testid}>
{items.map(item => (
<li key={item.id}>
<button type="button" onClick={() => onOpen(item)} data-testid="media-item" data-id={item.id} data-name={item.name}
aria-pressed={selectedIds ? selectedIds.has(item.id) : undefined}
className={cx('w-full text-left rounded-card border bg-surface overflow-hidden transition-colors duration-fast hover:border-line-strong focus-visible:shadow-focus outline-none',
selectedId === item.id ? 'border-accent ring-2 ring-accent' : 'border-line')}>
selectedId === item.id || selectedIds?.has(item.id) ? 'border-accent ring-2 ring-accent' : 'border-line')}>
<MediaThumb item={item} className="w-full aspect-square" />
<span className="block px-2 pt-1.5 text-label font-medium text-ink truncate" title={item.name}>{item.name}</span>
<span className="block px-2 pb-2 text-caption text-ink-3 truncate">{meta(item)}</span>
@@ -1,5 +1,6 @@
// Pick a picture from the media library (plan step 5.2), or upload one here: an upload made from
// the picker is picked at once. Used by MediaField (products, categories; more places later).
// `multiple` (5.3, a slideshow): tap pictures to select several, then "Add"; uploads are selected.
import { useCallback, useEffect, useRef, useState } from 'react'
import { Upload } from 'lucide-react'
import { errorMessage } from '@xenia/api'
@@ -10,13 +11,15 @@ import { ACCEPT } from './mediaLogic'
import { MediaGrid, UploadQueue } from './MediaParts'
import { useUploadQueue } from './mediaHooks'
export default function MediaPicker({ open, onClose, onPick, kind = 'image', selectedId }) {
export default function MediaPicker({ open, onClose, onPick, onPickMany, multiple = false, kind = 'image', selectedId }) {
const { t } = useTranslation('manager')
const [q, setQ] = useState('')
const [search, setSearch] = useState('')
const [page, setPage] = useState(null)
const [error, setError] = useState(null)
const input = useRef(null)
const [chosen, setChosen] = useState([]) // multiple: the items picked so far, in order
const toggle = item => setChosen(c => (c.some(x => x.id === item.id) ? c.filter(x => x.id !== item.id) : [...c, item]))
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
useEffect(() => {
@@ -26,25 +29,34 @@ export default function MediaPicker({ open, onClose, onPick, kind = 'image', sel
return () => { live = false }
}, [open, kind, search, t])
const { queue, add, clear, summary } = useUploadQueue(useCallback(item => onPick(item, { uploaded: !item.existing }), [onPick]))
const { queue, add, clear, summary } = useUploadQueue(useCallback(item => {
setPage(p => (p && !p.items.some(x => x.id === item.id) ? { ...p, items: [item, ...p.items], total: p.total + 1 } : p))
if (multiple) setChosen(c => (c.some(x => x.id === item.id) ? c : [...c, item]))
else onPick(item, { uploaded: !item.existing })
}, [onPick, multiple]))
return (
<Dialog open={open} size="lg" title={t('media.pickTitle')} onClose={onClose}
footer={<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>}>
footer={<>
<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>
{multiple && <Button disabled={!chosen.length} onClick={() => onPickMany(chosen)} data-testid="media-picker-add">
{t('media.addChosen', { count: chosen.length })}</Button>}
</>}>
<div className="grid gap-3" data-testid="media-picker">
<div className="flex flex-wrap gap-2">
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('media.search')} aria-label={t('media.search')}
className="flex-1 min-w-[10rem]" data-testid="media-picker-search" />
<Button variant="secondary" icon={<Upload size={16} />} onClick={() => input.current?.click()} disabled={summary.busy}>{t('media.uploadNew')}</Button>
<input ref={input} type="file" accept={kind === 'image' ? ACCEPT.split(',').filter(a => a.startsWith('image/')).join(',') : ACCEPT}
className="sr-only" data-testid="media-picker-file" onChange={e => { if (e.target.files?.length) add([e.target.files[0]]); e.target.value = '' }} />
className="sr-only" data-testid="media-picker-file" multiple={multiple} onChange={e => { if (e.target.files?.length) add(multiple ? e.target.files : [e.target.files[0]]); e.target.value = '' }} />
</div>
<UploadQueue queue={queue} summary={summary} onClear={clear} />
{error ? <EmptyState title={error} />
: !page ? <div className="flex justify-center p-6"><Spinner /></div>
: page.items.length === 0 ? <EmptyState title={t(search ? 'media.noMatch' : 'media.empty')} />
: <div className="max-h-[55vh] overflow-auto pr-1">
<MediaGrid items={page.items} selectedId={selectedId} onOpen={item => onPick(item, { uploaded: false })} testid="media-picker-grid" />
<MediaGrid items={page.items} selectedId={multiple ? undefined : selectedId} selectedIds={multiple ? new Set(chosen.map(c => c.id)) : undefined}
onOpen={item => (multiple ? toggle(item) : onPick(item, { uploaded: false }))} testid="media-picker-grid" />
</div>}
</div>
</Dialog>
@@ -10,7 +10,7 @@ import client from '../../api/client'
import { configGroups, configValue, refOptions } from './devicesLogic'
// Where a `ref` field's choices come from (the device list is passed in)
const REF_URLS = { prep_zones: '/api/prep-zones', categories: '/api/products/categories', printers: '/api/system/printers' }
const REF_URLS = { prep_zones: '/api/prep-zones', categories: '/api/products/categories', printers: '/api/system/printers', display_looks: '/api/display/looks' }
export default function DeviceConfigFields({ appKey, fields = [], value, onChange, devices = [], selfId = null }) {
const { t } = useTranslation('manager')
@@ -28,6 +28,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
const zones = lists.prep_zones ?? []
const categories = lists.categories ?? []
const printers = lists.printers ?? []
const looks = lists.display_looks ?? []
if (!fields.length) return null
const base = key => `modules:${appKey}.config.${key}`
@@ -53,7 +54,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
<Field key={f.key} label={label} hint={hint}>
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
options={[{ value: '', label: t(`${base(f.key)}.none`, { defaultValue: t('devices.form.none') }) },
...refOptions(f, { zones, categories, printers, devices, selfId })]} />
...refOptions(f, { zones, categories, printers, looks, devices, selfId })]} />
</Field>
)
}
@@ -85,8 +85,9 @@ export function configGroups(fields = []) {
return out
}
/** Options of a `ref` field: prep zones, categories, printers, or live devices of one app ("devices:<app>"). */
export function refOptions(field, { zones = [], categories = [], printers = [], devices = [], selfId = null } = {}) {
/** Options of a `ref` field: prep zones, categories, printers, customer display looks, or live devices of one app ("devices:<app>"). */
export function refOptions(field, { zones = [], categories = [], printers = [], looks = [], devices = [], selfId = null } = {}) {
if (field.choices_from === 'display_looks') return looks.map(l => ({ value: String(l.id), label: l.name }))
if (field.choices_from === 'prep_zones') return zones.map(z => ({ value: String(z.id), label: z.name }))
if (field.choices_from === 'categories') return categories.map(c => ({ value: String(c.id), label: c.name }))
if (field.choices_from === 'printers') return printers.filter(p => p.is_active !== false).map(p => ({ value: String(p.id), label: p.name }))
+4 -4
View File
@@ -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}} δεν υπάρχει στη βιβλιοθήκη πολυμέσων.",
+37 -8
View File
@@ -628,7 +628,7 @@
},
"display": {
"title": "Οθόνη πελάτη",
"intro": "Η οθόνη προς τους πελάτες στο ταμείο δείχνει την πώληση και το σύνολο όσο χτυπάτε, και \"Ευχαριστούμε\" με τα ρέστα μετά την πληρωμή. Εδώ διαλέγετε τι δείχνει στο ενδιάμεσο.",
"intro": "Η οθόνη που βλέπουν οι πελάτες στο ταμείο δείχνει την πώληση και το σύνολο όσο πουλάτε, και «Ευχαριστούμε» με τα ρέστα μετά την πληρωμή. Ενδιάμεσα δείχνει μια εμφάνιση που σχεδιάζετε εδώ. Φτιάξτε πολλές (π.χ. μια προσφορά, έναν QR κωδικό) και διαλέξτε ποια οθόνη δείχνει ποια.",
"style": "Ανάμεσα στις πωλήσεις, δείξε",
"styles": {
"name": {
@@ -664,7 +664,7 @@
"venueNameHint": "Εμφανίζεται στην οθόνη (και σε άλλες οθόνες).",
"message": "Μια γραμμή κειμένου (προαιρετικά)",
"messageHint": "π.χ. \"Καλώς ήρθατε!\" ή \"Δωρεάν Wi-Fi: Taverna\"",
"theme": "Εμφάνιση",
"theme": "Χρώματα",
"themes": {
"dark": "Σκούρα",
"light": "Φωτεινή"
@@ -678,11 +678,38 @@
},
"qrUrl": "Σύνδεσμος",
"qrCaption": "Κείμενο κάτω από τον κωδικό (προαιρετικά)",
"pickLogo": "Διαλέξτε το λογότυπο",
"pickImage": "Διαλέξτε την εικόνα",
"pickSlides": "Διαλέξτε τις φωτογραφίες, με τη σειρά (ξανά πάτημα για αφαίρεση)",
"upload": "Ανέβασμα εικόνων",
"noImages": "Δεν υπάρχουν εικόνες: ανεβάστε (JPG, PNG, WebP ή GIF, έως 5 MB)."
"pickLogo": "Το λογότυπό σας",
"pickImage": "Η εικόνα",
"pickSlides": "Οι φωτογραφίες, με αυτή τη σειρά",
"addSlides": "Προσθήκη εικόνων",
"noSlides": "Δεν υπάρχουν φωτογραφίες ακόμα: προσθέστε από τη βιβλιοθήκη πολυμέσων.",
"earlier": "Νωρίτερα",
"later": "Αργότερα",
"looks": {
"title": "Εμφανίσεις",
"default": "προεπιλογή",
"isDefault": "Η προεπιλεγμένη εμφάνιση",
"makeDefault": "Ορισμός ως προεπιλογή",
"madeDefault": "Είναι πλέον η προεπιλεγμένη εμφάνιση.",
"screens_one": "{{count}} οθόνη",
"screens_other": "{{count}} οθόνες",
"new": "Νέα εμφάνιση",
"create": "Δημιουργία",
"created": "Η εμφάνιση δημιουργήθηκε.",
"name": "Όνομα εμφάνισης",
"namePlaceholder": "π.χ. Καλοκαιρινή προσφορά",
"taken": "Υπάρχει ήδη εμφάνιση με αυτό το όνομα.",
"copyOf": "Ξεκινήστε από αντίγραφο της «{{name}}»",
"unsaved": "Δεν έχει αποθηκευτεί",
"discard": "Αυτή η εμφάνιση έχει αλλαγές που δεν αποθηκεύτηκαν. Να φύγετε;",
"whichScreen": "Ποια οθόνη δείχνει ποια εμφάνιση",
"noScreens": "Δεν έχει συνδεθεί ακόμα οθόνη πελάτη (Συσκευές → Σύνδεση συσκευής).",
"followDefault": "Η προεπιλεγμένη εμφάνιση ({{name}})",
"lookFor": "Εμφάνιση της {{name}}",
"deleteTitle": "Διαγραφή «{{name}}»;",
"deleteBody": "Οι οθόνες που τη δείχνουν επιστρέφουν στην προεπιλεγμένη εμφάνιση ({{name}}). Οι εικόνες της μένουν στη βιβλιοθήκη πολυμέσων.",
"deleted": "Η εμφάνιση διαγράφηκε."
}
},
"calls": {
"title": "Αναγνώριση κλήσης",
@@ -767,6 +794,8 @@
"fromLibrary": "Από τη βιβλιοθήκη",
"removePhoto": "Αφαίρεση",
"nameAfterProduct": "Ονομασία με το όνομα του προϊόντος",
"nameAfterCategory": "Ονομασία με το όνομα της κατηγορίας"
"nameAfterCategory": "Ονομασία με το όνομα της κατηγορίας",
"addChosen_one": "Προσθήκη {{count}} εικόνας",
"addChosen_other": "Προσθήκη {{count}} εικόνων"
}
}
+7
View File
@@ -87,6 +87,13 @@
},
"permissions": {
"manage": "Ρύθμιση της οθόνης πελάτη (οθόνη αναμονής, εικόνες)"
},
"config": {
"look": {
"label": "Οθόνη αναμονής",
"hint": "Ποια εμφάνιση δείχνει ανάμεσα στις πωλήσεις (Ρυθμίσεις → Οθόνη πελάτη).",
"none": "Η προεπιλεγμένη εμφάνιση"
}
}
},
"expenses": {
+4 -4
View File
@@ -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.",
+37 -8
View File
@@ -628,7 +628,7 @@
},
"display": {
"title": "Customer display",
"intro": "The screen facing your customers at the counter shows the sale and the total while you sell, and \"Thank you\" with the change after payment. Here you choose what it shows in between.",
"intro": "The screen facing your customers at the counter shows the sale and the total while you sell, and \"Thank you\" with the change after payment. In between it shows a look you design here. Make several looks (e.g. a menu promo, a QR code) and choose which display shows which.",
"style": "Between sales, show",
"styles": {
"name": {
@@ -664,7 +664,7 @@
"venueNameHint": "Shown on the display (and other screens).",
"message": "A line of text (optional)",
"messageHint": "e.g. \"Welcome!\" or \"Free Wi-Fi: Taverna\"",
"theme": "Look",
"theme": "Colours",
"themes": {
"dark": "Dark",
"light": "Light"
@@ -678,11 +678,38 @@
},
"qrUrl": "Link",
"qrCaption": "Text under the code (optional)",
"pickLogo": "Pick your logo",
"pickImage": "Pick the picture",
"pickSlides": "Pick the photos, in order (tap again to remove)",
"upload": "Upload images",
"noImages": "No images yet: upload some (JPG, PNG, WebP or GIF, up to 5 MB)."
"pickLogo": "Your logo",
"pickImage": "The picture",
"pickSlides": "The photos, in this order",
"addSlides": "Add pictures",
"noSlides": "No photos yet: add some from the media library.",
"earlier": "Earlier",
"later": "Later",
"looks": {
"title": "Looks",
"default": "default",
"isDefault": "The default look",
"makeDefault": "Make default",
"madeDefault": "Now the default look.",
"screens_one": "{{count}} display",
"screens_other": "{{count}} displays",
"new": "New look",
"create": "Create",
"created": "Look created.",
"name": "Name of the look",
"namePlaceholder": "e.g. Summer promo",
"taken": "There is already a look with this name.",
"copyOf": "Start from a copy of \"{{name}}\"",
"unsaved": "Not saved yet",
"discard": "This look has changes that aren't saved. Leave it anyway?",
"whichScreen": "Which display shows which look",
"noScreens": "No customer display is paired yet (Devices → Pair a device).",
"followDefault": "The default look ({{name}})",
"lookFor": "Look of {{name}}",
"deleteTitle": "Delete \"{{name}}\"?",
"deleteBody": "Displays showing it go back to the default look ({{name}}). Its pictures stay in the media library.",
"deleted": "Look deleted."
}
},
"calls": {
"title": "Caller ID",
@@ -767,6 +794,8 @@
"fromLibrary": "From the library",
"removePhoto": "Remove",
"nameAfterProduct": "Name it after the product",
"nameAfterCategory": "Name it after the category"
"nameAfterCategory": "Name it after the category",
"addChosen_one": "Add {{count}} picture",
"addChosen_other": "Add {{count}} pictures"
}
}
+7
View File
@@ -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": {
+2 -2
View File
@@ -614,10 +614,10 @@ try {
await page.getByTestId('display-save').click()
let idleCfg = null
for (let i = 0; i < 30 && idleCfg?.style !== 'qr'; i++) {
idleCfg = (await api('GET', '/api/display/settings', { token: boss })).idle
idleCfg = (await api('GET', '/api/display/looks', { token: boss })).find(l => l.is_default)?.config
if (idleCfg?.style !== 'qr') await sleep(100)
}
r.check('settings: customer display → a QR code to the online ordering, with a caption', idleCfg?.style === 'qr'
r.check('settings: customer display → the default look: a QR code to the online ordering, with a caption', idleCfg?.style === 'qr'
&& idleCfg.qr_target === 'ordering' && idleCfg.qr_caption === 'Order online', JSON.stringify(idleCfg))
await page.screenshot({ path: path.join(OUT, 'manager-display-settings.png'), fullPage: true })
+26
View File
@@ -156,6 +156,32 @@ try {
(await page.getByTestId('media-used-by').innerText().catch(() => '')).includes(p1.name) && await page.getByTestId('media-delete').isDisabled())
await page.keyboard.press('Escape')
// ── 5.3: the customer display's looks pick their pictures from the library ──
await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {})
await page.goto(`${MANAGER}/settings`)
await page.getByText('Customer display', { exact: true }).click()
await page.getByTestId('display-look-new').click({ timeout: 15_000 })
await page.getByTestId('display-look-new-name').fill('Promo')
await page.getByTestId('display-look-create').click()
await page.locator('[data-testid="display-look"][data-name="Promo"][aria-selected="true"]').waitFor({ timeout: 10_000 })
await page.getByTestId('display-style-slideshow').click()
await page.getByTestId('display-slides-add').click()
const picker = page.getByTestId('media-picker')
for (const i of [0, 1, 2]) await picker.getByTestId('media-item').nth(i).click()
await page.getByTestId('media-picker-add').click()
r.check('5.3: a new look "Promo": three pictures picked at once from the library, in order',
await page.getByTestId('display-slide-item').count() === 3)
await page.getByTestId('display-save').click()
await sleep(1000)
const looks = await api('GET', '/api/display/looks', { token: boss })
const promo = looks.find(l => l.name === 'Promo')
r.check('5.3: saved: the look is a slideshow of three library pictures; the default look is unchanged',
promo?.config.style === 'slideshow' && promo.config.slides.length === 3 && promo.preview.slide_urls.length === 3
&& looks.find(l => l.is_default)?.name === 'Main', JSON.stringify(looks.map(l => [l.name, l.config.style, l.config.slides])))
await page.screenshot({ path: path.join(OUT, 'media-display-looks.png'), fullPage: true })
const usedSlide = await api('DELETE', `/api/media/${promo.config.slides[0]}`, { token: boss }).then(() => 'deleted', e => e.message)
r.check('5.3: a picture in a look cannot be deleted from the library', usedSlide.includes('409'), usedSlide)
// ── The waiter's phone: photos fetched ahead, shown offline ─────────────────
const phone = await browser.newContext({ viewport: { width: 393, height: 852 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true })
const w = await phone.newPage()
+24 -11
View File
@@ -15,8 +15,9 @@
import http from 'node:http'
import net from 'node:net'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, OUT, reporter, sleep } from './lib/env.mjs'
import { BROWSER_CHANNEL, OUT, PYTHON, reporter, sleep, waitFor } from './lib/env.mjs'
import { startBackend, startTerminalVite } from './lib/proc.mjs'
import { supportLogin } from './lib/support.mjs'
@@ -715,24 +716,36 @@ try {
r.check('3.4: paid → "Thank you" with the change', await shown(myDisplay, 'display-paid', 5000)
&& (await myDisplay.getByTestId('display-paid').textContent()).includes('Thank you'))
await myDisplay.screenshot({ path: path.join(OUT, 'terminal-display-paid.png') })
// the venue's choice: a QR code to its online ordering, then a slideshow of its photos
await api('PUT', '/api/display/settings', { token: boss, body: { style: 'qr', qr_target: 'ordering', qr_caption: 'Order online', theme: 'light' } })
r.check('3.4: the idle screen follows the venue\'s settings at once (a QR code to its ordering, light)',
// the venue's choice: a QR code to its online ordering, then a slideshow of its photos (a look; 5.3)
const main = (await api('GET', '/api/display/looks', { token: boss })).find(l => l.is_default)
await api('PUT', `/api/display/looks/${main.id}`, { token: boss, body: { config: { style: 'qr', qr_target: 'ordering', qr_caption: 'Order online', theme: 'light' } } })
r.check('3.4: the idle screen follows the look at once (a QR code to the venue ordering, light)',
await myDisplay.waitForFunction(() => document.querySelector('[data-testid="display-qr"]'), null, { timeout: 20_000 }).then(() => true).catch(() => false)
&& (await myDisplay.getByTestId('display-qr').getAttribute('data-link')).includes('/order/') && await myDisplay.evaluate(() => document.documentElement.dataset.theme) === 'light')
await myDisplay.screenshot({ path: path.join(OUT, 'terminal-display-qr.png') })
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
const uploadImg = async () => {
const uploadImg = async (rgb) => {
const jpg = execFileSync(PYTHON, ['-c', `import io,sys;from PIL import Image;b=io.BytesIO();Image.new('RGB',(1280,720),(${rgb})).save(b,'JPEG');sys.stdout.buffer.write(b.getvalue())`])
const form = new FormData()
form.append('file', new Blob([png], { type: 'image/png' }), 'promo.png')
const res = await fetch(`${backend.url}/api/display/media`, { method: 'POST', headers: { authorization: `Bearer ${boss}` }, body: form })
form.append('file', new Blob([jpg], { type: 'image/jpeg' }), 'promo.jpg')
const res = await fetch(`${backend.url}/api/media`, { method: 'POST', headers: { authorization: `Bearer ${boss}` }, body: form })
return res.json()
}
const [a, b] = [await uploadImg(), await uploadImg()]
await api('PUT', '/api/display/settings', { token: boss, body: { style: 'slideshow', slides: [a.name, b.name], slide_seconds: 3, message: 'Today: 2 for 1' } })
r.check('3.4: …or a slideshow of its photos, with its line of text',
const [a, b, c] = [await uploadImg('200,40,40'), await uploadImg('40,200,40'), await uploadImg('40,40,200')]
await api('PUT', `/api/display/looks/${main.id}`, { token: boss, body: { config: { style: 'slideshow', slides: [a.id, b.id], slide_seconds: 3, message: 'Today: 2 for 1' } } })
r.check('3.4: …or a slideshow of its photos (from the media library), with its line of text',
await myDisplay.waitForFunction(() => document.querySelectorAll('[data-testid="display-slide"]').length === 2, null, { timeout: 20_000 }).then(() => true).catch(() => false)
&& (await myDisplay.getByTestId('display-message').textContent()) === 'Today: 2 for 1')
// 5.3: the other display gets its own look, another slideshow
const promo = await api('POST', '/api/display/looks', { token: boss, body: { name: 'Promo', config: { style: 'slideshow', slides: [c.id], slide_seconds: 5 } } })
const otherId = (await api('GET', '/api/display/displays', { token: boss })).find(d => d.name === 'Display elsewhere').id
await api('PUT', `/api/display/displays/${otherId}/look`, { token: boss, body: { look_id: promo.id } })
const slidesOf = page => page.evaluate(() => [...document.querySelectorAll('[data-testid="display-slide"]')].map(e => e.getAttribute('src') || e.style.backgroundImage || ''))
const otherSlides = await waitFor(async () => { const s = await slidesOf(otherDisplay); return s.length === 1 ? s : null }, 20_000, 300)
const mySlides = await slidesOf(myDisplay)
r.check('5.3: two displays, two slideshows from the library (each display its own look)',
!!otherSlides && otherSlides[0].includes(c.sha256) && mySlides.length === 2 && mySlides.every(u => !u.includes(c.sha256)),
JSON.stringify({ mine: mySlides.map(u => u.slice(-40)), other: otherSlides?.map(u => u.slice(-40)) }))
await otherDisplay.screenshot({ path: path.join(OUT, 'terminal-display-promo.png') })
// ── 3.5: caller ID at the counter ────────────────────────────────────────
await api('PUT', '/api/platform/modules/caller_id', { token: boss, body: { enabled: true } }).catch(() => {})
await api('POST', '/api/customers/', { token: boss, body: { name: 'Kostas Regular', phone: '+30 697 555 1234', notes: 'Always extra tzatziki' } })