feat(terminal): the customer display, with an idle screen each venue designs
Plan step 3.4. Owner (2026-11-16): the idle screen is configurable per venue. - routers/customer_display.py (module customer_display, /api/display): the counter POS pushes its state (POST /api/display/state: idle | cart | paid with lines, total, paid, change); only the displays linked to that POS get `display.state`; the last state is kept in memory for a display that reconnects (GET /api/display/state). pos_counter's device scope includes customer_display.state. - The idle screen: setting customer_display.idle (name, logo, logo + name, blank, one image, slideshow, QR code to the online ordering / QR menu / any link; a line of text; dark or light); images uploaded to /app/data/display_media (JPG/PNG/WebP/GIF ≤ 5 MB, random names, served publicly on the LAN); a change sends `display.settings` to every display. New key customer_display.manage (owners, store managers; migration 0022). - Terminal: CustomerDisplayApp (cart with a large total, "Thank you" with the change for 12 s, the venue's idle screen, its theme), logic.js (unit-tested); the POS pushes from the sale cart and the payment dialog (tables, online orders too) via useDisplay(). qrcode.react added to the terminal (already in the workspace). - Manager: Settings → Customer display (style cards, venue name, text, look, slide seconds, QR target/link/caption, image upload/pick/order/delete). - Tests: tests/test_customer_display.py (3), terminal display.test.mjs (3); e2e terminal (linked vs unlinked display, < 1 s, paid, QR and slideshow idle screens), manager (the settings tab). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -46,6 +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/ws.py` | Real-time event stream (seq + cursor replay) |
|
||||
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
||||
| `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below |
|
||||
|
||||
@@ -85,6 +85,10 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
|
||||
"online.not_found": (404, "Online order {order_id} not found."),
|
||||
"online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."),
|
||||
"display.media_unknown": (404, "Image {name} not found."),
|
||||
"display.media_type": (422, "Upload a JPG, PNG, WebP or GIF image."),
|
||||
"display.media_too_big": (413, "The image is too big (at most {max_mb} MB)."),
|
||||
"display.qr_url_missing": (422, "Enter the link the QR code opens."),
|
||||
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
||||
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
||||
"reservation.table_unknown": (404, "Table {table_id} not found."),
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""key customer_display.manage for owners and store managers (plan step 3.4)
|
||||
|
||||
The idle screen is a setting (customer_display.idle) and its images are files, so no table.
|
||||
|
||||
Revision ID: 0022_customer_display_key
|
||||
Revises: 0021_table_qr_token
|
||||
Create Date: 2026-11-17 10:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '0022_customer_display_key'
|
||||
down_revision = '0021_table_qr_token'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||
"select id, 'customer_display.manage' from users where role in ('owner', 'store_manager')"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(sa.text("delete from user_permissions where key = 'customer_display.manage'"))
|
||||
@@ -1,14 +1,23 @@
|
||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||
from core.modules.model import DeviceApp, Limit, Module
|
||||
from core.modules.model import DeviceApp, Limit, Module, Mount, Perm, SettingDef
|
||||
|
||||
MODULE = Module(
|
||||
key='customer_display',
|
||||
kind='app',
|
||||
name='Customer display',
|
||||
description='Screen facing the customer at a counter POS (phase 3).',
|
||||
description='Screen facing the customer at a counter POS: the sale, the total, the change, and an idle screen the venue designs (plan step 3.4).',
|
||||
depends=('pos_counter',),
|
||||
permissions=(
|
||||
Perm('customer_display.manage', 'Set up the customer display (idle screen, images)', roles=('owner', 'store_manager')),
|
||||
),
|
||||
limits=(
|
||||
Limit('devices', 'Number of customer displays', free=0, licensed_default=1),
|
||||
),
|
||||
settings=(
|
||||
SettingDef('customer_display.idle', '{}', 'What customer displays show between sales: style (name, logo, name_logo, blank, image, slideshow, qr), message, images, slide seconds, QR target, theme. Edited in Settings > Customer display.', type='json'),
|
||||
),
|
||||
routers=(
|
||||
Mount('routers.customer_display', '/api/display'),
|
||||
),
|
||||
device_app=DeviceApp(login_modes=('none',), scope=()),
|
||||
)
|
||||
|
||||
@@ -27,7 +27,8 @@ MODULE = Module(
|
||||
limits=(
|
||||
Limit('devices', 'Number of counter terminals', free=0, licensed_default=1),
|
||||
),
|
||||
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*', 'connect_orders.*'),
|
||||
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*', 'connect_orders.*',
|
||||
'customer_display.state'), # 3.4: it tells its display what to show
|
||||
config=POS_CONFIG),
|
||||
routers=(
|
||||
Mount('routers.pos', '/api/pos'),
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""The customer display (plan step 3.4): a screen facing the customer, linked to a counter POS.
|
||||
|
||||
The POS pushes what the customer should see; the display (paired, sign-in "none") shows it:
|
||||
|
||||
POST /api/display/state (the POS screen) {mode: idle|cart|paid, lines, total, paid, change}
|
||||
→ event `display.state` to the displays linked to this POS only
|
||||
GET /api/display/state (a display) what to show now: the linked POS's last state,
|
||||
the idle screen, the venue's name
|
||||
|
||||
What the display shows while idle is the venue's choice (owner, 2026-11-16: "configurable, so
|
||||
each venue can choose their style"): the name, the logo, both, nothing, one image, a slideshow
|
||||
of photos, or a QR code (the venue's ordering link, its QR menu, or any link), with an optional
|
||||
line of text, light or dark. Setting `customer_display.idle` (JSON, IdleBody); images are files
|
||||
the venue uploads here (data/display_media, served to the displays by name):
|
||||
|
||||
GET /api/display/settings (customer_display.manage) the idle screen + the uploaded images
|
||||
PUT /api/display/settings save it → `display.settings` to every display
|
||||
POST /api/display/media upload an image (jpg/png/webp/gif, ≤ 5 MB)
|
||||
DELETE /api/display/media/{name}
|
||||
GET /api/display/media/{name} (public, LAN) the image itself
|
||||
|
||||
The POS's last state is kept in memory (a display that reconnects asks for it); after a restart
|
||||
the displays show the idle screen until the next sale.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import uuid
|
||||
from typing import List, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, File, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.access.deps import public, require, require_device
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
from services.ws_bus import broadcast_sync
|
||||
|
||||
router = APIRouter()
|
||||
KEY = "customer_display.manage"
|
||||
SETTING = "customer_display.idle"
|
||||
MEDIA_DIR = os.environ.get("XENIA_DISPLAY_MEDIA_DIR", "/app/data/display_media")
|
||||
MAX_BYTES = 5 * 1024 * 1024
|
||||
TYPES = {"image/jpeg": "jpg", "image/png": "png", "image/webp": "webp", "image/gif": "gif"}
|
||||
NAME = re.compile(r"^[0-9a-f]{32}\.(jpg|png|webp|gif)$")
|
||||
STYLES = ("name", "logo", "name_logo", "blank", "image", "slideshow", "qr")
|
||||
|
||||
_last: dict[int, dict] = {} # POS device id → its last state
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
# ── shapes ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
class IdleBody(BaseModel):
|
||||
style: Literal["name", "logo", "name_logo", "blank", "image", "slideshow", "qr"] = "name"
|
||||
message: Optional[str] = Field(default=None, max_length=120) # a line under the name/logo/QR
|
||||
logo: Optional[str] = None # an uploaded image's name
|
||||
image: Optional[str] = None
|
||||
slides: List[str] = Field(default_factory=list, max_length=20)
|
||||
slide_seconds: int = Field(default=8, ge=3, le=120)
|
||||
qr_target: Literal["ordering", "menu", "custom"] = "ordering"
|
||||
qr_url: Optional[str] = Field(default=None, max_length=300)
|
||||
qr_caption: Optional[str] = Field(default=None, max_length=80)
|
||||
theme: Literal["dark", "light"] = "dark"
|
||||
|
||||
@field_validator("qr_url")
|
||||
@classmethod
|
||||
def _url(cls, v):
|
||||
v = (v or "").strip() or None
|
||||
if v and not re.match(r"^https?://", v):
|
||||
raise ValueError("a link starts with http:// or https://")
|
||||
return v
|
||||
|
||||
@field_validator("message", "qr_caption")
|
||||
@classmethod
|
||||
def _text(cls, v):
|
||||
return (v or "").strip() or None
|
||||
|
||||
|
||||
class Line(BaseModel):
|
||||
name: str = Field(max_length=120)
|
||||
quantity: Optional[float] = Field(default=None, ge=0, le=9999) # None: the name says it ("2× Burger")
|
||||
total: float = Field(ge=-100000, le=100000)
|
||||
options: List[str] = Field(default_factory=list, max_length=20)
|
||||
|
||||
|
||||
class StateBody(BaseModel):
|
||||
mode: Literal["idle", "cart", "paid"]
|
||||
lines: List[Line] = Field(default_factory=list, max_length=200)
|
||||
total: float = Field(default=0.0, ge=-100000, le=100000)
|
||||
paid: Optional[float] = Field(default=None, ge=0, le=100000)
|
||||
change: Optional[float] = Field(default=None, ge=0, le=100000)
|
||||
|
||||
|
||||
# ── helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _setting(db, key: str, default: str = "") -> str:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
return row.value if row and row.value is not None else default
|
||||
|
||||
|
||||
def idle_settings(db) -> dict:
|
||||
try:
|
||||
raw = json.loads(_setting(db, SETTING, "{}") or "{}")
|
||||
except ValueError:
|
||||
raw = {}
|
||||
try:
|
||||
return IdleBody(**{k: v for k, v in (raw or {}).items() if k in IdleBody.model_fields}).model_dump()
|
||||
except Exception:
|
||||
return IdleBody().model_dump()
|
||||
|
||||
|
||||
def _media_names() -> list[str]:
|
||||
try:
|
||||
return sorted(n for n in os.listdir(MEDIA_DIR) if NAME.match(n))
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
|
||||
|
||||
def media_url(name: str | None) -> str | None:
|
||||
return f"/api/display/media/{name}" if name else None
|
||||
|
||||
|
||||
def _qr_link(cfg: dict) -> str | None:
|
||||
if cfg["qr_target"] == "custom":
|
||||
return cfg["qr_url"]
|
||||
from config import settings
|
||||
from services.table_qr import apps_url, menu_url
|
||||
if cfg["qr_target"] == "menu":
|
||||
return menu_url()
|
||||
return f"{apps_url()}/order/{settings.SITE_ID or ''}"
|
||||
|
||||
|
||||
def idle_out(db) -> dict:
|
||||
"""The idle screen as a display shows it: the settings with image addresses and the QR link."""
|
||||
cfg = idle_settings(db)
|
||||
have = set(_media_names())
|
||||
keep = lambda n: n if n in have else None # noqa: E731 (a deleted image just disappears)
|
||||
return {**cfg, "logo_url": media_url(keep(cfg["logo"])), "image_url": media_url(keep(cfg["image"])),
|
||||
"slide_urls": [media_url(n) for n in cfg["slides"] if n in have],
|
||||
"qr_link": _qr_link(cfg) if cfg["style"] == "qr" else None}
|
||||
|
||||
|
||||
def _displays_of(db, pos_id: int) -> list[int]:
|
||||
from models.device import Device
|
||||
return [i for (i,) in db.query(Device.id).filter(Device.app_key == "customer_display", Device.linked_device_id == pos_id,
|
||||
Device.revoked_at.is_(None))]
|
||||
|
||||
|
||||
def _all_displays(db) -> list[int]:
|
||||
from models.device import Device
|
||||
return [i for (i,) in db.query(Device.id).filter(Device.app_key == "customer_display", Device.revoked_at.is_(None))]
|
||||
|
||||
|
||||
# ── the POS and the display ────────────────────────────────────────────────────
|
||||
|
||||
@router.post("/state", status_code=204)
|
||||
def push_state(body: StateBody, db: Session = Depends(get_db), dev=Depends(require_device("pos_counter"))):
|
||||
"""The counter POS says what its customer should see. Only its own displays hear it."""
|
||||
state = body.model_dump()
|
||||
with _lock:
|
||||
if _last.get(dev.id) == state:
|
||||
return None
|
||||
_last[dev.id] = state
|
||||
displays = _displays_of(db, dev.id)
|
||||
if displays:
|
||||
broadcast_sync("display.state", state, device_ids=displays)
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/state")
|
||||
def display_state(db: Session = Depends(get_db), dev=Depends(require_device("customer_display"))):
|
||||
from models.device import Device
|
||||
pos = db.get(Device, dev.linked_device_id) if dev.linked_device_id else None
|
||||
with _lock:
|
||||
state = _last.get(pos.id) if pos is not None else None
|
||||
return {"venue_name": _setting(db, "venue.name", "") or None,
|
||||
"linked": pos is not None and pos.revoked_at is None,
|
||||
"idle": idle_out(db),
|
||||
"state": state or {"mode": "idle", "lines": [], "total": 0.0, "paid": None, "change": None}}
|
||||
|
||||
|
||||
# ── the venue's settings and images ────────────────────────────────────────────
|
||||
|
||||
@router.get("/settings")
|
||||
def get_settings(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
return {"idle": idle_settings(db), "media": [{"name": n, "url": media_url(n)} for n in _media_names()],
|
||||
"preview": idle_out(db), "venue_name": _setting(db, "venue.name", "") or None}
|
||||
|
||||
|
||||
@router.put("/settings")
|
||||
def put_settings(body: IdleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from models.settings import PosSettings
|
||||
have = set(_media_names())
|
||||
for name in [body.logo, body.image, *body.slides]:
|
||||
if name and name not in have:
|
||||
raise XeniaError("display.media_unknown", name=name)
|
||||
if body.style == "qr" and body.qr_target == "custom" and not body.qr_url:
|
||||
raise XeniaError("display.qr_url_missing")
|
||||
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
|
||||
value = json.dumps(body.model_dump())
|
||||
if row is None:
|
||||
db.add(PosSettings(key=SETTING, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
displays = _all_displays(db)
|
||||
if displays:
|
||||
broadcast_sync("display.settings", {}, device_ids=displays)
|
||||
return get_settings(db, user)
|
||||
|
||||
|
||||
@router.post("/media", status_code=201)
|
||||
async def upload_media(file: UploadFile = File(...), user=Depends(require(KEY))):
|
||||
ext = TYPES.get((file.content_type or "").lower())
|
||||
if ext is None:
|
||||
raise XeniaError("display.media_type")
|
||||
data = await file.read(MAX_BYTES + 1)
|
||||
if len(data) > MAX_BYTES:
|
||||
raise XeniaError("display.media_too_big", max_mb=MAX_BYTES // (1024 * 1024))
|
||||
os.makedirs(MEDIA_DIR, exist_ok=True)
|
||||
name = f"{uuid.uuid4().hex}.{ext}"
|
||||
with open(os.path.join(MEDIA_DIR, name), "wb") as f:
|
||||
f.write(data)
|
||||
return {"name": name, "url": media_url(name)}
|
||||
|
||||
|
||||
@router.delete("/media/{name}", status_code=204)
|
||||
def delete_media(name: str, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
if not NAME.match(name) or name not in _media_names():
|
||||
raise XeniaError("display.media_unknown", name=name)
|
||||
os.remove(os.path.join(MEDIA_DIR, name))
|
||||
cfg = idle_settings(db) # drop it from the idle screen too
|
||||
if name in (cfg["logo"], cfg["image"]) or name in cfg["slides"]:
|
||||
cfg["logo"] = None if cfg["logo"] == name else cfg["logo"]
|
||||
cfg["image"] = None if cfg["image"] == name else cfg["image"]
|
||||
cfg["slides"] = [n for n in cfg["slides"] if n != name]
|
||||
from models.settings import PosSettings
|
||||
db.query(PosSettings).filter(PosSettings.key == SETTING).update({PosSettings.value: json.dumps(cfg)})
|
||||
db.commit()
|
||||
displays = _all_displays(db)
|
||||
if displays:
|
||||
broadcast_sync("display.settings", {}, device_ids=displays)
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/media/{name}", dependencies=[Depends(public())])
|
||||
def get_media(name: str):
|
||||
"""The image itself: the displays load it with a plain <img> (no headers). Names are random."""
|
||||
if not NAME.match(name) or not os.path.exists(os.path.join(MEDIA_DIR, name)):
|
||||
raise XeniaError("display.media_unknown", name=name)
|
||||
return FileResponse(os.path.join(MEDIA_DIR, name), headers={"Cache-Control": "public, max-age=86400"})
|
||||
@@ -0,0 +1,107 @@
|
||||
"""The customer display (plan step 3.4): a POS pushes what its customer sees, only its own
|
||||
displays hear it; the idle screen is the venue's design (name, logo, both, blank, an image, a
|
||||
slideshow, a QR code), with images the venue uploads."""
|
||||
import io
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
|
||||
PNG = (b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
|
||||
b"\x00\x00\x00\rIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def media_dir(tmp_path, monkeypatch):
|
||||
import routers.customer_display as cd
|
||||
monkeypatch.setattr(cd, "MEDIA_DIR", str(tmp_path / "media"))
|
||||
cd._last.clear()
|
||||
return tmp_path / "media"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def counters(client, owner_h, pair):
|
||||
"""Two counters, each with its own customer display."""
|
||||
out = {}
|
||||
for n in (1, 2):
|
||||
pos_token, pos = pair("pos_counter", f"Till {n}")
|
||||
disp_token, disp = pair("customer_display", f"Display {n}", linked_device_id=pos.json()["id"])
|
||||
assert disp.status_code == 201, disp.text
|
||||
out[n] = {"pos": {"X-Xenia-Device": pos_token}, "display": {"X-Xenia-Device": disp_token},
|
||||
"pos_id": pos.json()["id"], "display_id": disp.json()["id"]}
|
||||
return out
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sent(monkeypatch):
|
||||
import routers.customer_display as cd
|
||||
got = []
|
||||
real = cd.broadcast_sync
|
||||
monkeypatch.setattr(cd, "broadcast_sync", lambda kind, data, **kw: (got.append((kind, data, kw)), real(kind, data, **kw)))
|
||||
return got
|
||||
|
||||
|
||||
CART = {"mode": "cart", "lines": [{"name": "Freddo", "quantity": 2, "total": 6.0}, {"name": "Toast", "quantity": 1, "total": 3.5,
|
||||
"options": ["no ham"]}], "total": 9.5}
|
||||
|
||||
|
||||
def test_a_sale_shows_only_on_its_own_display(client, counters, sent):
|
||||
one, two = counters[1], counters[2]
|
||||
assert client.post("/api/display/state", headers=one["pos"], json=CART).status_code == 204
|
||||
assert [(k, kw["device_ids"]) for k, _, kw in sent] == [("display.state", [one["display_id"]])]
|
||||
s1 = client.get("/api/display/state", headers=one["display"]).json()
|
||||
assert s1["linked"] is True and s1["state"]["mode"] == "cart" and s1["state"]["total"] == 9.5
|
||||
assert [line["name"] for line in s1["state"]["lines"]] == ["Freddo", "Toast"]
|
||||
assert client.get("/api/display/state", headers=two["display"]).json()["state"]["mode"] == "idle"
|
||||
# the same state again: nothing new to send
|
||||
client.post("/api/display/state", headers=one["pos"], json=CART)
|
||||
assert len(sent) == 1
|
||||
client.post("/api/display/state", headers=one["pos"], json={"mode": "paid", "total": 9.5, "paid": 20, "change": 10.5})
|
||||
assert sent[-1][1]["change"] == 10.5
|
||||
# only a POS pushes, only a display reads
|
||||
assert err(client.post("/api/display/state", headers=one["display"], json=CART)) == "device.out_of_scope"
|
||||
assert err(client.get("/api/display/state", headers=one["pos"])) == "device.out_of_scope"
|
||||
assert err(client.post("/api/display/state", json=CART)) == "device.not_paired"
|
||||
assert client.post("/api/display/state", headers=one["pos"], json={"mode": "dance"}).status_code == 422
|
||||
|
||||
|
||||
def test_the_idle_screen_is_the_venues_design(client, owner_h, counters, sent, media_dir, monkeypatch):
|
||||
from services import cloud_sync
|
||||
monkeypatch.setitem(cloud_sync.license_state, "apps_url", "https://menu.example.com")
|
||||
monkeypatch.setattr(cloud_sync.settings, "SITE_ID", "taverna-1")
|
||||
s = client.get("/api/display/settings", headers=owner_h).json()
|
||||
assert s["idle"]["style"] == "name" and s["media"] == []
|
||||
up = lambda data, ctype="image/png": client.post("/api/display/media", headers=owner_h, # noqa: E731
|
||||
files={"file": ("x.png", io.BytesIO(data), ctype)})
|
||||
logo, photo = up(PNG).json(), up(PNG).json()
|
||||
assert logo["url"].startswith("/api/display/media/") and len(list(media_dir.iterdir())) == 2
|
||||
assert err(up(b"hello", "text/plain")) == "display.media_type"
|
||||
assert client.get(logo["url"]).content == PNG # the displays load it with <img>
|
||||
assert client.get("/api/display/media/../../secret.png").status_code == 404
|
||||
# a slideshow of the two photos, with a line of text
|
||||
body = {"style": "slideshow", "slides": [logo["name"], photo["name"]], "slide_seconds": 5, "message": "Kalimera!"}
|
||||
r = client.put("/api/display/settings", headers=owner_h, json=body)
|
||||
assert r.status_code == 200, r.text
|
||||
assert sorted(kw["device_ids"] for k, _, kw in sent if k == "display.settings")[0] == sorted([counters[1]["display_id"], counters[2]["display_id"]])
|
||||
idle = client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]
|
||||
assert idle["style"] == "slideshow" and idle["slide_urls"] == [logo["url"], photo["url"]] and idle["message"] == "Kalimera!"
|
||||
# a QR code: the venue's ordering link, or any link
|
||||
client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "ordering", "qr_caption": "Order online"})
|
||||
assert client.get("/api/display/state", headers=counters[1]["display"]).json()["idle"]["qr_link"] == "https://menu.example.com/order/taverna-1"
|
||||
assert err(client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "custom"})) == "display.qr_url_missing"
|
||||
assert client.put("/api/display/settings", headers=owner_h, json={"style": "qr", "qr_target": "custom", "qr_url": "javascript:x"}).status_code == 422
|
||||
# an image that isn't there; deleting one takes it off the screen
|
||||
assert err(client.put("/api/display/settings", headers=owner_h, json={"style": "logo", "logo": "0" * 32 + ".png"})) == "display.media_unknown"
|
||||
client.put("/api/display/settings", headers=owner_h, json={"style": "name_logo", "logo": logo["name"], "theme": "light"})
|
||||
assert client.delete(f"/api/display/media/{logo['name']}", headers=owner_h).status_code == 204
|
||||
after = client.get("/api/display/settings", headers=owner_h).json()
|
||||
assert after["idle"]["logo"] is None and [m["name"] for m in after["media"]] == [photo["name"]] and after["idle"]["theme"] == "light"
|
||||
|
||||
|
||||
def test_settings_need_the_key(client, make_user):
|
||||
from tests.conftest import TEST_PASSWORD
|
||||
waiter = make_user(role="waiter", username="w_display")
|
||||
tok = client.post("/api/auth/login", json={"client": "manager", "username": "w_display", "password": TEST_PASSWORD}).json().get("access_token")
|
||||
h = {"Authorization": f"Bearer {tok}"} if tok else {}
|
||||
assert client.get("/api/display/settings", headers=h).status_code in (401, 403)
|
||||
assert waiter.id
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { useCan, useModule } from '@xenia/access'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import CustomerDisplaySettings from './sections/CustomerDisplaySettings'
|
||||
import VenueSettings from './sections/VenueSettings'
|
||||
import AppInfoTab from './tabs/AppInfoTab'
|
||||
import ColoursTab from './tabs/ColoursTab'
|
||||
@@ -10,12 +12,16 @@ import DevelopmentTab from './tabs/DevelopmentTab'
|
||||
import FiscalTab from './tabs/FiscalTab'
|
||||
import { TabGroup } from '../../ui/Tabs'
|
||||
|
||||
const TABS = ['app-info', 'venue', 'security', 'operation', 'colours', 'print-fonts', 'fiscal', 'development']
|
||||
const TABS = ['app-info', 'venue', 'customer-display', 'security', 'operation', 'colours', 'print-fonts', 'fiscal', 'development']
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
const [activeTab, setActiveTab] = useState('app-info')
|
||||
const tabs = TABS.map(id => ({ id, label: t(`settings.tabs.${id}`) }))
|
||||
// the customer display's idle screen (3.4): only where there are displays and the user sets them up
|
||||
const displayOn = useModule('customer_display')
|
||||
const displayKey = useCan('customer_display.manage')
|
||||
const display = displayOn && displayKey
|
||||
const tabs = TABS.filter(id => id !== 'customer-display' || display).map(id => ({ id, label: t(`settings.tabs.${id}`) }))
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
@@ -23,6 +29,7 @@ export default function SettingsPage() {
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
{activeTab === 'app-info' && <AppInfoTab />}
|
||||
{activeTab === 'venue' && <div className="max-w-3xl"><VenueSettings /></div>}
|
||||
{activeTab === 'customer-display' && display && <div className="max-w-4xl"><CustomerDisplaySettings /></div>}
|
||||
{activeTab === 'security' && <SecurityTab />}
|
||||
{activeTab === 'operation' && <OperationTab />}
|
||||
{activeTab === 'colours' && <ColoursTab />}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// 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'
|
||||
import toast from 'react-hot-toast'
|
||||
import { Check, ImagePlus, Trash2 } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Field, IconButton, Input, Select, Spinner } from '@xenia/ui'
|
||||
import client from '../../../api/client'
|
||||
import { useSettings } from './useSettings'
|
||||
|
||||
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 [busy, setBusy] = useState(false)
|
||||
const [name, setName] = useState(null)
|
||||
const fileRef = useRef(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
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])
|
||||
|
||||
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 save = async () => {
|
||||
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)) }
|
||||
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])
|
||||
|
||||
return (
|
||||
<section className="bg-surface border border-line rounded-card shadow-raised grid gap-5 p-5" data-testid="settings-display">
|
||||
<header className="grid gap-1">
|
||||
<h2 className="text-body font-semibold text-ink">{t('display.title')}</h2>
|
||||
<p className="text-label text-ink-2">{t('display.intro')}</p>
|
||||
</header>
|
||||
|
||||
<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))' }}>
|
||||
{STYLES.map(s => (
|
||||
<button key={s} type="button" role="radio" aria-checked={form.style === s} onClick={() => set('style', s)} data-testid={`display-style-${s}`}
|
||||
className={`p-3 rounded-control border text-left grid gap-0.5 transition-colors duration-fast
|
||||
${form.style === s ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface-2 text-ink hover:bg-surface-3'}`}>
|
||||
<span className="text-body font-medium flex items-center gap-1.5">{form.style === s && <Check size={14} aria-hidden="true" />}{t(`display.styles.${s}.name`)}</span>
|
||||
<span className="text-caption text-ink-2">{t(`display.styles.${s}.hint`)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</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" />
|
||||
</Field>
|
||||
)}
|
||||
<Field label={t('display.theme')}>
|
||||
<Select value={form.theme} onChange={e => set('theme', e.target.value)} data-testid="display-theme">
|
||||
<option value="dark">{t('display.themes.dark')}</option>
|
||||
<option value="light">{t('display.themes.light')}</option>
|
||||
</Select>
|
||||
</Field>
|
||||
{shows('slides') && (
|
||||
<Field label={t('display.slideSeconds')}>
|
||||
<Input inputMode="numeric" value={String(form.slide_seconds)} data-testid="display-slide-seconds"
|
||||
onChange={e => set('slide_seconds', Number(e.target.value.replace(/\D/g, '')) || 0)} />
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{shows('qr') && (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label={t('display.qrTarget')}>
|
||||
<Select value={form.qr_target} onChange={e => set('qr_target', e.target.value)} data-testid="display-qr-target">
|
||||
{['ordering', 'menu', 'custom'].map(q => <option key={q} value={q}>{t(`display.qrTargets.${q}`)}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
{form.qr_target === 'custom' && (
|
||||
<Field label={t('display.qrUrl')}>
|
||||
<Input value={form.qr_url ?? ''} onChange={e => set('qr_url', e.target.value)} placeholder="https://" data-testid="display-qr-url" />
|
||||
</Field>
|
||||
)}
|
||||
<Field label={t('display.qrCaption')}>
|
||||
<Input value={form.qr_caption ?? ''} onChange={e => set('qr_caption', e.target.value)} maxLength={80} data-testid="display-qr-caption" />
|
||||
</Field>
|
||||
</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>
|
||||
</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>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div><Button onClick={save} loading={busy} data-testid="display-save">{t('fees.save')}</Button></div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
Generated
+10
-9
@@ -77,15 +77,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"manager_dashboard/node_modules/qrcode.react": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
|
||||
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@alloc/quick-lru": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.3.0.tgz",
|
||||
@@ -7242,6 +7233,15 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/qrcode.react": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
|
||||
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/queue-microtask": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||
@@ -9589,6 +9589,7 @@
|
||||
"@xenia/ui": "^0.0.0",
|
||||
"axios": "^1.21.1",
|
||||
"lucide-react": "^1.73.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-router-dom": "^7.18.5"
|
||||
|
||||
@@ -110,5 +110,11 @@
|
||||
"status_changed": "Η κράτηση άλλαξε από άλλη οθόνη στο μεταξύ (τώρα είναι {{current}}).",
|
||||
"table_unknown": "Το τραπέζι {{table_id}} δεν βρέθηκε.",
|
||||
"table_busy": "Αυτό το τραπέζι έχει ήδη ανοιχτή παραγγελία. Διαλέξτε άλλο τραπέζι ή κλείστε πρώτα εκείνη την παραγγελία."
|
||||
},
|
||||
"display": {
|
||||
"media_unknown": "Η εικόνα {{name}} δεν βρέθηκε.",
|
||||
"media_type": "Ανεβάστε εικόνα JPG, PNG, WebP ή GIF.",
|
||||
"media_too_big": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mb}} MB).",
|
||||
"qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,7 +308,8 @@
|
||||
"colours": "Εμφάνιση",
|
||||
"print-fonts": "Εκτύπωση",
|
||||
"fiscal": "Ταμειακή",
|
||||
"development": "Developer"
|
||||
"development": "Developer",
|
||||
"customer-display": "Οθόνη πελάτη"
|
||||
},
|
||||
"mode": {
|
||||
"password": "Κωδικός",
|
||||
@@ -599,5 +600,63 @@
|
||||
"copied": "Ο σύνδεσμος αντιγράφηκε",
|
||||
"open": "Άνοιγμα",
|
||||
"print": "Εκτύπωση"
|
||||
},
|
||||
"display": {
|
||||
"title": "Οθόνη πελάτη",
|
||||
"intro": "Η οθόνη προς τους πελάτες στο ταμείο δείχνει την πώληση και το σύνολο όσο χτυπάτε, και \"Ευχαριστούμε\" με τα ρέστα μετά την πληρωμή. Εδώ διαλέγετε τι δείχνει στο ενδιάμεσο.",
|
||||
"style": "Ανάμεσα στις πωλήσεις, δείξε",
|
||||
"styles": {
|
||||
"name": {
|
||||
"name": "Το όνομά σας",
|
||||
"hint": "Το όνομα του καταστήματος, μεγάλο"
|
||||
},
|
||||
"logo": {
|
||||
"name": "Το λογότυπο",
|
||||
"hint": "Μια εικόνα που ανεβάζετε"
|
||||
},
|
||||
"name_logo": {
|
||||
"name": "Λογότυπο και όνομα",
|
||||
"hint": "Το λογότυπο με το όνομα από κάτω"
|
||||
},
|
||||
"blank": {
|
||||
"name": "Τίποτα",
|
||||
"hint": "Απλή οθόνη"
|
||||
},
|
||||
"image": {
|
||||
"name": "Μια εικόνα",
|
||||
"hint": "Μία φωτογραφία, σε όλη την οθόνη"
|
||||
},
|
||||
"slideshow": {
|
||||
"name": "Παρουσίαση",
|
||||
"hint": "Φωτογραφίες η μία μετά την άλλη (προσφορές, πιάτα)"
|
||||
},
|
||||
"qr": {
|
||||
"name": "Κωδικός QR",
|
||||
"hint": "Ο σύνδεσμος παραγγελιών, το QR μενού ή άλλος σύνδεσμος"
|
||||
}
|
||||
},
|
||||
"venueName": "Όνομα καταστήματος",
|
||||
"venueNameHint": "Εμφανίζεται στην οθόνη (και σε άλλες οθόνες).",
|
||||
"message": "Μια γραμμή κειμένου (προαιρετικά)",
|
||||
"messageHint": "π.χ. \"Καλώς ήρθατε!\" ή \"Δωρεάν Wi-Fi: Taverna\"",
|
||||
"theme": "Εμφάνιση",
|
||||
"themes": {
|
||||
"dark": "Σκούρα",
|
||||
"light": "Φωτεινή"
|
||||
},
|
||||
"slideSeconds": "Δευτερόλεπτα ανά φωτογραφία",
|
||||
"qrTarget": "Ο κωδικός QR ανοίγει",
|
||||
"qrTargets": {
|
||||
"ordering": "Τις online παραγγελίες σας",
|
||||
"menu": "Το QR μενού σας",
|
||||
"custom": "Άλλο σύνδεσμο"
|
||||
},
|
||||
"qrUrl": "Σύνδεσμος",
|
||||
"qrCaption": "Κείμενο κάτω από τον κωδικό (προαιρετικά)",
|
||||
"pickLogo": "Διαλέξτε το λογότυπο",
|
||||
"pickImage": "Διαλέξτε την εικόνα",
|
||||
"pickSlides": "Διαλέξτε τις φωτογραφίες, με τη σειρά (ξανά πάτημα για αφαίρεση)",
|
||||
"upload": "Ανέβασμα εικόνων",
|
||||
"noImages": "Δεν υπάρχουν εικόνες: ανεβάστε (JPG, PNG, WebP ή GIF, έως 5 MB)."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,9 +81,12 @@
|
||||
},
|
||||
"customer_display": {
|
||||
"name": "Οθόνη πελάτη",
|
||||
"description": "Οθόνη προς τον πελάτη δίπλα σε ταμείο πάγκου (έρχεται σύντομα).",
|
||||
"description": "Οθόνη προς τον πελάτη στο ταμείο: η πώληση, το σύνολο, τα ρέστα, και μια οθόνη αναμονής που σχεδιάζετε εσείς.",
|
||||
"limits": {
|
||||
"devices": "Οθόνες πελάτη"
|
||||
},
|
||||
"permissions": {
|
||||
"manage": "Ρύθμιση της οθόνης πελάτη (οθόνη αναμονής, εικόνες)"
|
||||
}
|
||||
},
|
||||
"expenses": {
|
||||
|
||||
@@ -465,5 +465,12 @@
|
||||
"cancel": "Ακύρωση",
|
||||
"noShow": "Δεν ήρθαν"
|
||||
}
|
||||
},
|
||||
"display": {
|
||||
"total": "Σύνολο",
|
||||
"thanks": "Ευχαριστούμε!",
|
||||
"paid": "Πληρώθηκαν {{amount}}",
|
||||
"change": "Τα ρέστα σας: {{amount}}",
|
||||
"unlinked": "Δεν έχει συνδεθεί ακόμα με ταμείο (διαχείριση → Συσκευές)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,5 +110,11 @@
|
||||
"status_changed": "This booking was changed on another screen in the meantime (it is now {{current}}).",
|
||||
"table_unknown": "Table {{table_id}} not found.",
|
||||
"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."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,7 +308,8 @@
|
||||
"colours": "Appearance",
|
||||
"print-fonts": "Printing",
|
||||
"fiscal": "Fiscal device",
|
||||
"development": "Developer"
|
||||
"development": "Developer",
|
||||
"customer-display": "Customer display"
|
||||
},
|
||||
"mode": {
|
||||
"password": "Password",
|
||||
@@ -599,5 +600,63 @@
|
||||
"copied": "Link copied",
|
||||
"open": "Open",
|
||||
"print": "Print"
|
||||
},
|
||||
"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.",
|
||||
"style": "Between sales, show",
|
||||
"styles": {
|
||||
"name": {
|
||||
"name": "Your name",
|
||||
"hint": "The venue's name, large"
|
||||
},
|
||||
"logo": {
|
||||
"name": "Your logo",
|
||||
"hint": "An image you upload"
|
||||
},
|
||||
"name_logo": {
|
||||
"name": "Logo and name",
|
||||
"hint": "The logo with the name under it"
|
||||
},
|
||||
"blank": {
|
||||
"name": "Nothing",
|
||||
"hint": "A plain screen"
|
||||
},
|
||||
"image": {
|
||||
"name": "A picture",
|
||||
"hint": "One photo, full screen"
|
||||
},
|
||||
"slideshow": {
|
||||
"name": "A slideshow",
|
||||
"hint": "Photos one after another (promotions, dishes)"
|
||||
},
|
||||
"qr": {
|
||||
"name": "A QR code",
|
||||
"hint": "Your ordering link, QR menu, or any link"
|
||||
}
|
||||
},
|
||||
"venueName": "Venue name",
|
||||
"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",
|
||||
"themes": {
|
||||
"dark": "Dark",
|
||||
"light": "Light"
|
||||
},
|
||||
"slideSeconds": "Seconds per photo",
|
||||
"qrTarget": "The QR code opens",
|
||||
"qrTargets": {
|
||||
"ordering": "Your online ordering",
|
||||
"menu": "Your QR menu",
|
||||
"custom": "Another link"
|
||||
},
|
||||
"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)."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,9 +81,12 @@
|
||||
},
|
||||
"customer_display": {
|
||||
"name": "Customer display",
|
||||
"description": "A screen facing the customer at a counter POS (coming soon).",
|
||||
"description": "A screen facing the customer at a counter POS: the sale, the total, the change, and an idle screen you design.",
|
||||
"limits": {
|
||||
"devices": "Customer displays"
|
||||
},
|
||||
"permissions": {
|
||||
"manage": "Set up the customer display (idle screen, images)"
|
||||
}
|
||||
},
|
||||
"expenses": {
|
||||
|
||||
@@ -465,5 +465,12 @@
|
||||
"cancel": "Cancel",
|
||||
"noShow": "No-show"
|
||||
}
|
||||
},
|
||||
"display": {
|
||||
"total": "Total",
|
||||
"thanks": "Thank you!",
|
||||
"paid": "Paid {{amount}}",
|
||||
"change": "Your change: {{amount}}",
|
||||
"unlinked": "Not linked to a counter yet (manager → Devices)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"@xenia/ui": "^0.0.0",
|
||||
"axios": "^1.21.1",
|
||||
"lucide-react": "^1.73.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-router-dom": "^7.18.5"
|
||||
|
||||
@@ -1,6 +1,132 @@
|
||||
// Placeholder until step 3.4 builds this app (plan phase 3). Lazily loaded (apps/registry.js).
|
||||
import AppPlaceholder from '../AppPlaceholder'
|
||||
// The customer display (plan step 3.4): a screen facing the customer, paired with sign-in
|
||||
// "none" and linked to a counter POS in the manager's pair dialog. While the cashier sells it
|
||||
// shows the lines and the total; after payment "Thank you" with what was paid and the change;
|
||||
// in between, the idle screen the venue designed in Settings → Customer display (the name, the
|
||||
// logo, both, nothing, an image, a slideshow, or a QR code, with a line of text, light or dark).
|
||||
// The POS's state arrives live (`display.state`, addressed to this screen only); a settings
|
||||
// change re-reads it (`display.settings`). GET /api/display/state on start and reconnect.
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { QRCodeSVG } from 'qrcode.react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { applyTheme, getStoredTheme } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveEvent, useLiveEvents } from '../../device/context'
|
||||
import { idleParts, PAID_MS, slideAt, viewOf } from './logic'
|
||||
|
||||
const quiet = { xenia: { noOverride: true } }
|
||||
|
||||
export default function CustomerDisplayApp() {
|
||||
return <AppPlaceholder appKey="customer_display" />
|
||||
const [data, setData] = useState(null)
|
||||
const [state, setState] = useState(null)
|
||||
const [receivedAt, setReceivedAt] = useState(0)
|
||||
const [now, setNow] = useState(() => Date.now())
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const { data: d } = await client.get('/api/display/state', quiet)
|
||||
setData(d)
|
||||
setState(s => s ?? d.state)
|
||||
setReceivedAt(r => r || Date.now())
|
||||
} catch { /* the shell shows offline */ }
|
||||
}, [])
|
||||
useEffect(() => { load() }, [load])
|
||||
useLiveEvent('ready', load)
|
||||
useLiveEvents(['display.settings', 'device.updated'], load)
|
||||
useLiveEvent('display.state', next => { setState(next); setReceivedAt(Date.now()) })
|
||||
|
||||
// the clock moves the paid screen to idle and the slides along
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setNow(Date.now()), 1000)
|
||||
return () => clearInterval(id)
|
||||
}, [])
|
||||
|
||||
const theme = data?.idle?.theme ?? 'dark'
|
||||
useEffect(() => {
|
||||
applyTheme(theme)
|
||||
return () => { applyTheme(getStoredTheme()) }
|
||||
}, [theme])
|
||||
|
||||
if (!data) return <main className="absolute inset-0 bg-canvas" data-testid="app-customer_display" />
|
||||
const view = viewOf(state, receivedAt, now)
|
||||
return (
|
||||
<main className="absolute inset-0 bg-canvas text-ink overflow-hidden select-none" data-testid="app-customer_display" data-view={view}>
|
||||
{view === 'cart' && <CartView state={state} venue={data.venue_name} />}
|
||||
{view === 'paid' && <PaidView state={state} />}
|
||||
{view === 'idle' && <IdleView idle={data.idle} venue={data.venue_name} now={now} linked={data.linked} />}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
function CartView({ state, venue }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney, formatNumber } = useFormat()
|
||||
const end = useRef(null)
|
||||
useEffect(() => { end.current?.scrollIntoView({ block: 'end' }) }, [state.lines.length])
|
||||
return (
|
||||
<div className="h-full flex flex-col" data-testid="display-cart">
|
||||
{venue && <header className="px-8 py-4 text-title text-ink-2 border-b border-line">{venue}</header>}
|
||||
<ul className="flex-1 overflow-hidden px-8 py-4 grid content-start gap-3">
|
||||
{state.lines.map((l, i) => (
|
||||
<li key={i} className="flex items-baseline gap-4 text-3xl" data-testid="display-line">
|
||||
<span className="w-20 shrink-0 text-ink-2 tabular-nums">{formatNumber(l.quantity)}×</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="font-medium">{l.name}</span>
|
||||
{l.options?.length > 0 && <span className="block text-xl text-ink-2">{l.options.join(' · ')}</span>}
|
||||
</span>
|
||||
<span className="tabular-nums">{formatMoney(l.total)}</span>
|
||||
</li>
|
||||
))}
|
||||
<li ref={end} />
|
||||
</ul>
|
||||
<footer className="px-8 py-6 bg-surface border-t border-line flex items-baseline justify-between">
|
||||
<span className="text-3xl text-ink-2">{t('display.total')}</span>
|
||||
<span className="text-7xl font-semibold tabular-nums" data-testid="display-total">{formatMoney(state.total)}</span>
|
||||
</footer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PaidView({ state }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
return (
|
||||
<div className="h-full flex flex-col items-center justify-center gap-6 text-center p-8" data-testid="display-paid">
|
||||
<p className="text-7xl font-semibold text-success-ink">{t('display.thanks')}</p>
|
||||
<p className="text-3xl text-ink-2">{t('display.paid', { amount: formatMoney(state.paid ?? state.total) })}</p>
|
||||
{state.change > 0 && <p className="text-5xl font-semibold tabular-nums" data-testid="display-change">{t('display.change', { amount: formatMoney(state.change) })}</p>}
|
||||
<span className="sr-only">{PAID_MS}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function IdleView({ idle, venue, now, linked }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const p = idleParts(idle, venue)
|
||||
const slide = slideAt(p.slides.length, idle?.slide_seconds, now)
|
||||
const full = p.image || p.slides.length > 0
|
||||
return (
|
||||
<div className="h-full relative flex flex-col items-center justify-center gap-6 p-8 text-center" data-testid="display-idle" data-style={idle?.style}>
|
||||
{p.image && <img src={p.image} alt="" className="absolute inset-0 w-full h-full object-cover" data-testid="display-image" />}
|
||||
{p.slides.map((src, i) => (
|
||||
<img key={src} src={src} alt="" data-testid="display-slide" data-current={i === slide ? 'true' : 'false'}
|
||||
className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-1000 ${i === slide ? 'opacity-100' : 'opacity-0'}`} />
|
||||
))}
|
||||
{!p.blank && !full && (
|
||||
<>
|
||||
{p.logo && <img src={p.logo} alt={venue || ''} className="max-h-[45vh] max-w-[70vw] object-contain" data-testid="display-logo" />}
|
||||
{p.name && <h1 className="text-7xl font-semibold" data-testid="display-name">{p.name}</h1>}
|
||||
{p.qr && (
|
||||
<div className="grid justify-items-center gap-4" data-testid="display-qr" data-link={p.qr}>
|
||||
<div className="p-5 rounded-card bg-surface shadow-raised"><QRCodeSVG value={p.qr} size={320} includeMargin={false} /></div>
|
||||
{p.caption && <p className="text-4xl font-semibold">{p.caption}</p>}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{p.message && (
|
||||
<p className={`text-3xl ${full ? 'absolute bottom-8 inset-x-8 py-3 rounded-card bg-surface/80 text-ink' : 'text-ink-2'}`} data-testid="display-message">{p.message}</p>
|
||||
)}
|
||||
{!linked && <p className="absolute bottom-3 right-4 text-label text-ink-3" data-testid="display-unlinked">{t('display.unlinked')}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// The customer display's logic (plan step 3.4). Pure: unit-tested in Node (tests/display.test.mjs).
|
||||
|
||||
export const PAID_MS = 12_000 // "Thank you" stays this long, then the idle screen
|
||||
export const STYLES = ['name', 'logo', 'name_logo', 'blank', 'image', 'slideshow', 'qr']
|
||||
|
||||
/** What to show: 'idle' | 'cart' | 'paid'. A paid screen goes idle after PAID_MS; an empty cart is idle. */
|
||||
export function viewOf(state, receivedAt, now = Date.now()) {
|
||||
if (!state || state.mode === 'idle') return 'idle'
|
||||
if (state.mode === 'paid') return now - receivedAt < PAID_MS ? 'paid' : 'idle'
|
||||
return state.lines?.length ? 'cart' : 'idle'
|
||||
}
|
||||
|
||||
/** The parts of the idle screen to draw, from the venue's settings (GET /api/display/state → idle). */
|
||||
export function idleParts(idle, venueName) {
|
||||
const s = STYLES.includes(idle?.style) ? idle.style : 'name'
|
||||
const logo = idle?.logo_url || null
|
||||
return {
|
||||
name: (s === 'name' || s === 'name_logo' || (s === 'logo' && !logo)) ? (venueName || null) : null,
|
||||
logo: (s === 'logo' || s === 'name_logo') ? logo : null,
|
||||
image: s === 'image' ? idle?.image_url || null : null,
|
||||
slides: s === 'slideshow' ? idle?.slide_urls ?? [] : [],
|
||||
qr: s === 'qr' ? idle?.qr_link || null : null,
|
||||
caption: s === 'qr' ? idle?.qr_caption || null : null,
|
||||
message: s === 'blank' ? null : idle?.message || null,
|
||||
blank: s === 'blank',
|
||||
}
|
||||
}
|
||||
|
||||
/** The slide to show at `now` (every `seconds`). */
|
||||
export function slideAt(count, seconds, now = Date.now()) {
|
||||
if (!count) return -1
|
||||
return Math.floor(now / (Math.max(3, seconds || 8) * 1000)) % count
|
||||
}
|
||||
@@ -3,12 +3,13 @@
|
||||
// by row. The caller's `submit({ method, rowMethods, cashGiven })` makes the one call: a quick
|
||||
// sale (POST /api/pos/sales, rows = cart lines) or a table's items (POST /api/pos/orders/{id}/pay,
|
||||
// rows = order items). Cash with the exact amount is pre-selected: Charge → Take = two taps.
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Banknote, Check, CreditCard, Split } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Input } from '@xenia/ui'
|
||||
import { changeFor, quickAmounts, splitPayments } from './logic/cart'
|
||||
import { useDisplay } from './usePos'
|
||||
|
||||
const tab = on => `flex-1 min-h-[var(--x-control-lg)] rounded-control flex items-center justify-center gap-2 text-body-lg font-medium transition-colors duration-fast
|
||||
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
|
||||
@@ -29,6 +30,13 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const short = cashDue > 0 && change == null
|
||||
// the customer display (3.4): the bill while paying, then "Thank you" with the change
|
||||
const display = useDisplay()
|
||||
const paidRef = useRef(false)
|
||||
useEffect(() => {
|
||||
display({ mode: 'cart', lines: rows.map(r => ({ name: r.label, total: r.total })), total })
|
||||
return () => { if (!paidRef.current) display({ mode: 'idle' }) }
|
||||
}, []) // eslint-disable-line react-hooks/exhaustive-deps -- once, when the dialog opens
|
||||
|
||||
const pay = async () => {
|
||||
if (busy || short) return
|
||||
@@ -36,7 +44,10 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
|
||||
setError('')
|
||||
const payments = method === 'split' ? parts.payments : [{ method, lines: rows.map((_, i) => i) }]
|
||||
try {
|
||||
onPaid(await submit({ method, rowMethods: split, payments, cashGiven: cashDue > 0 ? (given ?? cashDue) : null }))
|
||||
const result = await submit({ method, rowMethods: split, payments, cashGiven: cashDue > 0 ? (given ?? cashDue) : null })
|
||||
paidRef.current = true
|
||||
display({ mode: 'paid', total, paid: result?.cash_given ?? total, change: result?.change ?? 0 })
|
||||
onPaid(result)
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, t))
|
||||
} finally {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// The quick-sale cart (plan steps 3.3a–b): order type, the lines priced by the backend,
|
||||
// Charge → PaymentDialog (POST /api/pos/sales); after a sale it shows what happened and
|
||||
// "Same again".
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Banknote, Repeat, ShoppingBag, Trash2, Utensils } from 'lucide-react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, EmptyState, useToast } from '@xenia/ui'
|
||||
@@ -9,7 +9,7 @@ import client from '../../api/client'
|
||||
import CartLine from './CartLine'
|
||||
import { setLineQty } from './logic/cart'
|
||||
import PaymentDialog from './PaymentDialog'
|
||||
import { useQuote } from './usePos'
|
||||
import { useDisplay, useQuote } from './usePos'
|
||||
|
||||
export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
@@ -20,6 +20,22 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId,
|
||||
const quote = useQuote(cart, orderType)
|
||||
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
|
||||
|
||||
// the customer display (3.4) follows the cart; after a sale it shows "Thank you" (sent by
|
||||
// the payment) until it times out, so an empty cart then says nothing
|
||||
const display = useDisplay()
|
||||
const thanking = useRef(false) // the display shows "Thank you" for the last sale
|
||||
useEffect(() => {
|
||||
if (paying) return
|
||||
if (!cart.length) { if (!thanking.current) display({ mode: 'idle' }); return }
|
||||
if (!ready) return
|
||||
thanking.current = false
|
||||
display({
|
||||
mode: 'cart', total: quote.quote.total,
|
||||
lines: cart.map((l, i) => ({ name: byId.get(l.product_id)?.name ?? '', quantity: l.quantity, total: quote.quote.lines[i].total })),
|
||||
})
|
||||
}, [cart, ready, quote.quote, paying, byId, display])
|
||||
useEffect(() => () => display({ mode: 'idle' }), [display])
|
||||
|
||||
const submit = async ({ method, payments, cashGiven }) => (await client.post('/api/pos/sales', {
|
||||
order_type: orderType, lines: cart, payments: method === 'split' ? payments : [{ method }], cash_given: cashGiven,
|
||||
})).data
|
||||
@@ -65,6 +81,7 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId,
|
||||
onClose={() => setPaying(false)}
|
||||
onPaid={result => {
|
||||
setPaying(false)
|
||||
thanking.current = true
|
||||
setLastSale({ lines: cart, orderType, result })
|
||||
setCart([])
|
||||
toast.success(result.change > 0 ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// the menu, the cart priced by the backend, the tables, a table's order, online orders and receipts. Kept fresh by the
|
||||
// live connection, so a waiter's phone and the counter see each other's changes at once.
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useModule } from '@xenia/access'
|
||||
import client from '../../api/client'
|
||||
import { useLiveEvent, useLiveEvents } from '../../device/context'
|
||||
|
||||
@@ -130,6 +131,21 @@ export function useOnline(enabled) {
|
||||
return { data, reload: load }
|
||||
}
|
||||
|
||||
// The customer display (plan step 3.4): what this counter's customer should see. One timer for
|
||||
// the whole screen, so the last thing said wins; "paid" goes at once, the rest after a moment
|
||||
// (a burst of cart changes is one message). Nothing is sent while the module is off.
|
||||
let displayTimer = null
|
||||
|
||||
/** push({ mode: 'idle' | 'cart' | 'paid', lines?, total?, paid?, change? }) → POST /api/display/state. */
|
||||
export function useDisplay() {
|
||||
const on = useModule('customer_display')
|
||||
return useCallback(state => {
|
||||
if (!on) return
|
||||
clearTimeout(displayTimer)
|
||||
displayTimer = setTimeout(() => { client.post('/api/display/state', state, quiet).catch(() => {}) }, state.mode === 'paid' ? 0 : 200)
|
||||
}, [on])
|
||||
}
|
||||
|
||||
const BOOKING_EVENTS = ['reservation_requested', 'reservation_updated']
|
||||
|
||||
/** GET /api/connect/bookings: { requested, upcoming } (null while loading); live (S.6). */
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// The customer display's logic (plan step 3.4).
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { idleParts, PAID_MS, slideAt, viewOf } from '../src/apps/customer-display/logic.js'
|
||||
|
||||
test('what the display shows: the cart, thank you (for a while), idle', () => {
|
||||
const t0 = 1_000_000
|
||||
assert.equal(viewOf(null, 0, t0), 'idle')
|
||||
assert.equal(viewOf({ mode: 'cart', lines: [{}] }, t0, t0), 'cart')
|
||||
assert.equal(viewOf({ mode: 'cart', lines: [] }, t0, t0), 'idle')
|
||||
assert.equal(viewOf({ mode: 'paid' }, t0, t0 + 1000), 'paid')
|
||||
assert.equal(viewOf({ mode: 'paid' }, t0, t0 + PAID_MS + 1), 'idle')
|
||||
})
|
||||
|
||||
test('the idle screen the venue chose', () => {
|
||||
const idle = { logo_url: '/l.png', image_url: '/i.png', slide_urls: ['/a.png', '/b.png'], qr_link: 'https://x/order/s', qr_caption: 'Order online', message: 'Hi' }
|
||||
assert.deepEqual(idleParts({ ...idle, style: 'name' }, 'Taverna'), { name: 'Taverna', logo: null, image: null, slides: [], qr: null, caption: null, message: 'Hi', blank: false })
|
||||
assert.equal(idleParts({ ...idle, style: 'logo' }, 'Taverna').name, null)
|
||||
assert.equal(idleParts({ ...idle, style: 'logo', logo_url: null }, 'Taverna').name, 'Taverna', 'no logo yet: the name instead')
|
||||
const both = idleParts({ ...idle, style: 'name_logo' }, 'Taverna')
|
||||
assert.equal(both.name, 'Taverna'); assert.equal(both.logo, '/l.png')
|
||||
assert.equal(idleParts({ ...idle, style: 'image' }, 'T').image, '/i.png')
|
||||
assert.deepEqual(idleParts({ ...idle, style: 'slideshow' }, 'T').slides, ['/a.png', '/b.png'])
|
||||
const qr = idleParts({ ...idle, style: 'qr' }, 'T')
|
||||
assert.equal(qr.qr, 'https://x/order/s'); assert.equal(qr.caption, 'Order online')
|
||||
const blank = idleParts({ ...idle, style: 'blank' }, 'T')
|
||||
assert.equal(blank.blank, true); assert.equal(blank.message, null); assert.equal(blank.name, null)
|
||||
assert.equal(idleParts({ style: 'nonsense' }, 'T').name, 'T')
|
||||
})
|
||||
|
||||
test('the slideshow moves on every N seconds', () => {
|
||||
assert.equal(slideAt(0, 8, 0), -1)
|
||||
assert.equal(slideAt(3, 8, 0), 0)
|
||||
assert.equal(slideAt(3, 8, 8000), 1)
|
||||
assert.equal(slideAt(3, 8, 24_000), 0)
|
||||
assert.equal(slideAt(2, 1, 3000), 1, 'at least 3 seconds a slide')
|
||||
})
|
||||
@@ -590,6 +590,22 @@ try {
|
||||
r.check('fees: …and it never shows in the products list', !(await api('GET', '/api/products/?all=true', { token: boss })).some(p => p.id === feeProduct?.id))
|
||||
await page.screenshot({ path: path.join(OUT, 'manager-fees.png'), fullPage: true })
|
||||
|
||||
// 3.4: the customer display's idle screen, the venue's choice
|
||||
await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {})
|
||||
await page.goto(`${APP}/settings`)
|
||||
await page.getByText('Customer display', { exact: true }).click()
|
||||
await page.getByTestId('display-style-qr').click()
|
||||
await page.getByTestId('display-qr-caption').fill('Order online')
|
||||
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
|
||||
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'
|
||||
&& 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 })
|
||||
|
||||
await page.goto(`${APP}/settings`)
|
||||
await page.getByText('Sign-in & security', { exact: true }).click()
|
||||
const waiterMode = page.getByTestId('setting-auth.waiter_login_mode')
|
||||
|
||||
@@ -684,6 +684,56 @@ try {
|
||||
{ order: saleOrder, name: simple.name }, { timeout: 8000 }).then(() => true).catch(() => false))
|
||||
await api('PUT', '/api/settings/fiscal.enabled', { token: boss, body: { value: 'false' } })
|
||||
await page.getByTestId('mode-sale').click()
|
||||
|
||||
// ── 3.4: the customer display ────────────────────────────────────────────
|
||||
// two displays: one linked to this counter, one not (another counter's); the venue's idle screen
|
||||
await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {})
|
||||
await api('PUT', '/api/settings/venue.name', { token: boss, body: { value: 'Taverna E2E' } })
|
||||
// its own address for the pairing rate limit (one per screen in a real venue)
|
||||
const myDisplay = await screen(await (await browser.newContext({ viewport: { width: 1024, height: 600 }, extraHTTPHeaders: { 'x-real-ip': '10.9.0.41' } })).newPage())
|
||||
await pairFromManager(myDisplay, boss, { app_key: 'customer_display', name: 'Display at the counter', linked_device_id: kitchen.id })
|
||||
// its own address for the pairing rate limit (one per screen in a real venue)
|
||||
const otherDisplay = await screen(await (await browser.newContext({ viewport: { width: 1024, height: 600 }, extraHTTPHeaders: { 'x-real-ip': '10.9.0.42' } })).newPage())
|
||||
await pairFromManager(otherDisplay, boss, { app_key: 'customer_display', name: 'Display elsewhere' })
|
||||
r.check('3.4: a display linked to the counter shows the idle screen: the venue name (the default)',
|
||||
await shown(myDisplay, 'display-idle', 15_000) && (await myDisplay.getByTestId('display-name').textContent()) === 'Taverna E2E')
|
||||
await simpleCard.locator('button').first().click()
|
||||
await simpleCard.locator('button').first().click()
|
||||
const started = Date.now()
|
||||
const seen = await myDisplay.waitForFunction(() => document.querySelector('[data-testid="app-customer_display"]')?.dataset.view === 'cart', null, { timeout: 5000 })
|
||||
.then(() => Date.now() - started).catch(() => null)
|
||||
const shownTotal = await myDisplay.getByTestId('display-total').textContent().catch(() => '')
|
||||
r.check('3.4: a sale shows on its own display within a second (the lines and the total)', seen != null && seen < 1500
|
||||
&& shownTotal.includes((2 * simple.price).toFixed(2)) && await myDisplay.getByTestId('display-line').count() === 1, `${seen} ms, ${shownTotal}`)
|
||||
r.check('3.4: …and not on another counter\'s display', await otherDisplay.getByTestId('app-customer_display').getAttribute('data-view') === 'idle')
|
||||
await myDisplay.screenshot({ path: path.join(OUT, 'terminal-display-cart.png') })
|
||||
await page.getByTestId('charge').click()
|
||||
await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 })
|
||||
await page.getByTestId('cash-given').fill('50').catch(() => {})
|
||||
await page.getByTestId('pay-confirm').click()
|
||||
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)',
|
||||
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 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 })
|
||||
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',
|
||||
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')
|
||||
await myDisplay.context().close()
|
||||
await otherDisplay.context().close()
|
||||
drawerServer.close()
|
||||
await page.getByRole('button', { name: 'Sign out' }).click()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user