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>
This commit is contained in:
2026-11-17 23:44:42 +02:00
co-authored by Claude Opus 5.5
parent 2a6640fe5c
commit cc81e0a31f
11 changed files with 430 additions and 6 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()` |
+11
View File
@@ -493,5 +493,16 @@
"vegetarian": "Χορτοφαγικό", "vegetarian": "Χορτοφαγικό",
"vegan": "Vegan" "vegan": "Vegan"
} }
},
"menuTablet": {
"title": "Μενού",
"search": "Αναζήτηση στο μενού…",
"clear": "Καθαρισμός",
"language": "Γλώσσα",
"categories": "Κατηγορίες",
"noResults": "Δεν βρέθηκε τίποτα για «{{q}}».",
"empty": "Το μενού είναι άδειο.",
"soldOut": "Εξαντλήθηκε",
"close": "Κλείσιμο"
} }
} }
+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],