Compare commits

...
2 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 cc81e0a31f feat(terminal): the menu tablet app (platform-v2 step 5.7a)
terminal/src/apps/menu-tablet: the venue's menu for staff (a quick price
check) and guests. Category chips that jump to their section, or one A–Z
list; compact rows, expanded rows (photo, description) or full cards; tap a
product to see it big (photo, price, description, tags); search that ignores
accents and also finds names typed in Latin letters ("souvl"); sold out
marked; the guest's language for the tablet's texts; back to the start (search
cleared, first language, top) after the set time without a touch; light or
dark; the last menu kept for offline; live on menu_tablet.changed /
device.updated. @xenia/i18n exports ./latin for plain-JS use.
tests: logic (3), e2e menu_tablet.mjs (10 checks, in run-all).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:44:42 +02:00
bonaminandClaude Opus 5.5 2a6640fe5c feat(backend): the menu tablet's menu (platform-v2 step 5.7a)
GET /api/menu-tablet/menu for a paired menu tablet: categories in the
catalogue's order (sub-categories after their parent, one category and its
sub-categories when the tablet is set so), each with its products in its own
order (a product in several categories shows in each), the products once with
name, description, tags, photo, the price of the tablet's sales point (or none)
and availability; sold-out hidden when set; the venue's name and the tablet's
settings. Device config: view, photos, descriptions, group, theme, prices of,
sold out, category, search, languages, idle reset (texts in both languages).
Menu changes send menu_tablet.changed to every tablet (main.py, with signage).
tests: test_menu_tablet.py (4); 531 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:44:42 +02:00
17 changed files with 827 additions and 12 deletions
+1
View File
@@ -49,6 +49,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `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/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/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/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out | | `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out |
| `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage |
| `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/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) | | `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/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
+3 -1
View File
@@ -112,12 +112,14 @@ async def _menu_change_push(request, call_next):
def _signage_menu_changed() -> None: def _signage_menu_changed() -> None:
"""The signage screens showing a menu board read it again (plan step 5.4b).""" """The signage screens showing a menu board (5.4b) and the menu tablets (5.7a) read their menu again."""
try: try:
from routers.menu_tablet import menu_changed as tablet_menu_changed
from routers.signage import menu_changed as signage_menu_changed from routers.signage import menu_changed as signage_menu_changed
db = SessionLocal() db = SessionLocal()
try: try:
signage_menu_changed(db) signage_menu_changed(db)
tablet_menu_changed(db) # the menu tablets read their menu again (5.7a)
finally: finally:
db.close() db.close()
except Exception as e: # never breaks the request that changed the menu except Exception as e: # never breaks the request that changed the menu
+21 -3
View File
@@ -1,11 +1,13 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4.""" """Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import DeviceApp, Limit, Module, Perm from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
POINTS = ('in_store', 'in_store_takeaway', 'qr_table', 'online_takeaway', 'online_delivery', 'online_preorder', 'none')
MODULE = Module( MODULE = Module(
key='menu_tablet', key='menu_tablet',
kind='app', kind='app',
name='Menu tablet', name='Menu tablet',
description='Self-service catalogue on a tablet (phase 5).', description="The venue's menu on a tablet: a quick price check for staff and a menu for guests (plan step 5.7a).",
depends=('catalog',), depends=('catalog',),
permissions=( permissions=(
Perm('menu_tablet.manage', 'Set up menu tablets', roles=('owner', 'store_manager')), Perm('menu_tablet.manage', 'Set up menu tablets', roles=('owner', 'store_manager')),
@@ -13,5 +15,21 @@ MODULE = Module(
limits=( limits=(
Limit('devices', 'Number of menu tablets', free=0, licensed_default=1), Limit('devices', 'Number of menu tablets', free=0, licensed_default=1),
), ),
device_app=DeviceApp(login_modes=('none',), scope=()), routers=(
Mount('routers.menu_tablet', '/api/menu-tablet'),
),
# How the menu looks on this tablet (owner 2026-11-17: views, photos, descriptions, grouping…)
device_app=DeviceApp(login_modes=('none',), scope=(), config=(
ConfigField('view', 'enum', default='expanded', choices=('compact', 'expanded', 'full'), group='look'),
ConfigField('photos', 'bool', default=True, group='look'),
ConfigField('descriptions', 'bool', default=True, group='look'),
ConfigField('group', 'bool', default=True, group='look'),
ConfigField('theme', 'enum', default='light', choices=('light', 'dark'), group='look'),
ConfigField('sales_point', 'enum', default='in_store', choices=POINTS, group='menu'),
ConfigField('sold_out', 'enum', default='strike', choices=('strike', 'hide'), group='menu'),
ConfigField('category', 'ref', default=None, choices_from='categories', group='menu'),
ConfigField('search', 'bool', default=True, group='use'),
ConfigField('languages', 'enum', default='both', choices=('both', 'el', 'en'), group='use'),
ConfigField('idle_seconds', 'int', default=120, choices=(0, 30, 60, 120, 300, 600), group='use'),
)),
) )
+117
View File
@@ -0,0 +1,117 @@
"""The menu tablet (plan step 5.7a): the venue's menu on a tablet, for staff ("how much is the
steak?") and for guests (a menu at the entrance, later a digital menu at the table). Just the
products and their categories: no ordering, no tables, no sign-in.
GET /api/menu-tablet/menu (a paired menu tablet) the categories in the catalogue's order
(sub-categories after their parent), each with its products in its
own order (a product listed in several categories shows in each),
the products once with name, description, tags, photo, the price
of the tablet's sales point and whether it is available; the
tablet's settings (device config) and the venue's name.
How it looks is the tablet's device config (modules/menu_tablet/manifest.py): view, photos,
descriptions, grouping, whose prices, sold-out style, search, one category or all, languages,
idle reset, light / dark. Any menu change sends `menu_tablet.changed` to every tablet (main.py).
"""
from __future__ import annotations
import json
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from core import sales_points
from core.access.deps import require_device
from database import get_db
router = APIRouter()
def _config(dev) -> dict:
from core.modules.device_config import effective, for_app
return effective(for_app("menu_tablet"), dev.config)
def tablets(db) -> list[int]:
from models.device import Device
return [i for (i,) in db.query(Device.id).filter(Device.app_key == "menu_tablet", Device.revoked_at.is_(None))]
def menu_changed(db) -> None:
"""Products, categories or prices changed (main.py): every tablet reads its menu again."""
from services.ws_bus import broadcast_sync
ids = tablets(db)
if ids:
broadcast_sync("menu_tablet.changed", {}, device_ids=ids)
def _tags(p) -> list[str]:
raw = getattr(p, "tags", None)
if isinstance(raw, str):
try:
raw = json.loads(raw)
except ValueError:
raw = []
return [t for t in (raw or []) if isinstance(t, str)]
@router.get("/menu")
def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
from models.product import Category, Product, ProductCategory
from models.settings import PosSettings
from services import media as media_store
from services.pos_cart import unit_prices
cfg = _config(dev)
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
by_parent: dict = {}
for c in cats:
by_parent.setdefault(c.parent_id, []).append(c)
ordered = [] # parents, each followed by its sub-categories
def walk(parent_id, depth):
for c in by_parent.get(parent_id, []):
ordered.append((c, depth))
walk(c.id, depth + 1)
walk(None, 0)
if cfg.get("category"):
root = next(((c, d) for c, d in ordered if c.id == cfg["category"]), None)
keep = set()
if root:
stack = [root[0].id]
while stack:
cid = stack.pop()
keep.add(cid)
stack.extend(x.id for x in by_parent.get(cid, []))
ordered = [(c, d) for c, d in ordered if c.id in keep]
point = None if cfg["sales_point"] == "none" else cfg["sales_point"]
products = db.query(Product).filter(Product.lifecycle_status == "active", Product.system_key.is_(None)).all()
if point:
products = [p for p in products if sales_points.is_sold_at(p, point)]
if cfg["sold_out"] == "hide":
products = [p for p in products if p.is_available]
by_id = {p.id: p for p in products}
members = db.query(ProductCategory).order_by(ProductCategory.sort_order).all()
in_cat: dict = {}
for m in members:
if m.product_id in by_id:
in_cat.setdefault(m.category_id, []).append(m.product_id)
out_cats, used = [], set()
for c, depth in ordered:
ids = in_cat.get(c.id, [])
has_sub = any(in_cat.get(x.id) for x in by_parent.get(c.id, []))
if ids or has_sub:
out_cats.append({"id": c.id, "name": c.name, "parent_id": c.parent_id, "depth": depth, "products": ids})
used.update(ids)
shown = [by_id[i] for i in by_id if i in used]
prices = dict(zip([p.id for p in shown], unit_prices(db, shown, point))) if point and shown else {}
name_row = db.query(PosSettings).filter(PosSettings.key == "venue.name").first()
return {
"venue": {"name": (name_row.value if name_row else "") or None},
"config": cfg,
"categories": out_cats,
"products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p),
"price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available),
"image": media_store.image_of(p.media)} for p in shown},
}
+88
View File
@@ -0,0 +1,88 @@
"""The menu tablet (plan step 5.7a): the menu for a paired tablet, categories in the catalogue's
order with their products (a product in several categories shows in each), a sales point's live
prices, sold out crossed out or hidden, one category or all; menu changes reach the tablets."""
import pytest
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
@pytest.fixture
def menu(db):
from models.product import Category, Product, ProductCategory
grill, drinks = Category(name="Grill", sort_order=0), Category(name="Drinks", sort_order=1)
db.add_all([grill, drinks])
db.flush()
pita = Category(name="Pita", sort_order=0, parent_id=grill.id)
db.add(pita)
db.flush()
def prod(name, cats, price, **kw):
p = Product(name=name, base_price=price, primary_category_id=cats[0].id, **kw)
db.add(p)
db.flush()
for i, c in enumerate(cats):
db.add(ProductCategory(product_id=p.id, category_id=c.id, sort_order=kw.get("sort_order", 0)))
return p
out = {"steak": prod("Steak", [grill], 12.0, description="Pork, 300 g", tags='["gluten-free"]', sort_order=1),
"souvlaki": prod("Souvlaki", [grill, pita], 3.5, sort_order=0),
"beer": prod("Beer", [drinks], 4.5),
"wine": prod("Wine", [drinks], 5.0, sold_at='["online_delivery"]'),
"old": prod("Old", [grill], 1.0, lifecycle_status="archived")}
db.commit()
out["cats"] = {"grill": grill.id, "drinks": drinks.id, "pita": pita.id}
return out
@pytest.fixture
def tablet(pair):
token, r = pair("menu_tablet", "Entrance")
assert r.status_code == 201, r.text
return {"h": {"X-Xenia-Device": token}, "id": r.json()["id"]}
def names(data):
return [(c["name"], [data["products"][str(i)]["name"] for i in c["products"]]) for c in data["categories"]]
def test_the_menu_on_a_tablet(client, owner_h, tablet, menu):
photo = up(client, owner_h, jpeg(800, 600)).json()
client.put(f"/api/products/{menu['steak'].id}", headers=owner_h, json={"media_id": photo["id"]})
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert names(data) == [("Grill", ["Souvlaki", "Steak"]), ("Pita", ["Souvlaki"]), ("Drinks", ["Beer"])] # Wine: delivery only
assert [c["depth"] for c in data["categories"]] == [0, 1, 0]
steak = data["products"][str(menu["steak"].id)]
assert (steak["price"], steak["description"], steak["tags"], steak["image"]["card"]) == (12.0, "Pork, 300 g", ["gluten-free"], photo["urls"]["card"])
assert data["config"]["view"] == "expanded" and data["config"]["search"] is True
def test_the_tablets_settings_change_the_menu(client, owner_h, tablet, menu, db):
menu["beer"].is_available = False
db.commit()
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert data["products"][str(menu["beer"].id)]["available"] is False
cfg = {"sold_out": "hide", "category": menu["cats"]["grill"], "sales_point": "none", "view": "full"}
assert client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": cfg}).status_code == 200
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert names(data) == [("Grill", ["Souvlaki", "Steak"]), ("Pita", ["Souvlaki"])]
assert {p["price"] for p in data["products"].values()} == {None} and data["config"]["view"] == "full"
client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"sales_point": "online_delivery"}})
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert names(data)[0][0] == "Grill" and None not in {p["price"] for p in data["products"].values()} # prices again, still only Grill
assert err(client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"view": "huge"}})) == "validation.device_config"
def test_menu_changes_reach_the_tablets(client, owner_h, tablet, menu, db, monkeypatch):
import routers.menu_tablet as mt
sent = []
monkeypatch.setattr("services.ws_bus.broadcast_sync", lambda kind, data, **kw: sent.append((kind, kw.get("device_ids"))))
mt.menu_changed(db)
assert sent == [("menu_tablet.changed", [tablet["id"]])]
client.put(f"/api/products/{menu['steak'].id}", headers=owner_h, json={"base_price": 13.5})
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["products"][str(menu["steak"].id)]["price"] == 13.5
def test_only_menu_tablets(client, pair):
token, _ = pair("kds", "Kitchen")
assert err(client.get("/api/menu-tablet/menu", headers={"X-Xenia-Device": token})) == "device.out_of_scope"
assert err(client.get("/api/menu-tablet/menu")) == "device.not_paired"
+84 -1
View File
@@ -272,12 +272,95 @@
}, },
"menu_tablet": { "menu_tablet": {
"name": "Tablet μενού", "name": "Tablet μενού",
"description": "Κατάλογος αυτοεξυπηρέτησης σε tablet (έρχεται σύντομα).", "description": "Το μενού του καταστήματος σε tablet: γρήγορος έλεγχος τιμών για το προσωπικό και μενού για τους πελάτες.",
"limits": { "limits": {
"devices": "Tablet μενού" "devices": "Tablet μενού"
}, },
"permissions": { "permissions": {
"manage": "Ρύθμιση των tablet μενού" "manage": "Ρύθμιση των tablet μενού"
},
"config_groups": {
"look": "Εμφάνιση",
"menu": "Μενού",
"use": "Χρήση"
},
"config": {
"view": {
"label": "Προβολή",
"hint": "Συμπαγής: πυκνή λίστα. Αναλυτική: με μικρή φωτογραφία και περιγραφή. Πλήρης: μεγάλες κάρτες.",
"choices": {
"compact": "Συμπαγής",
"expanded": "Αναλυτική",
"full": "Πλήρης"
}
},
"photos": {
"label": "Φωτογραφίες"
},
"descriptions": {
"label": "Περιγραφές"
},
"group": {
"label": "Ομαδοποίηση ανά κατηγορία",
"hint": "Όχι: μία λίστα με όλα τα προϊόντα (αλφαβητικά)."
},
"theme": {
"label": "Χρώματα",
"choices": {
"light": "Ανοιχτά",
"dark": "Σκούρα"
}
},
"sales_point": {
"label": "Τιμές για",
"hint": "Ποιες τιμές δείχνει.",
"choices": {
"in_store": "Στο κατάστημα",
"in_store_takeaway": "Πακέτο στο ταμείο",
"qr_table": "QR μενού στο τραπέζι",
"online_takeaway": "Online, παραλαβή",
"online_delivery": "Online, διανομή",
"online_preorder": "Online, με κράτηση",
"none": "Χωρίς τιμές"
}
},
"sold_out": {
"label": "Εξαντλημένα",
"choices": {
"strike": "Διαγραμμένα",
"hide": "Κρυμμένα"
}
},
"category": {
"label": "Μόνο αυτή η κατηγορία",
"hint": "Με τις υποκατηγορίες της.",
"none": "Όλο το μενού"
},
"search": {
"label": "Αναζήτηση",
"hint": "Πεδίο αναζήτησης (βολικό για γρήγορο έλεγχο τιμής)."
},
"languages": {
"label": "Γλώσσες",
"hint": "Τα κείμενα του tablet· τα ονόματα των προϊόντων είναι όπως στο μενού.",
"choices": {
"both": "Ελληνικά και Αγγλικά (διαλέγει ο πελάτης)",
"el": "Ελληνικά",
"en": "Αγγλικά"
}
},
"idle_seconds": {
"label": "Επιστροφή στην αρχή μετά από",
"hint": "Δευτερόλεπτα χωρίς άγγιγμα.",
"choices": {
"0": "Ποτέ",
"30": "30 δ",
"60": "1 λεπτό",
"120": "2 λεπτά",
"300": "5 λεπτά",
"600": "10 λεπτά"
}
}
} }
}, },
"notes": { "notes": {
+11
View File
@@ -493,5 +493,16 @@
"vegetarian": "Χορτοφαγικό", "vegetarian": "Χορτοφαγικό",
"vegan": "Vegan" "vegan": "Vegan"
} }
},
"menuTablet": {
"title": "Μενού",
"search": "Αναζήτηση στο μενού…",
"clear": "Καθαρισμός",
"language": "Γλώσσα",
"categories": "Κατηγορίες",
"noResults": "Δεν βρέθηκε τίποτα για «{{q}}».",
"empty": "Το μενού είναι άδειο.",
"soldOut": "Εξαντλήθηκε",
"close": "Κλείσιμο"
} }
} }
+84 -1
View File
@@ -272,12 +272,95 @@
}, },
"menu_tablet": { "menu_tablet": {
"name": "Menu tablet", "name": "Menu tablet",
"description": "A self-service catalogue on a tablet (coming soon).", "description": "The venue's menu on a tablet: a quick price check for staff and a menu for guests.",
"limits": { "limits": {
"devices": "Menu tablets" "devices": "Menu tablets"
}, },
"permissions": { "permissions": {
"manage": "Set up menu tablets" "manage": "Set up menu tablets"
},
"config_groups": {
"look": "Look",
"menu": "Menu",
"use": "Use"
},
"config": {
"view": {
"label": "View",
"hint": "Compact: a dense list. Expanded: with a small photo and the description. Full: big cards.",
"choices": {
"compact": "Compact",
"expanded": "Expanded",
"full": "Full"
}
},
"photos": {
"label": "Photos"
},
"descriptions": {
"label": "Descriptions"
},
"group": {
"label": "Group by category",
"hint": "Off: one list of every product (A to Z)."
},
"theme": {
"label": "Colours",
"choices": {
"light": "Light",
"dark": "Dark"
}
},
"sales_point": {
"label": "Prices of",
"hint": "Whose prices it shows.",
"choices": {
"in_store": "In the shop",
"in_store_takeaway": "Takeaway at the counter",
"qr_table": "QR menu at the table",
"online_takeaway": "Online, takeaway",
"online_delivery": "Online, delivery",
"online_preorder": "Online, with a booking",
"none": "No prices"
}
},
"sold_out": {
"label": "Sold-out products",
"choices": {
"strike": "Crossed out",
"hide": "Hidden"
}
},
"category": {
"label": "Only this category",
"hint": "With its sub-categories.",
"none": "The whole menu"
},
"search": {
"label": "Search",
"hint": "A search box (handy for a quick price check)."
},
"languages": {
"label": "Languages",
"hint": "The tablet's own texts; product names are as in the menu.",
"choices": {
"both": "Greek and English (the guest picks)",
"el": "Greek",
"en": "English"
}
},
"idle_seconds": {
"label": "Back to the start after",
"hint": "Seconds without a touch.",
"choices": {
"0": "Never",
"30": "30 s",
"60": "1 min",
"120": "2 min",
"300": "5 min",
"600": "10 min"
}
}
} }
}, },
"notes": { "notes": {
+11
View File
@@ -493,5 +493,16 @@
"vegetarian": "Vegetarian", "vegetarian": "Vegetarian",
"vegan": "Vegan" "vegan": "Vegan"
} }
},
"menuTablet": {
"title": "Menu",
"search": "Search the menu…",
"clear": "Clear",
"language": "Language",
"categories": "Categories",
"noResults": "Nothing found for \"{{q}}\".",
"empty": "The menu is empty.",
"soldOut": "Sold out",
"close": "Close"
} }
} }
+2 -1
View File
@@ -7,7 +7,8 @@
"main": "src/index.js", "main": "src/index.js",
"exports": { "exports": {
".": "./src/index.js", ".": "./src/index.js",
"./sample": "./sample/Sample.jsx" "./sample": "./sample/Sample.jsx",
"./latin": "./src/latin.js"
}, },
"scripts": { "scripts": {
"test": "node --test \"tests/*.test.mjs\"", "test": "node --test \"tests/*.test.mjs\"",
@@ -0,0 +1,209 @@
// The menu tablet (plan step 5.7a, owner 2026-11-17): the venue's menu on a tablet, for staff ("how
// much is the steak?": search, see the price) and for guests (a menu at the entrance, or handed to
// them). Just the products and their categories. How it looks is the tablet's device config:
// compact / expanded / full view, photos, descriptions, grouped or one A–Z list, whose prices,
// sold-out style, search, one category or all, languages, back to the start after a while, light /
// dark. Keeps the last menu for offline; a menu change arrives live (`menu_tablet.changed`).
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Search, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { applyTheme, Dialog, getStoredTheme, Input } from '@xenia/ui'
import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context'
import { idle, languagesOf, search, sections } from './logic'
const quiet = { xenia: { noOverride: true } }
const CACHE_KEY = 'xenia:menu-tablet:menu'
const REFRESH_MS = 5 * 60_000
function readCache() {
try { return JSON.parse(localStorage.getItem(CACHE_KEY) || 'null') } catch { return null }
}
export default function MenuTabletApp() {
const { t } = useTranslation('terminal')
const { language, changeLanguage } = useLanguage()
const [data, setData] = useState(readCache)
const [q, setQ] = useState('')
const [open, setOpen] = useState(null)
const lastTouch = useRef(0) // set on the first touch and when the tablet starts (below)
const scroller = useRef(null)
const load = useCallback(async () => {
try {
const { data: d } = await client.get('/api/menu-tablet/menu', quiet)
setData(d)
try { localStorage.setItem(CACHE_KEY, JSON.stringify(d)) } catch { /* the memory copy still shows */ }
} catch { /* offline: keep what we have */ }
}, [])
useEffect(() => { load() }, [load])
useLiveEvent('ready', load)
useLiveEvents(['menu_tablet.changed', 'device.updated'], load)
useEffect(() => {
const id = setInterval(load, REFRESH_MS)
return () => clearInterval(id)
}, [load])
const cfg = data?.config || {}
const langs = languagesOf(cfg)
// the tablet's language: one of those offered (the first after a reset)
useEffect(() => {
if (data && !langs.includes(language)) changeLanguage(langs[0])
}, [data, langs.join(','), language]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
applyTheme(cfg.theme || 'light')
return () => { applyTheme(getStoredTheme()) }
}, [cfg.theme])
// back to the start after a while without a touch
const reset = useCallback(() => {
setQ('')
setOpen(null)
scroller.current?.scrollTo?.({ top: 0 })
if (langs.length > 1 && language !== langs[0]) changeLanguage(langs[0])
}, [langs, language, changeLanguage])
useEffect(() => {
const touch = () => { lastTouch.current = Date.now() }
touch()
window.addEventListener('pointerdown', touch)
window.addEventListener('keydown', touch)
const id = setInterval(() => {
if (idle(lastTouch.current, cfg.idle_seconds)) { reset(); lastTouch.current = Date.now() }
}, 5000)
return () => { window.removeEventListener('pointerdown', touch); window.removeEventListener('keydown', touch); clearInterval(id) }
}, [cfg.idle_seconds, reset])
const groups = useMemo(() => sections(data, cfg.group !== false, language), [data, cfg.group, language])
const found = useMemo(() => search(data, q, language), [data, q, language])
const goTo = id => scroller.current?.querySelector(`[data-section="${id}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'start' })
if (!data) return <main className="fixed inset-0 bg-canvas" data-testid="app-menu_tablet" />
return (
<main className="fixed inset-0 bg-canvas text-ink flex flex-col select-none" data-testid="app-menu_tablet" data-view={cfg.view}>
<header className="flex items-center gap-3 px-4 py-3 border-b border-line bg-surface">
<h1 className="text-title font-semibold truncate flex-1" data-testid="menu-venue">{data.venue?.name || t('menuTablet.title')}</h1>
{cfg.search !== false && (
<div className="relative w-full max-w-xs">
<Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('menuTablet.search')} aria-label={t('menuTablet.search')}
className="pl-9 w-full" data-testid="menu-search" />
{q && <button type="button" onClick={() => setQ('')} aria-label={t('menuTablet.clear')} className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-ink-3"><X size={16} /></button>}
</div>
)}
{langs.length > 1 && (
<div className="flex rounded-control border border-line overflow-hidden" role="group" aria-label={t('menuTablet.language')}>
{langs.map(l => (
<button key={l} type="button" onClick={() => changeLanguage(l)} aria-pressed={language === l} data-testid={`menu-lang-${l}`}
className={`px-3 py-2 text-label font-semibold ${language === l ? 'bg-accent text-accent-fg' : 'bg-surface text-ink-2'}`}>{l.toUpperCase()}</button>
))}
</div>
)}
</header>
{!q && cfg.group !== false && groups.length > 1 && (
<nav className="flex gap-2 px-4 py-2 overflow-x-auto border-b border-line bg-surface-2" aria-label={t('menuTablet.categories')} data-testid="menu-categories">
{groups.filter(g => g.depth === 0).map(g => (
<button key={g.id} type="button" onClick={() => goTo(g.id)} data-testid="menu-category-chip"
className="px-3 py-1.5 rounded-control bg-surface border border-line text-label font-medium whitespace-nowrap">{g.name}</button>
))}
</nav>
)}
<div ref={scroller} className="flex-1 overflow-y-auto px-4 py-4">
{q ? (
found.length ? <Items products={found} cfg={cfg} onOpen={setOpen} testid="menu-results" />
: <p className="text-body text-ink-3 text-center py-10" data-testid="menu-no-results">{t('menuTablet.noResults', { q })}</p>
) : groups.length === 0 ? <p className="text-body text-ink-3 text-center py-10">{t('menuTablet.empty')}</p> : (
groups.map(g => (
<section key={g.id} data-section={g.id} className="mb-6 scroll-mt-4" data-testid="menu-section">
{g.name && <h2 className={`${g.depth ? 'text-body-lg' : 'text-heading'} font-semibold text-ink mb-3`}>{g.name}</h2>}
<Items products={g.products} cfg={cfg} onOpen={setOpen} />
</section>
))
)}
</div>
{open && <Details product={open} cfg={cfg} onClose={() => setOpen(null)} />}
</main>
)
}
function Price({ value, className = '' }) {
const { formatMoney } = useFormat()
return value == null ? null : <span className={`tabular-nums font-semibold text-accent-ink whitespace-nowrap ${className}`} data-testid="menu-price">{formatMoney(value)}</span>
}
function SoldOut({ product }) {
const { t } = useTranslation('terminal')
return product.available ? null : <span className="text-caption font-semibold text-danger-ink uppercase" data-testid="menu-sold-out">{t('menuTablet.soldOut')}</span>
}
/** The products in the tablet's view: compact rows, expanded rows, or full cards. */
function Items({ products, cfg, onOpen, testid = 'menu-items' }) {
const view = cfg.view || 'expanded'
const photos = cfg.photos !== false
const desc = cfg.descriptions !== false
if (view === 'full') {
return (
<ul className="grid gap-4" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(15rem, 1fr))' }} data-testid={testid}>
{products.map(p => (
<li key={p.id}>
<button type="button" onClick={() => onOpen(p)} data-testid="menu-item" data-id={p.id} data-available={p.available ? 'true' : 'false'}
className={`w-full text-left rounded-card border border-line bg-surface overflow-hidden grid ${p.available ? '' : 'opacity-60'}`}>
{photos && (p.image ? <img src={p.image.card} alt="" loading="lazy" className="w-full aspect-[4/3] object-cover bg-surface-3" />
: <div className="w-full aspect-[4/3] bg-surface-2 flex items-center justify-center text-display font-semibold text-ink-3" aria-hidden="true">{p.name.trim()[0]}</div>)}
<div className="p-3 grid gap-1">
<div className="flex items-start gap-2">
<span className={`text-body-lg font-semibold flex-1 ${p.available ? '' : 'line-through'}`}>{p.name}</span>
<Price value={p.price} className="text-body-lg" />
</div>
<SoldOut product={p} />
{desc && p.description && <p className="text-label text-ink-2 line-clamp-3">{p.description}</p>}
</div>
</button>
</li>
))}
</ul>
)
}
return (
<ul className={`grid ${view === 'compact' ? 'gap-0' : 'gap-2'}`} data-testid={testid}>
{products.map(p => (
<li key={p.id}>
<button type="button" onClick={() => onOpen(p)} data-testid="menu-item" data-id={p.id} data-available={p.available ? 'true' : 'false'}
className={`w-full text-left flex items-center gap-3 ${view === 'compact' ? 'py-2 border-b border-line' : 'p-2 rounded-card bg-surface border border-line'} ${p.available ? '' : 'opacity-60'}`}>
{view === 'expanded' && photos && p.image && <img src={p.image.thumb} alt="" loading="lazy" className="w-16 h-16 rounded-control object-cover bg-surface-3 shrink-0" />}
<div className="flex-1 min-w-0 grid gap-0.5">
<div className="flex items-baseline gap-2">
<span className={`${view === 'compact' ? 'text-body' : 'text-body-lg'} font-medium ${p.available ? '' : 'line-through'}`}>{p.name}</span>
<SoldOut product={p} />
</div>
{view === 'expanded' && desc && p.description && <p className="text-label text-ink-2 line-clamp-2">{p.description}</p>}
</div>
<Price value={p.price} className={view === 'compact' ? 'text-body' : 'text-body-lg'} />
</button>
</li>
))}
</ul>
)
}
/** One product, big: its photo, price, description and tags. */
function Details({ product: p, cfg, onClose }) {
const { t } = useTranslation('terminal')
return (
<Dialog open size="md" title={p.name} onClose={onClose} closeLabel={t('menuTablet.close')}>
<div className="grid gap-3" data-testid="menu-details" data-id={p.id}>
{cfg.photos !== false && p.image && <img src={p.image.full} alt="" className="w-full rounded-card object-cover max-h-[50vh]" />}
<div className="flex items-center gap-3">
<Price value={p.price} className="text-heading" />
<SoldOut product={p} />
</div>
{p.description && <p className="text-body text-ink-2 whitespace-pre-line">{p.description}</p>}
{p.tags?.length > 0 && (
<div className="flex flex-wrap gap-1.5">{p.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-control bg-surface-2 text-label text-ink-2">{tag}</span>)}</div>
)}
</div>
</Dialog>
)
}
+50
View File
@@ -0,0 +1,50 @@
// The menu tablet's logic (plan step 5.7a). Pure: unit-tested in Node (tests/menu-tablet.test.mjs).
import { latin } from '@xenia/i18n/latin' // plain JS (Node tests)
/** Lowercase, no accents: "Σουβλάκι" and "σουβλακι" match. */
export function fold(text) {
return String(text ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim()
}
/** Does a product match a search? By its name in Greek or in Latin letters ("souvlaki"), or a tag. */
export function matches(product, query) {
const q = fold(query)
if (!q) return true
const name = fold(product.name)
return name.includes(q) || fold(latin(product.name)).includes(q) || (product.tags || []).some(t => fold(t).includes(q))
}
/** Every product once, A to Z (the ungrouped list and the search's results). */
export function allProducts(data, language = 'el') {
return Object.values(data?.products || {}).sort((a, b) => a.name.localeCompare(b.name, language))
}
/** What a search finds: the products whose name (or tag) matches, A to Z; a name that starts with it first. */
export function search(data, query, language = 'el') {
const q = fold(query)
if (!q) return []
const found = allProducts(data, language).filter(p => matches(p, q))
const starts = p => fold(p.name).startsWith(q) || fold(latin(p.name)).startsWith(q)
return [...found.filter(starts), ...found.filter(p => !starts(p))]
}
/** The sections to show: grouped = each category with its products; not grouped = one A–Z list. */
export function sections(data, grouped, language = 'el') {
if (!data) return []
if (!grouped) return [{ id: 'all', name: null, depth: 0, products: allProducts(data, language) }]
return (data.categories || [])
.map(c => ({ ...c, products: c.products.map(id => data.products[String(id)]).filter(Boolean) }))
.filter(c => c.products.length)
}
/** Back to the start? After `seconds` without a touch (0 = never). */
export function idle(lastTouchMs, seconds, nowMs = Date.now()) {
return Number(seconds) > 0 && nowMs - lastTouchMs >= Number(seconds) * 1000
}
/** The languages a guest can pick, the first one being where the tablet starts. */
export function languagesOf(config) {
if (config?.languages === 'el') return ['el']
if (config?.languages === 'en') return ['en']
return ['el', 'en']
}
+2 -1
View File
@@ -1,12 +1,13 @@
// The apps a paired screen can run (plan step 3.1b, APPS_PLATFORM D-2): the device's // The apps a paired screen can run (plan step 3.1b, APPS_PLATFORM D-2): the device's
// app_key (GET /api/devices/me) picks one. Each app is its own lazily loaded chunk, so a // app_key (GET /api/devices/me) picks one. Each app is its own lazily loaded chunk, so a
// kitchen screen never downloads the POS. The menu tablet arrives in step 5.7. // kitchen screen never downloads the POS.
export const APPS = { export const APPS = {
kds: () => import('./kds/KdsApp.jsx'), kds: () => import('./kds/KdsApp.jsx'),
pos_counter: () => import('./pos/PosApp.jsx'), pos_counter: () => import('./pos/PosApp.jsx'),
customer_display: () => import('./customer-display/CustomerDisplayApp.jsx'), customer_display: () => import('./customer-display/CustomerDisplayApp.jsx'),
signage: () => import('./signage/SignageApp.jsx'), signage: () => import('./signage/SignageApp.jsx'),
menu_tablet: () => import('./menu-tablet/MenuTabletApp.jsx'),
} }
/** The loader of an app, or null when this terminal version doesn't have it. */ /** The loader of an app, or null when this terminal version doesn't have it. */
+36
View File
@@ -0,0 +1,36 @@
// The menu tablet's logic (plan step 5.7a).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { allProducts, fold, idle, languagesOf, matches, search, sections } from '../src/apps/menu-tablet/logic.js'
const data = {
categories: [{ id: 1, name: 'Grill', depth: 0, products: [2, 1] }, { id: 3, name: 'Pita', depth: 1, products: [1] }, { id: 4, name: 'Empty', depth: 0, products: [9] }],
products: { 1: { id: 1, name: 'Σουβλάκι χοιρινό', tags: [] }, 2: { id: 2, name: 'Μπριζόλα', tags: ['gluten-free'] }, 5: { id: 5, name: 'Αναψυκτικό', tags: [] } },
}
test('search finds Greek names with or without accents, in Latin letters, and by tag', () => {
assert.equal(fold('Σουβλάκι'), 'σουβλακι')
assert.ok(matches(data.products[1], 'σουβλακι'))
assert.ok(matches(data.products[1], 'souvl'))
assert.ok(matches(data.products[2], 'gluten'))
assert.ok(!matches(data.products[2], 'souvl'))
assert.deepEqual(search(data, 'ι').map(p => p.id).slice(0, 1).length, 1)
assert.deepEqual(search(data, 'mpriz').map(p => p.id), [2])
assert.deepEqual(search(data, ' '), [])
})
test('sections: grouped by category (empty ones left out) or one A–Z list', () => {
assert.deepEqual(sections(data, true).map(s => [s.name, s.products.map(p => p.id)]), [['Grill', [2, 1]], ['Pita', [1]]])
assert.deepEqual(sections(data, false)[0].products.map(p => p.id), allProducts(data).map(p => p.id))
assert.deepEqual(allProducts(data).map(p => p.name), ['Αναψυκτικό', 'Μπριζόλα', 'Σουβλάκι χοιρινό'])
assert.deepEqual(sections(null, true), [])
})
test('back to the start after a while; the languages a guest can pick', () => {
assert.equal(idle(0, 60, 59_000), false)
assert.equal(idle(0, 60, 60_000), true)
assert.equal(idle(0, 0, 9e9), false)
assert.deepEqual(languagesOf({ languages: 'both' }), ['el', 'en'])
assert.deepEqual(languagesOf({ languages: 'en' }), ['en'])
assert.deepEqual(languagesOf(undefined), ['el', 'en'])
})
+3 -3
View File
@@ -5,10 +5,10 @@ import { APPS, appLoader } from '../src/apps/registry.js'
import { DEVICE_KEY, SESSION_KEY, createDeviceStore } from '../src/device/storage.js' import { DEVICE_KEY, SESSION_KEY, createDeviceStore } from '../src/device/storage.js'
import { deviceGone, formatCode, idleExpired, liveAction, pollOutcome, refusedAction, screenFor } from '../src/device/flow.js' import { deviceGone, formatCode, idleExpired, liveAction, pollOutcome, refusedAction, screenFor } from '../src/device/flow.js'
test('the apps a screen can run: KDS, counter POS, customer display, signage (the menu tablet in 5.7)', () => { test('the apps a screen can run: KDS, counter POS, customer display, signage, menu tablet', () => {
assert.deepEqual(Object.keys(APPS).sort(), ['customer_display', 'kds', 'pos_counter', 'signage']) assert.deepEqual(Object.keys(APPS).sort(), ['customer_display', 'kds', 'menu_tablet', 'pos_counter', 'signage'])
assert.equal(typeof appLoader('kds'), 'function') assert.equal(typeof appLoader('kds'), 'function')
assert.equal(appLoader('menu_tablet'), null) assert.equal(appLoader('waiter'), null)
assert.equal(appLoader('toString'), null) // never a prototype member assert.equal(appLoader('toString'), null) // never a prototype member
}) })
+103
View File
@@ -0,0 +1,103 @@
// Menu tablet suite (plan step 5.7a): a tablet paired as a menu tablet shows the venue's menu with
// prices; search finds a product (also typed in Latin letters) and its price; a product opens big;
// the view options from the device config change it live; a price change shows without a reload;
// the guest's language; back to the start after a while without a touch.
// Starts its own backend (:8067) and the terminal (:5195).
// node menu_tablet.mjs
import path from 'node:path'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, OUT, reporter, sleep, waitFor } from './lib/env.mjs'
import { startBackend, startTerminalVite } from './lib/proc.mjs'
import { supportLogin } from './lib/support.mjs'
const backend = await startBackend({ port: 8067, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } })
const term = await startTerminalVite({ port: 5195, backendUrl: backend.url })
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const r = reporter('menu tablet: the menu, search, views, live prices, languages, idle reset (5.7a)')
const errors = []
let failures = 0
async function api(method, url, { token, body } = {}) {
const res = await fetch(backend.url + url, {
method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
})
const text = await res.text()
let data = null
try { data = JSON.parse(text) } catch { data = text }
if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`)
return data
}
const shown = (page, testId, timeout = 10_000) => page.getByTestId(testId).first().waitFor({ timeout }).then(() => true).catch(() => false)
try {
const boss = await supportLogin(backend.url)
await api('PUT', '/api/platform/modules/menu_tablet', { token: boss, body: { enabled: true } }).catch(() => {})
const products = (await api('GET', '/api/products/?sold_at=in_store', { token: boss })).filter(p => !p.is_service_item && p.lifecycle_status === 'active')
const souvlaki = products.find(p => /Σουβλάκι/.test(p.name)) || products[0]
const tab = await (await browser.newContext({ viewport: { width: 1180, height: 820 }, hasTouch: true })).newPage()
tab.on('pageerror', e => errors.push(e.message))
await tab.goto(term.url)
await shown(tab, 'pairing-code', 20_000)
const code = await tab.getByTestId('pairing-code').getAttribute('data-code')
const dev = await api('POST', '/api/devices', { token: boss, body: { code, app_key: 'menu_tablet', name: 'Entrance' } })
r.check('a tablet paired as a menu tablet shows the menu by category, with prices', await shown(tab, 'menu-section', 20_000)
&& await tab.getByTestId('menu-section').count() > 1 && await tab.getByTestId('menu-price').count() > 5)
await tab.screenshot({ path: path.join(OUT, 'menu-tablet-expanded.png') })
// the staff's price check
await tab.getByTestId('menu-search').fill('souvl')
const hit = tab.getByTestId('menu-results').locator(`[data-testid="menu-item"][data-id="${souvlaki.id}"]`)
r.check(`search in Latin letters ("souvl") finds "${souvlaki.name}" with its price`, await hit.waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
&& (await hit.textContent()).includes(souvlaki.base_price.toFixed(2)))
await hit.click()
r.check('…and opens it big with its price', await shown(tab, 'menu-details', 5000)
&& (await tab.getByTestId('menu-details').getByTestId('menu-price').textContent()).includes(souvlaki.base_price.toFixed(2)))
await tab.keyboard.press('Escape')
await tab.getByTestId('menu-search').fill('zzzz')
r.check('nothing found: says so', await shown(tab, 'menu-no-results', 5000))
await tab.getByTestId('menu-search').fill('')
// the view options from the device config, live
await api('PATCH', `/api/devices/${dev.id}`, { token: boss, body: { config: { view: 'full', theme: 'dark' } } })
r.check('the view from the manager (full cards, dark) changes the tablet at once',
!!(await waitFor(async () => (await tab.getByTestId('app-menu_tablet').getAttribute('data-view')) === 'full', 15_000, 300))
&& await tab.evaluate(() => document.documentElement.dataset.theme) === 'dark')
await tab.screenshot({ path: path.join(OUT, 'menu-tablet-full.png') })
await api('PATCH', `/api/devices/${dev.id}`, { token: boss, body: { config: { view: 'compact', group: false, theme: 'light' } } })
r.check('compact, one A–Z list', !!(await waitFor(async () => (await tab.getByTestId('app-menu_tablet').getAttribute('data-view')) === 'compact'
&& (await tab.getByTestId('menu-section').count()) === 1, 15_000, 300)))
await tab.screenshot({ path: path.join(OUT, 'menu-tablet-compact.png') })
// a price change, live
await api('PUT', `/api/products/${souvlaki.id}`, { token: boss, body: { base_price: 7.7 } })
const live = await waitFor(async () => ((await tab.locator(`[data-testid="menu-item"][data-id="${souvlaki.id}"]`).textContent().catch(() => '')).includes('7.70') ? true : null), 15_000, 300)
r.check('a price change shows on the tablet without a reload', !!live)
// the guest's language, then back to the start after a while
await tab.getByTestId('menu-lang-en').click()
const enPlaceholder = await tab.getByTestId('menu-search').getAttribute('placeholder')
await tab.getByTestId('menu-lang-el').click()
const elPlaceholder = await tab.getByTestId('menu-search').getAttribute('placeholder')
r.check('the guest picks the language (the tablet\'s own texts)', enPlaceholder !== elPlaceholder, `${enPlaceholder} / ${elPlaceholder}`)
await api('PATCH', `/api/devices/${dev.id}`, { token: boss, body: { config: { idle_seconds: 30 } } })
await sleep(1500)
await tab.getByTestId('menu-search').fill('souvl')
await tab.getByTestId('menu-lang-en').click()
const reset = await waitFor(async () => ((await tab.getByTestId('menu-search').inputValue()) === '' ? true : null), 45_000, 1000)
r.check('after a while without a touch: back to the start (search cleared, the first language)', !!reset
&& await tab.getByTestId('menu-lang-el').getAttribute('aria-pressed') === 'true')
r.check('no page errors', errors.length === 0, errors.join(' | '))
failures += r.done()
} catch (e) {
console.error(e)
r.check('the suite ran to the end', false, String(e.message).split(/\r?\n/)[0])
failures += r.done()
} finally {
await browser.close()
term.stop()
await backend.stop()
}
process.exit(failures ? 1 : 0)
+2 -1
View File
@@ -28,7 +28,8 @@ const suites = [
['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E], ['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E],
['media (Media page, product photos, waiter offline photos)', 'node', ['media.mjs'], E2E], ['media (Media page, product photos, waiter offline photos)', 'node', ['media.mjs'], E2E],
['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E], ['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E],
['signage (the player on a TV)', 'node', ['signage.mjs'], E2E], ['signage (the player on a TV, the editor)', 'node', ['signage.mjs'], E2E],
['menu tablet (menu, search, views, live prices)', 'node', ['menu_tablet.mjs'], E2E],
['order app (cloud: takeaway + delivery + bookings)', 'node', ['order_app.mjs'], E2E], ['order app (cloud: takeaway + delivery + bookings)', 'node', ['order_app.mjs'], E2E],
['QR menu at the table (cloud + venue)', 'node', ['qr_table.mjs'], E2E], ['QR menu at the table (cloud + venue)', 'node', ['qr_table.mjs'], E2E],
['stack (compose: terminal :8082, LAN only)', 'node', ['stack.mjs'], E2E], ['stack (compose: terminal :8082, LAN only)', 'node', ['stack.mjs'], E2E],