diff --git a/docs/README.md b/docs/README.md index 99f7a29..6b2f086 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,7 +48,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) | | `local_backend/routers/customer_display.py`, `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`). **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 | +| `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`). **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/` (`logic.js`: 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 | | `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 2c1bb02..b65becc 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -479,5 +479,9 @@ "paid": "Πληρώθηκαν {{amount}}", "change": "Τα ρέστα σας: {{amount}}", "unlinked": "Δεν έχει συνδεθεί ακόμα με ταμείο (διαχείριση → Συσκευές)" + }, + "signage": { + "nothing": "Καμία λίστα για αυτή την οθόνη (Προβολή στον διαχειριστή).", + "starting": "Εκκίνηση…" } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index d63fe46..1fb268d 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -479,5 +479,9 @@ "paid": "Paid {{amount}}", "change": "Your change: {{amount}}", "unlinked": "Not linked to a counter yet (manager → Devices)" + }, + "signage": { + "nothing": "No playlist for this screen (Signage in the manager).", + "starting": "Starting…" } } diff --git a/terminal/src/apps/registry.js b/terminal/src/apps/registry.js index f404ca7..19c02a9 100644 --- a/terminal/src/apps/registry.js +++ b/terminal/src/apps/registry.js @@ -1,11 +1,12 @@ // 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. Signage and the menu tablet arrive in phase 5. +// kitchen screen never downloads the POS. The menu tablet arrives in step 5.7. 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'), } /** The loader of an app, or null when this terminal version doesn't have it. */ @@ -21,3 +22,7 @@ export const APP_THEMES = { kds: 'dark' } export function appTheme(appKey) { return Object.hasOwn(APP_THEMES, appKey) ? APP_THEMES[appKey] : null } + +// Screens nobody works at (a TV with signage): no "server unreachable" banner over what guests +// see, only a small mark in a corner; the app keeps playing what it has (5.5a). +export const QUIET_OFFLINE = new Set(['signage']) diff --git a/terminal/src/apps/signage/SignageApp.jsx b/terminal/src/apps/signage/SignageApp.jsx new file mode 100644 index 0000000..1afccaa --- /dev/null +++ b/terminal/src/apps/signage/SignageApp.jsx @@ -0,0 +1,204 @@ +// The signage player (plan step 5.5a): a TV paired as a signage screen, no sign-in. It plays its +// playlist (or the playlist its schedule picks now) full screen: slides in order, each for its +// time (a video to its end), with its transition, only on its days / hours / dates; turned for a +// TV mounted sideways. Everything it needs is kept on the device: the last answer of +// GET /api/signage/screen in localStorage and every picture and video as an in-memory copy, so it +// keeps playing (and switching by its schedule) while the server is down, and catches up on +// `signage.changed`, a reconnect, or every few minutes (prices that change by time alone). +// Menu boards and widgets are drawn in 5.5b. +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useTranslation } from '@xenia/i18n' +import client from '../../api/client' +import { useDevice, useLiveEvent, useLiveEvents } from '../../device/context' +import { frameStyle, localNow, mediaUrls, nextSlide, playlistNow, slideMs } from './logic' +import { MenuSlide, TextSlide } from './Slides' + +const quiet = { xenia: { noOverride: true } } +const CACHE_KEY = 'xenia:signage:screen' +const REFRESH_MS = 5 * 60_000 +const VIDEO_MAX_MS = 15 * 60_000 // a video "to its end" that never ends moves on after this +const KEEP_VIDEO_BYTES = 120 * 1024 * 1024 // bigger videos stream from the server (not kept offline) +const TRANSITION_MS = 800 + +function readCache() { + try { return JSON.parse(localStorage.getItem(CACHE_KEY) || 'null') } catch { return null } +} +function writeCache(data) { + try { localStorage.setItem(CACHE_KEY, JSON.stringify(data)) } catch { /* full or blocked: the memory copy still plays */ } +} + +/** url → an in-memory copy (object URL) of every file the playlists need; old copies are let go. */ +function useKeptMedia(urls) { + const [kept, setKept] = useState({}) + const keptRef = useRef({}) + const key = urls.slice().sort().join('|') + useEffect(() => { + let live = true + const wanted = key ? key.split('|') : [] + ;(async () => { + for (const url of wanted) { + if (keptRef.current[url]) continue + try { + const res = await fetch(url) + if (!res.ok) continue + const size = Number(res.headers.get('content-length') || 0) + if (size > KEEP_VIDEO_BYTES) continue + const blob = await res.blob() + if (!live) return + keptRef.current = { ...keptRef.current, [url]: URL.createObjectURL(blob) } + setKept(keptRef.current) + } catch { /* offline: the next answer tries again; the address still works while online */ } + } + const gone = Object.keys(keptRef.current).filter(u => !wanted.includes(u)) + if (gone.length) { + const next = { ...keptRef.current } + for (const u of gone) { URL.revokeObjectURL(next[u]); delete next[u] } + keptRef.current = next + if (live) setKept(next) + } + })() + return () => { live = false } + }, [key]) + useEffect(() => () => Object.values(keptRef.current).forEach(u => URL.revokeObjectURL(u)), []) + return kept +} + +export default function SignageApp() { + const { t } = useTranslation('terminal') + const { offline } = useDevice() + const [data, setData] = useState(readCache) + const [now, setNow] = useState(() => new Date()) + + const load = useCallback(async () => { + try { + const { data: d } = await client.get('/api/signage/screen', quiet) + setData(prev => (prev?.version === d.version ? prev : d)) + writeCache(d) + } catch { /* keep playing what we have */ } + }, []) + useEffect(() => { load() }, [load]) + useLiveEvent('ready', load) + useLiveEvents(['signage.changed', 'device.updated'], load) + useEffect(() => { + const id = setInterval(load, REFRESH_MS) + return () => clearInterval(id) + }, [load]) + useEffect(() => { + const id = setInterval(() => setNow(new Date()), 1000) + return () => clearInterval(id) + }, []) + + const kept = useKeptMedia(useMemo(() => mediaUrls(data), [data])) + const playlist = playlistNow(data, now) + const tz = data?.schedule?.timezone + const screen = data?.screen + return ( +
+
+ {playlist?.slides?.length + ? + : } +
+
+ ) +} + +function Empty({ text }) { + return ( +
+ {text} +
+ ) +} + +/** Plays one playlist: the current slide, the next when its time is up, with the transition. */ +function Player({ playlist, kept, tz, venue, now }) { + const local = localNow(tz, now) + const slides = playlist.slides + const [cur, setCur] = useState(() => ({ index: nextSlide(slides, -1, local), at: Date.now(), n: 0 })) + const [prev, setPrev] = useState(null) + const media = id => { + const m = playlist.media?.[String(id)] + return m ? { ...m, src: kept[m.url] || m.url } : null + } + + const curRef = useRef(cur) + useEffect(() => { curRef.current = cur }) + const advance = useCallback(() => { + const c = curRef.current + const next = nextSlide(slides, c.index, localNow(tz, new Date())) + setPrev(c.index >= 0 ? c : null) + setCur({ index: next, at: Date.now(), n: c.n + 1 }) + }, [slides, tz]) + + // the slide list changed (an edit): keep going from a slide that still exists + useEffect(() => { + setCur(c => (c.index >= 0 && c.index < slides.length ? c : { index: nextSlide(slides, -1, localNow(tz, new Date())), at: Date.now(), n: c.n + 1 })) + }, [slides, tz]) + + const slide = cur.index >= 0 ? slides[cur.index] : null + // time's up (videos to their end call advance themselves, with a safety limit) + useEffect(() => { + if (!slide) return undefined + const ms = slideMs(slide) ?? VIDEO_MAX_MS + const id = setTimeout(advance, ms) + return () => clearTimeout(id) + }, [slide, cur.n, advance]) + // a slide that may no longer show (its window ended) is skipped at once; none showing → wait + useEffect(() => { + if (cur.index < 0 && nextSlide(slides, -1, local) >= 0) advance() + }, [cur.index, slides, local.minutes, advance]) // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { + if (!prev) return undefined + const id = setTimeout(() => setPrev(null), TRANSITION_MS) + return () => clearTimeout(id) + }, [prev]) + + if (!slide) return + const transition = slide.transition || playlist.transition || 'fade' + return ( + <> + {prev && slides[prev.index] && ( + + )} + + + ) +} + +function Layer({ slide, media, venue, now, onEnded, className, current = false }) { + return ( +
+ {slide.kind === 'image' && } + {slide.kind === 'video' && } + {slide.kind === 'text' && } + {slide.kind === 'menu' && } +
+ ) +} + +function ImageSlide({ content, media }) { + const m = media(content.media_id) + return ( +
+ {m && } +
+ ) +} + +function VideoSlide({ slide, media, onEnded }) { + const c = slide.content + const m = media(c.media_id) + const ref = useRef(null) + useEffect(() => { ref.current?.play?.().catch(() => {}) }, [m?.src]) + return ( +
+ {m &&
+ ) +} diff --git a/terminal/src/apps/signage/Slides.jsx b/terminal/src/apps/signage/Slides.jsx new file mode 100644 index 0000000..e7a708c --- /dev/null +++ b/terminal/src/apps/signage/Slides.jsx @@ -0,0 +1,66 @@ +// Text and menu slides of the signage player (plan steps 5.5a, 5.5b). Colours, fonts and sizes +// here are the venue's own choices for its TV (slide content = data, CS-16), so they are inline +// styles, not tokens. Sizes scale with the screen (vmin), so a slide looks the same on any TV. +import { useFormat } from '@xenia/i18n' +import { FONTS } from './logic' + + +/** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */ +export function Background({ bg, media }) { + const m = bg?.kind === 'media' ? media(bg.media_id) : null + return ( +
+ {m && } + {m && bg.dim > 0 &&
} +
+ ) +} + +const JUSTIFY = { top: 'flex-start', middle: 'center', bottom: 'flex-end' } + +export function TextSlide({ content: c, media }) { + const scale = (c.text_size || 100) / 100 + return ( +
+ +
+ {c.title &&

{c.title}

} + {c.body &&

{c.body}

} +
+
+ ) +} + +/** A first menu board (5.5a): its title and every item with its price; 5.5b lays it out fully. */ +export function MenuSlide({ slide, media }) { + const { formatMoney } = useFormat() + const c = slide.content + const scale = (c.text_size || 100) / 100 + const groups = slide.menu?.groups || [] + return ( +
+ +
+ {c.title &&

{c.title}

} +
+ {groups.map((g, i) => ( +
+ {g.category && c.category_titles !== false &&

{g.category.name}

} + {g.items.map(it => ( +
+ {it.name} + {it.price != null && {formatMoney(it.price)}} +
+ ))} +
+ ))} +
+
+
+ ) +} diff --git a/terminal/src/apps/signage/logic.js b/terminal/src/apps/signage/logic.js new file mode 100644 index 0000000..acc60ab --- /dev/null +++ b/terminal/src/apps/signage/logic.js @@ -0,0 +1,118 @@ +// The signage player's logic (plan step 5.5a). Pure: unit-tested in Node (tests/signage.test.mjs). +// The schedule rules are the server's (local_backend/services/signage_schedule.py) so a screen +// switches playlists by itself while the server is down; the same cases are tested on both sides. + +/** The venue's local clock at `date`: { weekday (0 = Monday), minutes, date: "YYYY-MM-DD" }. */ +export function localNow(timeZone, date = new Date()) { + const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', { + timeZone: timeZone || undefined, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', + weekday: 'short', hourCycle: 'h23', + }).formatToParts(date).map(p => [p.type, p.value])) + const weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].indexOf(parts.weekday) + return { weekday, minutes: Number(parts.hour) * 60 + Number(parts.minute), date: `${parts.year}-${parts.month}-${parts.day}` } +} + +/** The day before a local moment (for windows that pass midnight). */ +function yesterday(local) { + const d = new Date(`${local.date}T12:00:00Z`) + d.setUTCDate(d.getUTCDate() - 1) + return { weekday: (local.weekday + 6) % 7, minutes: local.minutes, date: d.toISOString().slice(0, 10) } +} + +const mins = hhmm => { + if (!hhmm) return null + const [h, m] = hhmm.split(':').map(Number) + return h * 60 + m +} + +function dayOk(w, local) { + const days = w.days || [] + return (!days.length || days.includes(local.weekday)) && + (!w.date_from || local.date >= w.date_from) && (!w.date_to || local.date <= w.date_to) +} + +/** Does a window (days, time_from / time_to that may pass midnight, date_from / date_to) cover `local`? */ +export function matches(w, local) { + let start = mins(w.time_from) + let end = mins(w.time_to) + if (start == null && end == null) return dayOk(w, local) + start = start ?? 0 + end = end ?? 24 * 60 + if (start < end) return local.minutes >= start && local.minutes < end && dayOk(w, local) + if (local.minutes >= start) return dayOk(w, local) + if (local.minutes < end) return dayOk(w, yesterday(local)) + return false +} + +const specific = e => ((e.date_from || e.date_to) ? 4 : 0) + (e.days?.length ? 2 : 0) + ((e.time_from || e.time_to) ? 1 : 0) + +/** The playlist a schedule plays at `local`: highest priority, then the most specific, then the later entry. */ +export function pick(entries, fallback, local) { + let best = null + let bestKey = null + ;(entries || []).forEach((e, i) => { + if (e.playlist_id == null || !matches(e, local)) return + const key = [e.priority || 0, specific(e), i] + if (!bestKey || key[0] > bestKey[0] || (key[0] === bestKey[0] && (key[1] > bestKey[1] || (key[1] === bestKey[1] && key[2] > bestKey[2])))) { + best = e.playlist_id + bestKey = key + } + }) + return best ?? fallback ?? null +} + +/** The playlist to play now from the screen's answer (GET /api/signage/screen). */ +export function playlistNow(data, now = new Date()) { + if (!data) return null + if (!data.schedule) return data.playlist || null + const id = pick(data.schedule.entries, data.schedule.fallback_playlist_id, localNow(data.schedule.timezone, now)) + return id != null ? data.playlists?.[String(id)] ?? null : null +} + +/** A slide may show now: its own window (days / hours / dates), in venue time. */ +export function slideShows(slide, local) { + return matches({ days: slide.days, time_from: slide.time_from, time_to: slide.time_to, date_from: slide.date_from, date_to: slide.date_to }, local) +} + +/** The index of the next slide that may show after `current` (wrapping), or -1 when none may. */ +export function nextSlide(slides, current, local) { + const n = slides?.length || 0 + for (let step = 1; step <= n; step++) { + const i = (((current ?? -1) + step) % n + n) % n + if (slideShows(slides[i], local)) return i + } + return -1 +} + +/** How long a slide stays, in ms; null = until its video ends (with a safety limit in the player). */ +export function slideMs(slide) { + if (slide.kind === 'video' && slide.video_to_end) return null + return Math.max(2, slide.duration_s || 10) * 1000 +} + +/** The frame's size and turn for a screen: CSS for the box that holds the slides. */ +export function frameStyle(rotation) { + const r = Number(rotation) || 0 + if (r === 90 || r === 270) { + return { width: '100vh', height: '100vw', transform: `translate(-50%, -50%) rotate(${r}deg)`, top: '50%', left: '50%', position: 'absolute' } + } + return { width: '100vw', height: '100vh', transform: r === 180 ? 'rotate(180deg)' : undefined, top: 0, left: 0, position: 'absolute' } +} + +/** Every media address a playlist (or a schedule's playlists) needs, to keep on the device. */ +export function mediaUrls(data) { + if (!data) return [] + const lists = data.schedule ? Object.values(data.playlists || {}) : (data.playlist ? [data.playlist] : []) + const out = new Set() + for (const p of lists) for (const m of Object.values(p.media || {})) if (m.url) out.add(m.url) + return [...out] +} + +/** The fonts a slide can choose (all on the device: nothing to download, works offline). */ +export const FONTS = { + sans: 'system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif', + serif: 'Georgia, "Times New Roman", serif', + rounded: 'ui-rounded, "SF Pro Rounded", "Arial Rounded MT Bold", system-ui, sans-serif', + condensed: '"Arial Narrow", "Roboto Condensed", "Helvetica Neue", sans-serif', + display: 'Impact, "Arial Black", system-ui, sans-serif', +} diff --git a/terminal/src/index.css b/terminal/src/index.css index 196caaa..e8df8a4 100644 --- a/terminal/src/index.css +++ b/terminal/src/index.css @@ -16,3 +16,22 @@ } input, textarea { -webkit-user-select: text; user-select: text; } } + +/* Signage transitions (plan step 5.5a): the new slide comes in over the old one going out. */ +.sg-in, .sg-out { animation-fill-mode: both; animation-timing-function: ease-in-out; } +.sg-out { z-index: 0; } +.sg-in { z-index: 1; } +.sg-in-fade { animation-name: sg-fade-in; } +.sg-out-fade { animation-name: sg-fade-out; } +.sg-in-slide { animation-name: sg-slide-in; } +.sg-out-slide { animation-name: sg-slide-out; } +.sg-in-zoom { animation-name: sg-zoom-in; } +.sg-out-zoom { animation-name: sg-fade-out; } +.sg-in-none, .sg-out-none { animation: none; } +.sg-out-none { display: none; } +@keyframes sg-fade-in { from { opacity: 0; } to { opacity: 1; } } +@keyframes sg-fade-out { from { opacity: 1; } to { opacity: 0; } } +@keyframes sg-slide-in { from { transform: translateX(100%); } to { transform: translateX(0); } } +@keyframes sg-slide-out { from { transform: translateX(0); } to { transform: translateX(-100%); } } +@keyframes sg-zoom-in { from { opacity: 0; transform: scale(1.12); } to { opacity: 1; transform: scale(1); } } +@media (prefers-reduced-motion: reduce) { .sg-in, .sg-out { animation: none; } .sg-out { display: none; } } diff --git a/terminal/src/screens/Terminal.jsx b/terminal/src/screens/Terminal.jsx index 8301992..56c326c 100644 --- a/terminal/src/screens/Terminal.jsx +++ b/terminal/src/screens/Terminal.jsx @@ -6,6 +6,7 @@ import { useTranslation } from '@xenia/i18n' import { Button, Spinner } from '@xenia/ui' import { useDevice } from '../device/context' import { screenFor } from '../device/flow' +import { QUIET_OFFLINE } from '../apps/registry' import AppScreen from './AppScreen' import BlockedScreen from './BlockedScreen' import PairingScreen from './PairingScreen' @@ -16,7 +17,9 @@ export default function Terminal() { const screen = screenFor(device) return ( <> - {device.offline && } + {screen === 'app' && QUIET_OFFLINE.has(device.me?.app_key) + ? (device.offline || !device.liveUp) && + : device.offline && } {screen === 'pairing' && } {screen === 'loading' &&
} {(screen === 'blocked' || screen === 'app_off') && } @@ -37,3 +40,10 @@ function OfflineBanner({ onRetry }) {
) } + +/** A screen guests look at: a small dot instead of the banner (the app keeps playing). */ +function OfflineMark() { + const { t } = useTranslation('terminal') + return +} diff --git a/terminal/tests/signage.test.mjs b/terminal/tests/signage.test.mjs new file mode 100644 index 0000000..d43a2f4 --- /dev/null +++ b/terminal/tests/signage.test.mjs @@ -0,0 +1,75 @@ +// The signage player's logic (plan step 5.5a): the same schedule cases as the server's +// local_backend/tests/test_signage_schedule.py, slide windows, the next slide, the frame. +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { frameStyle, localNow, matches, mediaUrls, nextSlide, pick, playlistNow, slideMs } from '../src/apps/signage/logic.js' + +const at = (date, hhmm) => { + const d = new Date(`${date}T12:00:00Z`) + const [h, m] = hhmm.split(':').map(Number) + return { weekday: (d.getUTCDay() + 6) % 7, minutes: h * 60 + m, date } +} +const MON_10 = at('2026-11-16', '10:00') +const MON_13 = at('2026-11-16', '13:00') +const SAT_13 = at('2026-11-21', '13:00') +const SAT_23 = at('2026-11-21', '23:30') +const SUN_01 = at('2026-11-22', '01:00') +const MON_01 = at('2026-11-16', '01:00') + +test('the venue clock in its own time zone', () => { + const l = localNow('Europe/Athens', new Date('2026-11-16T22:30:00Z')) // 00:30 on Tuesday in Athens + assert.deepEqual(l, { weekday: 1, minutes: 30, date: '2026-11-17' }) +}) + +test('which windows match (the server\'s cases)', () => { + const lunch = { time_from: '12:00', time_to: '15:00' } + assert.ok(matches(lunch, MON_13) && !matches(lunch, MON_10)) + const night = { days: [5], time_from: '22:00', time_to: '02:00' } + assert.ok(matches(night, SAT_23) && matches(night, SUN_01) && !matches(night, MON_01)) + const xmas = { date_from: '2026-12-20', date_to: '2026-12-27' } + assert.ok(matches(xmas, at('2026-12-24', '20:00')) && !matches(xmas, at('2026-12-28', '09:00'))) + assert.ok(matches({}, MON_10)) + assert.ok(matches({ time_from: '18:00' }, at('2026-11-16', '23:59'))) +}) + +test('the schedule\'s winner (the server\'s cases)', () => { + const entries = [{ playlist_id: 10, time_from: '12:00', time_to: '15:00' }, { playlist_id: 20, days: [5, 6] }, + { playlist_id: 30, days: [5, 6], time_from: '12:00', time_to: '15:00' }, + { playlist_id: 40, date_from: '2026-11-21', date_to: '2026-11-21', priority: 5 }] + assert.equal(pick(entries, 99, MON_10), 99) + assert.equal(pick(entries, 99, MON_13), 10) + assert.equal(pick(entries, 99, at('2026-11-22', '13:00')), 30) + assert.equal(pick(entries, 99, SAT_13), 40) + assert.equal(pick(entries, null, MON_10), null) +}) + +test('the playlist now, alone or from a schedule', () => { + assert.equal(playlistNow({ playlist: { id: 1 } }).id, 1) + const data = { schedule: { timezone: 'Europe/Athens', entries: [{ playlist_id: 2, time_from: '12:00', time_to: '15:00' }], fallback_playlist_id: 3 }, + playlists: { 2: { id: 2 }, 3: { id: 3 } } } + assert.equal(playlistNow(data, new Date('2026-11-16T11:00:00Z')).id, 2) // 13:00 in Athens + assert.equal(playlistNow(data, new Date('2026-11-16T08:00:00Z')).id, 3) + assert.equal(playlistNow(null), null) +}) + +test('the next slide skips the ones outside their window, and wraps', () => { + const slides = [{ id: 1 }, { id: 2, time_from: '12:00', time_to: '15:00' }, { id: 3, days: [0] }] + assert.equal(nextSlide(slides, -1, MON_10), 0) + assert.equal(nextSlide(slides, 0, MON_10), 2) // 2 is a lunch slide + assert.equal(nextSlide(slides, 2, MON_10), 0) + assert.equal(nextSlide(slides, 0, MON_13), 1) + assert.equal(nextSlide([{ id: 1, days: [6] }], -1, MON_10), -1) + assert.equal(nextSlide([], -1, MON_10), -1) +}) + +test('how long a slide stays; the frame for a turned TV; what to keep on the device', () => { + assert.equal(slideMs({ kind: 'text', duration_s: 8 }), 8000) + assert.equal(slideMs({ kind: 'video', video_to_end: true, duration_s: 8 }), null) + assert.equal(slideMs({ kind: 'image' }), 10000) + assert.equal(frameStyle(90).width, '100vh') + assert.equal(frameStyle(0).width, '100vw') + assert.equal(frameStyle(180).transform, 'rotate(180deg)') + const data = { schedule: {}, playlists: { 1: { media: { 5: { url: '/a' } } }, 2: { media: { 6: { url: '/b' }, 5: { url: '/a' } } } } } + assert.deepEqual(mediaUrls(data).sort(), ['/a', '/b']) + assert.deepEqual(mediaUrls({ playlist: null }), []) +}) diff --git a/terminal/tests/terminal.test.mjs b/terminal/tests/terminal.test.mjs index 746da02..4fe614e 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 + menu tablet in phase 5)', () => { - assert.deepEqual(Object.keys(APPS).sort(), ['customer_display', 'kds', 'pos_counter']) +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']) assert.equal(typeof appLoader('kds'), 'function') - assert.equal(appLoader('signage'), null) + assert.equal(appLoader('menu_tablet'), null) assert.equal(appLoader('toString'), null) // never a prototype member }) diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index 69317f7..41b1949 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -27,6 +27,7 @@ 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], ['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], diff --git a/tests/e2e/signage.mjs b/tests/e2e/signage.mjs new file mode 100644 index 0000000..0e4496f --- /dev/null +++ b/tests/e2e/signage.mjs @@ -0,0 +1,154 @@ +// Signage suite (plan step 5.5a): a TV paired as a signage screen plays its playlist (picture, +// text, video to its end, menu board) in order with transitions, turns for a TV mounted sideways, +// keeps playing with the server stopped (a quiet mark, no banner), and catches up when it is back. +// Starts its own backend (:8065) and the terminal (:5193). +// node signage.mjs +import { execFileSync } from 'node:child_process' +import path from 'node:path' +import { chromium } from 'playwright' +import { BROWSER_CHANNEL, OUT, PYTHON, reporter, sleep, waitFor } from './lib/env.mjs' +import { startBackend, startTerminalVite } from './lib/proc.mjs' +import { supportLogin } from './lib/support.mjs' + +let backend = await startBackend({ port: 8065, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } }) +const dataDir = backend.dataDir +const term = await startTerminalVite({ port: 5193, backendUrl: backend.url }) +const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) +const r = reporter('signage: the player on a TV (5.5a)') +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 +} +async function upload(token, bytes, name, type) { + const form = new FormData() + form.append('file', new Blob([bytes], { type }), name) + const res = await fetch(`${backend.url}/api/media`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, body: form }) + return res.json() +} +const shown = (page, testId, timeout = 10_000) => page.getByTestId(testId).first().waitFor({ timeout }).then(() => true).catch(() => false) +const kindNow = page => page.getByTestId('signage-slide').getAttribute('data-kind', { timeout: 2000 }).catch(() => null) + +/** The kinds the screen shows over `ms`, in order, without repeats next to each other. */ +async function watch(page, ms) { + const seen = [] + const end = Date.now() + ms + while (Date.now() < end) { + const k = await kindNow(page) + if (k && seen[seen.length - 1] !== k) seen.push(k) + await sleep(200) + } + return seen +} + +try { + const boss = await supportLogin(backend.url) + await api('PUT', '/api/platform/modules/signage', { token: boss, body: { enabled: true } }).catch(() => {}) + + // a 2-second video recorded in the browser (WebM), a photo, a playlist of four slides + const rec = await browser.newPage() + const webm = Buffer.from(await rec.evaluate(async () => { + const c = document.createElement('canvas'); c.width = 320; c.height = 180 + const g = c.getContext('2d') + const rec = new MediaRecorder(c.captureStream(25), { mimeType: 'video/webm' }) + const parts = [] + rec.ondataavailable = e => parts.push(e.data) + rec.start() + const t0 = performance.now() + await new Promise(done => { + const draw = () => { + const s = (performance.now() - t0) / 2000 + g.fillStyle = `hsl(${Math.round(s * 360)},70%,50%)`; g.fillRect(0, 0, 320, 180) + if (s < 1) requestAnimationFrame(draw); else done() + } + draw() + }) + rec.stop() + await new Promise(r => { rec.onstop = r }) + const buf = await new Blob(parts, { type: 'video/webm' }).arrayBuffer() + return [...new Uint8Array(buf)] + })) + await rec.close() + const jpg = execFileSync(PYTHON, ['-c', "import io,sys;from PIL import Image;b=io.BytesIO();Image.new('RGB',(1920,1080),(200,40,40)).save(b,'JPEG');sys.stdout.buffer.write(b.getvalue())"]) + const photo = await upload(boss, jpg, 'promo.jpg', 'image/jpeg') + const video = await upload(boss, webm, 'clip.webm', 'video/webm') + r.check('setup: a photo and a video in the library', photo.kind === 'image' && video.kind === 'video', `${photo.kind} ${video.kind} ${JSON.stringify(video).slice(0, 120)}`) + const pl = await api('POST', '/api/signage/playlists', { token: boss, body: { name: 'Window', orientation: 'landscape' } }) + const add = body => api('POST', `/api/signage/playlists/${pl.id}/slides`, { token: boss, body }) + await add({ kind: 'image', duration_s: 3, content: { media_id: photo.id } }) + await add({ kind: 'text', duration_s: 3, transition: 'slide', content: { title: 'Happy hour', body: '17:00 - 19:00', background: { kind: 'colour', colour: '#1e3a8a' } } }) + await add({ kind: 'video', content: { media_id: video.id } }) + await add({ kind: 'menu', duration_s: 3, content: { title: 'Our menu', select: 'all', page_size: 12 } }) + + // ── the TV ──────────────────────────────────────────────────────────────── + const tv = await (await browser.newContext({ viewport: { width: 1280, height: 720 } })).newPage() + tv.on('pageerror', e => errors.push(e.message)) + await tv.goto(term.url) + await shown(tv, 'pairing-code', 20_000) + const code = await tv.getByTestId('pairing-code').getAttribute('data-code') + const dev = await api('POST', '/api/devices', { token: boss, body: { code, app_key: 'signage', name: 'Window TV' } }) + r.check('a TV paired as a signage screen opens the player (nothing to play yet)', await shown(tv, 'app-signage', 20_000) && await shown(tv, 'signage-empty', 5000)) + await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } }) + r.check('…its playlist starts at once (signage.changed)', await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300)) + const order = await watch(tv, 16_000) + const seq = order.join(' ') + r.check('the slides play in order: picture → text → video (to its end) → menu board → picture…', + /image text video menu/.test(seq) || /text video menu image/.test(seq) || /video menu image text/.test(seq) || /menu image text video/.test(seq), seq) + const img = await waitFor(async () => (await kindNow(tv)) === 'image' ? tv.getByTestId('signage-image').evaluate(i => i.naturalWidth) : null, 20_000, 200) + r.check('the picture shows (from the copy kept on the TV)', img > 0 && (await tv.getByTestId('signage-image').getAttribute('src')).startsWith('blob:'), String(img)) + await tv.screenshot({ path: path.join(OUT, 'signage-image.png') }) + await waitFor(async () => (await kindNow(tv)) === 'text', 20_000, 150) + r.check('the text slide comes in with its transition (slide)', (await tv.getByTestId('signage-slide').getAttribute('class')).includes('sg-in-slide') + && (await tv.getByTestId('signage-title').textContent()) === 'Happy hour') + await sleep(900) + await tv.screenshot({ path: path.join(OUT, 'signage-text.png') }) + await waitFor(async () => (await kindNow(tv)) === 'menu', 20_000, 150) + r.check('the menu board lists the products with prices', await tv.getByTestId('signage-menu-item').count() > 0 && await tv.getByTestId('signage-menu-price').count() > 0) + await tv.screenshot({ path: path.join(OUT, 'signage-menu.png') }) + + // ── a TV mounted sideways ───────────────────────────────────────────────── + await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { rotation: 90 } }) + r.check('turn the picture 90°: the frame turns', await waitFor(async () => (await tv.getByTestId('signage-frame').getAttribute('data-rotation')) === '90', 15_000, 300)) + await tv.screenshot({ path: path.join(OUT, 'signage-rotated.png') }) + await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { rotation: 0 } }) + await waitFor(async () => (await tv.getByTestId('signage-frame').getAttribute('data-rotation')) === '0', 15_000, 300) + + // ── the server stops: the TV keeps playing ──────────────────────────────── + await backend.stop() + const offlineOrder = await watch(tv, 14_000) + r.check('server stopped: the TV keeps playing its slides', new Set(offlineOrder).size >= 3, offlineOrder.join(' ')) + r.check('…with a small mark, never the banner over the slides', await shown(tv, 'offline-mark', 15_000) && await tv.getByTestId('offline-banner').count() === 0) + const offImg = await waitFor(async () => (await kindNow(tv)) === 'image' ? tv.getByTestId('signage-image').evaluate(i => i.complete && i.naturalWidth) : null, 20_000, 200) + r.check('…and the picture still shows', offImg > 0, String(offImg)) + + // ── back: it catches up ────────────────────────────────────────────────── + backend = await startBackend({ port: 8065, siteId: 'test-site-1', dataDir, env: { LICENSE_MODE: 'off' } }) + const boss2 = await supportLogin(backend.url) + await api('POST', `/api/signage/playlists/${pl.id}/slides`, { token: boss2, body: { kind: 'text', duration_s: 3, position: 0, content: { title: 'Back online' } } }) + const caught = await waitFor(async () => { + const titles = await tv.getByTestId('signage-title').allTextContents().catch(() => []) + return titles.includes('Back online') ? true : null + }, 60_000, 300) + r.check('server back: the TV catches up (a slide added meanwhile shows)', !!caught) + r.check('…and the mark goes away', await tv.getByTestId('offline-mark').waitFor({ state: 'detached', timeout: 20_000 }).then(() => true).catch(() => false)) + + r.check('no page errors', errors.length === 0, errors.join(' | ')) + failures += r.done() +} catch (e) { + console.error(e) + failures += 1 + r.done() +} finally { + await browser.close() + term.stop() + await backend.stop() +} +process.exit(failures ? 1 : 0)