diff --git a/docs/README.md b/docs/README.md index 2d46952..6eb1c1b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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/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///` (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//` 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/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/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()` | diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index 006be86..a26219d 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -493,5 +493,16 @@ "vegetarian": "Χορτοφαγικό", "vegan": "Vegan" } + }, + "menuTablet": { + "title": "Μενού", + "search": "Αναζήτηση στο μενού…", + "clear": "Καθαρισμός", + "language": "Γλώσσα", + "categories": "Κατηγορίες", + "noResults": "Δεν βρέθηκε τίποτα για «{{q}}».", + "empty": "Το μενού είναι άδειο.", + "soldOut": "Εξαντλήθηκε", + "close": "Κλείσιμο" } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index 4cbdaa2..d6bd6d0 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -493,5 +493,16 @@ "vegetarian": "Vegetarian", "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" } } diff --git a/packages/i18n/package.json b/packages/i18n/package.json index 733c8dd..8792f61 100644 --- a/packages/i18n/package.json +++ b/packages/i18n/package.json @@ -7,7 +7,8 @@ "main": "src/index.js", "exports": { ".": "./src/index.js", - "./sample": "./sample/Sample.jsx" + "./sample": "./sample/Sample.jsx", + "./latin": "./src/latin.js" }, "scripts": { "test": "node --test \"tests/*.test.mjs\"", diff --git a/terminal/src/apps/menu-tablet/MenuTabletApp.jsx b/terminal/src/apps/menu-tablet/MenuTabletApp.jsx new file mode 100644 index 0000000..7611b41 --- /dev/null +++ b/terminal/src/apps/menu-tablet/MenuTabletApp.jsx @@ -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
+ return ( +
+
+

{data.venue?.name || t('menuTablet.title')}

+ {cfg.search !== false && ( +
+
+ )} + {langs.length > 1 && ( +
+ {langs.map(l => ( + + ))} +
+ )} +
+ + {!q && cfg.group !== false && groups.length > 1 && ( + + )} + +
+ {q ? ( + found.length ? + :

{t('menuTablet.noResults', { q })}

+ ) : groups.length === 0 ?

{t('menuTablet.empty')}

: ( + groups.map(g => ( +
+ {g.name &&

{g.name}

} + +
+ )) + )} +
+ + {open &&
setOpen(null)} />} +
+ ) +} + +function Price({ value, className = '' }) { + const { formatMoney } = useFormat() + return value == null ? null : {formatMoney(value)} +} + +function SoldOut({ product }) { + const { t } = useTranslation('terminal') + return product.available ? null : {t('menuTablet.soldOut')} +} + +/** 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 ( +
    + {products.map(p => ( +
  • + +
  • + ))} +
+ ) + } + return ( +
    + {products.map(p => ( +
  • + +
  • + ))} +
+ ) +} + +/** One product, big: its photo, price, description and tags. */ +function Details({ product: p, cfg, onClose }) { + const { t } = useTranslation('terminal') + return ( + +
+ {cfg.photos !== false && p.image && } +
+ + +
+ {p.description &&

{p.description}

} + {p.tags?.length > 0 && ( +
{p.tags.map(tag => {tag})}
+ )} +
+
+ ) +} diff --git a/terminal/src/apps/menu-tablet/logic.js b/terminal/src/apps/menu-tablet/logic.js new file mode 100644 index 0000000..6ed76d2 --- /dev/null +++ b/terminal/src/apps/menu-tablet/logic.js @@ -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'] +} diff --git a/terminal/src/apps/registry.js b/terminal/src/apps/registry.js index 19c02a9..3d5ffa8 100644 --- a/terminal/src/apps/registry.js +++ b/terminal/src/apps/registry.js @@ -1,12 +1,13 @@ // 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 -// kitchen screen never downloads the POS. The menu tablet arrives in step 5.7. +// kitchen screen never downloads the POS. export const APPS = { kds: () => import('./kds/KdsApp.jsx'), pos_counter: () => import('./pos/PosApp.jsx'), customer_display: () => import('./customer-display/CustomerDisplayApp.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. */ diff --git a/terminal/tests/menu-tablet.test.mjs b/terminal/tests/menu-tablet.test.mjs new file mode 100644 index 0000000..ce96862 --- /dev/null +++ b/terminal/tests/menu-tablet.test.mjs @@ -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']) +}) diff --git a/terminal/tests/terminal.test.mjs b/terminal/tests/terminal.test.mjs index 4fe614e..8cb27fd 100644 --- a/terminal/tests/terminal.test.mjs +++ b/terminal/tests/terminal.test.mjs @@ -5,10 +5,10 @@ import { APPS, appLoader } from '../src/apps/registry.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' -test('the apps a screen can run: KDS, counter POS, customer display, signage (the menu tablet in 5.7)', () => { - assert.deepEqual(Object.keys(APPS).sort(), ['customer_display', 'kds', 'pos_counter', 'signage']) +test('the apps a screen can run: KDS, counter POS, customer display, signage, menu tablet', () => { + assert.deepEqual(Object.keys(APPS).sort(), ['customer_display', 'kds', 'menu_tablet', 'pos_counter', 'signage']) 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 }) diff --git a/tests/e2e/menu_tablet.mjs b/tests/e2e/menu_tablet.mjs new file mode 100644 index 0000000..eb42919 --- /dev/null +++ b/tests/e2e/menu_tablet.mjs @@ -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) diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index f9ac58c..6d7bc87 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -28,7 +28,8 @@ const suites = [ ['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E], ['media (Media page, product photos, waiter offline photos)', 'node', ['media.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], ['QR menu at the table (cloud + venue)', 'node', ['qr_table.mjs'], E2E], ['stack (compose: terminal :8082, LAN only)', 'node', ['stack.mjs'], E2E],