diff --git a/docs/README.md b/docs/README.md index 6b2f086..f58e3c7 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. **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/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. 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/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 b65becc..006be86 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -482,6 +482,16 @@ }, "signage": { "nothing": "Καμία λίστα για αυτή την οθόνη (Προβολή στον διαχειριστή).", - "starting": "Εκκίνηση…" + "starting": "Εκκίνηση…", + "soldOut": "Εξαντλήθηκε", + "badges": { + "new": "Νέο", + "chef": "Πρόταση σεφ", + "offer": "Προσφορά", + "popular": "Δημοφιλές", + "spicy": "Καυτερό", + "vegetarian": "Χορτοφαγικό", + "vegan": "Vegan" + } } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index 1fb268d..4cbdaa2 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -482,6 +482,16 @@ }, "signage": { "nothing": "No playlist for this screen (Signage in the manager).", - "starting": "Starting…" + "starting": "Starting…", + "soldOut": "Sold out", + "badges": { + "new": "New", + "chef": "Chef's pick", + "offer": "Offer", + "popular": "Popular", + "spicy": "Spicy", + "vegetarian": "Vegetarian", + "vegan": "Vegan" + } } } diff --git a/terminal/src/apps/signage/SignageApp.jsx b/terminal/src/apps/signage/SignageApp.jsx index 1afccaa..1805d36 100644 --- a/terminal/src/apps/signage/SignageApp.jsx +++ b/terminal/src/apps/signage/SignageApp.jsx @@ -5,12 +5,12 @@ // 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. +// Menu boards page by themselves when they don't fit (5.5b); widgets sit in corners and bars. 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 { boardPages, frameStyle, localNow, mediaUrls, menuMs, nextSlide, pageAt, playlistNow, slideMs } from './logic' import { MenuSlide, TextSlide } from './Slides' const quiet = { xenia: { noOverride: true } } @@ -97,7 +97,7 @@ export default function SignageApp() { data-testid="app-signage" data-playlist={playlist?.id ?? ''} data-orientation={screen?.orientation ?? ''} data-offline={offline ? 'true' : 'false'}>
{playlist?.slides?.length - ? + ? : }
@@ -113,9 +113,21 @@ function Empty({ text }) { } /** Plays one playlist: the current slide, the next when its time is up, with the transition. */ -function Player({ playlist, kept, tz, venue, now }) { +function useWindowSize() { + const [size, setSize] = useState(() => ({ w: window.innerWidth, h: window.innerHeight })) + useEffect(() => { + const on = () => setSize({ w: window.innerWidth, h: window.innerHeight }) + window.addEventListener('resize', on) + return () => window.removeEventListener('resize', on) + }, []) + return size +} + +function Player({ playlist, kept, tz, venue, now, rotation }) { const local = localNow(tz, now) const slides = playlist.slides + const size = useWindowSize() + const pagesOf = useCallback(sl => (sl?.kind === 'menu' ? boardPages(sl, rotation, size.w, size.h) : null), [rotation, size]) const [cur, setCur] = useState(() => ({ index: nextSlide(slides, -1, local), at: Date.now(), n: 0 })) const [prev, setPrev] = useState(null) const media = id => { @@ -141,10 +153,10 @@ function Player({ playlist, kept, tz, venue, now }) { // 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 ms = slide.kind === 'menu' ? menuMs(slide, pagesOf(slide).length) : (slideMs(slide) ?? VIDEO_MAX_MS) const id = setTimeout(advance, ms) return () => clearTimeout(id) - }, [slide, cur.n, advance]) + }, [slide, cur.n, advance, pagesOf]) // 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() @@ -160,22 +172,24 @@ function Player({ playlist, kept, tz, venue, now }) { return ( <> {prev && slides[prev.index] && ( - + )} + className={cur.n === 0 ? '' : `sg-in sg-in-${transition}`} current + pages={pagesOf(slide)} page={pageAt(pagesOf(slide)?.length || 0, slide.content?.page_seconds, now.getTime() - cur.at)} /> ) } -function Layer({ slide, media, venue, now, onEnded, className, current = false }) { +function Layer({ slide, media, venue, now, onEnded, className, current = false, pages, page }) { return (
{slide.kind === 'image' && } {slide.kind === 'video' && } {slide.kind === 'text' && } - {slide.kind === 'menu' && } + {slide.kind === 'menu' && }
) } diff --git a/terminal/src/apps/signage/Slides.jsx b/terminal/src/apps/signage/Slides.jsx index e7a708c..901837d 100644 --- a/terminal/src/apps/signage/Slides.jsx +++ b/terminal/src/apps/signage/Slides.jsx @@ -1,9 +1,11 @@ -// 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' - +// Text and menu slides of the signage player, and their widgets (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 { Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Moon, Sun } from 'lucide-react' +import { QRCodeSVG } from 'qrcode.react' +import { useFormat, useTranslation } from '@xenia/i18n' +import { FONTS, weatherIcon } from './logic' /** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */ export function Background({ bg, media }) { @@ -17,50 +19,166 @@ export function Background({ bg, media }) { } const JUSTIFY = { top: 'flex-start', middle: 'center', bottom: 'flex-end' } +const hasBar = (c, where) => (c.widgets || []).some(w => w.position === where) -export function TextSlide({ content: c, media }) { +export function TextSlide({ content: c, media, venue, now }) { 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 }) { +/** A menu board (5.5b): its page of items (pages flip on their own), photos, descriptions, badges, sold out. */ +export function MenuSlide({ slide, media, venue, now, page, pages }) { + const { t } = useTranslation('terminal') const { formatMoney } = useFormat() const c = slide.content const scale = (c.text_size || 100) / 100 - const groups = slide.menu?.groups || [] + const accent = c.accent_colour || '#f59e0b' + const groups = pages[page] || [] return ( -
+
-
- {c.title &&

{c.title}

} -
+
+ {c.title &&

{c.title}

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

{g.category.name}

} +
+ {g.category && c.category_titles !== false && ( +

{g.category.name}

+ )} {g.items.map(it => ( -
- {it.name} - {it.price != null && {formatMoney(it.price)}} +
+ {c.show_photos && (it.image + ? + : )} +
+
+ {it.name} + {it.badge && ( + {t(`signage.badges.${it.badge}`)} + )} + {!it.available && {t('signage.soldOut')}} + + {it.price != null && {formatMoney(it.price)}} +
+ {it.description &&
{it.description}
} +
))}
))}
+ {pages.length > 1 && ( + + )}
+
) } + +// ── widgets (5.5b) ────────────────────────────────────────────────────────── + +const SIZE = { small: 0.75, medium: 1, large: 1.4 } +const CORNER = { + 'top-left': { top: '3vmin', left: '3vmin', alignItems: 'flex-start' }, + 'top-center': { top: '3vmin', left: '50%', transform: 'translateX(-50%)', alignItems: 'center' }, + 'top-right': { top: '3vmin', right: '3vmin', alignItems: 'flex-end' }, + 'bottom-left': { bottom: '3vmin', left: '3vmin', alignItems: 'flex-start' }, + 'bottom-center': { bottom: '3vmin', left: '50%', transform: 'translateX(-50%)', alignItems: 'center' }, + 'bottom-right': { bottom: '3vmin', right: '3vmin', alignItems: 'flex-end' }, +} + +/** The widgets of a slide, in their corners and bars. One that has nothing to show is left out. */ +export function Widgets({ widgets, media, venue, now, colour }) { + if (!widgets?.length) return null + const bar = where => widgets.filter(w => w.position === where) + const bars = [['top-bar', { top: 0 }], ['bottom-bar', { bottom: 0 }]] + return ( + <> + {bars.map(([where, pos]) => bar(where).length > 0 && ( +
+ {bar(where).map((w, i) => )} +
+ ))} + {widgets.filter(w => CORNER[w.position]).map((w, i) => ( +
+ +
+ ))} + + ) +} + +const ICONS = { sun: Sun, moon: Moon, 'cloud-sun': CloudSun, 'cloud-moon': CloudMoon, cloud: Cloud, fog: CloudFog, rain: CloudRain, snow: CloudSnow, storm: CloudLightning } + +function Widget({ w, media, venue, now }) { + const { formatDate, formatTime } = useFormat() + const s = SIZE[w.size] || 1 + const text = { fontSize: `${3.4 * s}vmin`, fontWeight: 700, lineHeight: 1.15, textShadow: '0 0.2vmin 0.8vmin rgba(0,0,0,0.35)' } + if (w.kind === 'logo') { + const m = media(w.media_id) + return m ? : null + } + if (w.kind === 'name') return venue?.name ? {venue.name} : null + if (w.kind === 'date') return {formatDate(now, w.date_style === 'short' ? 'date' : 'dateLong')} + if (w.kind === 'clock') return {formatTime(now, w.clock_seconds ? 'timeSeconds' : 'time')} + if (w.kind === 'message') { + const msg = w.text || venue?.message + return msg ? {msg} : null + } + if (w.kind === 'qr') { + return w.link ? ( +
+
+ +
+ {w.qr_caption && {w.qr_caption}} +
+ ) : null + } + if (w.kind === 'weather') { + const wx = venue?.weather + if (!wx || wx.temperature == null) return null // no internet / no place: hidden (5.4c) + const Icon = ICONS[weatherIcon(wx.code, wx.is_day)] || Cloud + const deg = wx.units === 'fahrenheit' ? '°F' : '°C' + return ( +
+
+ ) + } + return null +} diff --git a/terminal/src/apps/signage/logic.js b/terminal/src/apps/signage/logic.js index acc60ab..173108f 100644 --- a/terminal/src/apps/signage/logic.js +++ b/terminal/src/apps/signage/logic.js @@ -116,3 +116,87 @@ export const FONTS = { condensed: '"Arial Narrow", "Roboto Condensed", "Helvetica Neue", sans-serif', display: 'Impact, "Arial Black", system-ui, sans-serif', } + +// ── menu boards (5.5b) ─────────────────────────────────────────────────────── + +/** The frame's height in vmin (its shorter side is 100) for a screen w × h: 100 when wide, ~178 when tall (16:9). */ +export function frameHeightVmin(rotation, w = 16, h = 9) { + const turned = Number(rotation) === 90 || Number(rotation) === 270 + const frameTall = turned ? w > h : h > w // the screen's sides, swapped when the picture is turned + return frameTall ? (100 * Math.max(w, h)) / Math.min(w, h) : 100 +} + +/** + * How many rows fit in one column of a menu board: rows are items (taller with a photo or a + * description) and group headings. Sizes in vmin, as the board draws them. + */ +export function rowsPerColumn({ heightVmin = 100, textSize = 100, photos = false, descriptions = false, title = false, bars = 0 }) { + const s = (textSize || 100) / 100 + const row = (photos ? 8 : descriptions ? 7 : 4.8) * s + const used = 10 + (title ? 11 * s : 0) + bars * 9 // padding, the title, top / bottom bars of widgets + return Math.max(3, Math.floor((heightVmin - used) / row)) +} + +/** + * The board's pages: groups split into pages of at most `perPage` rows (a heading counts as a + * row; a group cut in two repeats its heading on the next page). → [[{category, items}], …] + */ +export function menuPages(groups, perPage, headings = true) { + const per = Math.max(1, perPage | 0) + const pages = [] + let page = [] + let used = 0 + const flush = () => { if (page.length) pages.push(page); page = []; used = 0 } + for (const g of groups || []) { + let items = [...(g.items || [])] + if (!items.length) continue + while (items.length) { + const head = headings && g.category ? 1 : 0 + if (used + head + 1 > per) flush() + const room = per - used - head + const take = items.slice(0, Math.max(1, room)) + page.push({ category: g.category, items: take }) + used += head + take.length + items = items.slice(take.length) + if (items.length) flush() + } + } + flush() + return pages +} + +/** A menu slide's time: every page for its seconds, at least the slide's own time. */ +export function menuMs(slide, pageCount) { + const per = Math.max(3, slide.content?.page_seconds || 10) * 1000 + return Math.max(slideMs(slide), pageCount > 1 ? pageCount * per : 0) +} + +/** The page on screen `elapsedMs` into the slide (the pages go round while the slide lasts). */ +export function pageAt(pageCount, pageSeconds, elapsedMs) { + if (pageCount <= 1 || !(elapsedMs > 0)) return 0 // the clock's last tick may be just before the slide began + return Math.floor(elapsedMs / (Math.max(3, pageSeconds || 10) * 1000)) % pageCount // round and round while the slide lasts +} + +/** A weather code (WMO, as Open-Meteo sends it) → an icon name for the widget. */ +export function weatherIcon(code, isDay = true) { + if (code == null) return 'cloud' + if (code === 0) return isDay ? 'sun' : 'moon' + if (code <= 2) return isDay ? 'cloud-sun' : 'cloud-moon' + if (code === 3) return 'cloud' + if (code === 45 || code === 48) return 'fog' + if ((code >= 51 && code <= 67) || (code >= 80 && code <= 82)) return 'rain' + if ((code >= 71 && code <= 77) || code === 85 || code === 86) return 'snow' + if (code >= 95) return 'storm' + return 'cloud' +} + +/** A menu slide's pages for this screen (w × h pixels, turned by `rotation`). */ +export function boardPages(slide, rotation, w, h) { + const c = slide.content || {} + const widgets = c.widgets || [] + const bars = ['top-bar', 'bottom-bar'].filter(p => widgets.some(x => x.position === p)).length + const rows = rowsPerColumn({ heightVmin: frameHeightVmin(rotation, w, h), textSize: c.text_size, photos: c.show_photos, + descriptions: c.show_descriptions, title: !!c.title, bars }) + const per = c.page_size || rows * (c.columns || 2) + return menuPages(slide.menu?.groups || [], per, c.category_titles !== false) +} diff --git a/terminal/tests/signage.test.mjs b/terminal/tests/signage.test.mjs index d43a2f4..5db67d3 100644 --- a/terminal/tests/signage.test.mjs +++ b/terminal/tests/signage.test.mjs @@ -2,7 +2,7 @@ // 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' +import { boardPages, frameHeightVmin, frameStyle, localNow, matches, mediaUrls, menuMs, menuPages, nextSlide, pageAt, pick, playlistNow, rowsPerColumn, slideMs, weatherIcon } from '../src/apps/signage/logic.js' const at = (date, hhmm) => { const d = new Date(`${date}T12:00:00Z`) @@ -73,3 +73,47 @@ test('how long a slide stays; the frame for a turned TV; what to keep on the dev assert.deepEqual(mediaUrls(data).sort(), ['/a', '/b']) assert.deepEqual(mediaUrls({ playlist: null }), []) }) + +test('a menu board in pages: headings count, a cut group repeats its heading', () => { + const g = [{ category: { id: 1, name: 'A' }, items: [1, 2, 3, 4, 5, 6, 7].map(id => ({ id })) }, { category: { id: 2, name: 'B' }, items: [{ id: 9 }] }] + const pages = menuPages(g, 4) + assert.deepEqual(pages.map(p => p.map(x => [x.category.name, x.items.length])), [[['A', 3]], [['A', 3]], [['A', 1], ['B', 1]]]) + assert.deepEqual(menuPages(g, 4, false).map(p => p.reduce((n, x) => n + x.items.length, 0)), [4, 4]) + assert.deepEqual(menuPages([], 4), []) + assert.equal(menuPages([{ category: null, items: [{ id: 1 }] }], 10).length, 1) +}) + +test('rows that fit: taller screens and smaller text fit more, photos fewer', () => { + assert.equal(frameHeightVmin(0, 1920, 1080), 100) + assert.ok(Math.abs(frameHeightVmin(0, 1080, 1920) - 177.8) < 0.1) + assert.ok(Math.abs(frameHeightVmin(90, 1920, 1080) - 177.8) < 0.1) // a wide TV turned: a tall frame + const base = rowsPerColumn({ heightVmin: 100 }) + assert.ok(rowsPerColumn({ heightVmin: 178 }) > base && rowsPerColumn({ heightVmin: 100, textSize: 70 }) > base) + assert.ok(rowsPerColumn({ heightVmin: 100, photos: true }) < base && rowsPerColumn({ heightVmin: 100, bars: 2 }) < base) + assert.ok(rowsPerColumn({ heightVmin: 10 }) >= 3) + const slide = { kind: 'menu', content: { columns: 1, page_size: 5 }, menu: { groups: [{ category: null, items: Array.from({ length: 12 }, (_, i) => ({ id: i })) }] } } + assert.equal(boardPages(slide, 0, 1920, 1080).length, 3) +}) + +test('a menu slide stays for all its pages; the page on screen', () => { + const slide = { kind: 'menu', duration_s: 10, content: { page_seconds: 8 } } + assert.equal(menuMs(slide, 1), 10_000) + assert.equal(menuMs(slide, 3), 24_000) + assert.equal(pageAt(3, 8, 0), 0) + assert.equal(pageAt(3, 8, 8_100), 1) + assert.equal(pageAt(3, 8, 16_500), 2) + assert.equal(pageAt(3, 8, 24_100), 0) // round again on a long slide + assert.equal(pageAt(1, 8, 99_000), 0) + assert.equal(pageAt(3, 8, -400), 0) +}) + +test('weather codes → icons', () => { + assert.equal(weatherIcon(0, true), 'sun') + assert.equal(weatherIcon(0, false), 'moon') + assert.equal(weatherIcon(2), 'cloud-sun') + assert.equal(weatherIcon(61), 'rain') + assert.equal(weatherIcon(73), 'snow') + assert.equal(weatherIcon(95), 'storm') + assert.equal(weatherIcon(45), 'fog') + assert.equal(weatherIcon(null), 'cloud') +}) diff --git a/tests/e2e/signage.mjs b/tests/e2e/signage.mjs index 0e4496f..a00b5ae 100644 --- a/tests/e2e/signage.mjs +++ b/tests/e2e/signage.mjs @@ -1,4 +1,4 @@ -// Signage suite (plan step 5.5a): a TV paired as a signage screen plays its playlist (picture, +// Signage suite (plan steps 5.5a, 5.5b): 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). @@ -14,7 +14,7 @@ let backend = await startBackend({ port: 8065, siteId: 'test-site-1', env: { LIC 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 r = reporter('signage: the player on a TV (5.5a), menu boards and widgets (5.5b)') const errors = [] let failures = 0 @@ -122,6 +122,61 @@ try { 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) + // ── 5.5b: a menu board that pages by itself, live prices, sold out, widgets ── + await api('PUT', '/api/signage/message', { token: boss, body: { text: 'Fresh fish today' } }) + const products = (await api('GET', '/api/products/?sold_at=in_store', { token: boss })).filter(p => !p.is_service_item && p.lifecycle_status === 'active') + const star = products[0] + const board = await api('POST', '/api/signage/playlists', { token: boss, body: { name: 'Menu board', orientation: 'landscape' } }) + await api('POST', `/api/signage/playlists/${board.id}/slides`, { token: boss, body: { kind: 'menu', duration_s: 60, content: { + title: 'Our menu', select: 'all', show_descriptions: true, page_seconds: 4, product_order: [star.id], group_by_category: false, columns: 1, + badges: { [String(star.id)]: 'chef' }, background: { kind: 'colour', colour: '#14213d' }, accent_colour: '#fca311', + widgets: [{ kind: 'name', position: 'top-left' }, { kind: 'clock', position: 'top-right' }, { kind: 'message', position: 'bottom-bar' }, + { kind: 'date', position: 'bottom-bar' }, { kind: 'weather', position: 'top-center' }] } } }) + await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: board.id } }) + await waitFor(async () => (await kindNow(tv)) === 'menu' && (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(board.id), 20_000, 300) + const pagesWide = Number(await tv.getByTestId('signage-menu').getAttribute('data-pages')) + const firstPage = await tv.getByTestId('signage-menu').getAttribute('data-page') + const flipped = await waitFor(async () => (await tv.getByTestId('signage-menu').getAttribute('data-page')) !== firstPage, 12_000, 300) + r.check(`5.5b: a long menu pages by itself (${pagesWide} pages on a wide TV)`, pagesWide > 1 && !!flipped, `${pagesWide} pages`) + r.check('5.5b: widgets in their places: the message of the day and the date in the bottom bar, the clock, the name', + (await tv.getByTestId('signage-bottom-bar').textContent()).includes('Fresh fish today') && await tv.getByTestId('signage-w-clock').count() === 1 + && await tv.getByTestId('signage-w-date').count() === 1) + r.check('5.5b: no weather place set → the weather widget is hidden', await tv.getByTestId('signage-w-weather').count() === 0) + await waitFor(async () => (await tv.getByTestId('signage-menu').getAttribute('data-page')) === '0', 20_000, 200) + r.check('5.5b: the chosen product first, with its badge', await tv.getByTestId('signage-menu-item').first().getAttribute('data-id') === String(star.id) + && (await tv.getByTestId('signage-menu-item').first().textContent()).includes("Chef's pick")) + await tv.screenshot({ path: path.join(OUT, 'signage-menu-board.png') }) + // a price change and a product going sold out show without a reload + await api('PUT', `/api/products/${star.id}`, { token: boss, body: { base_price: 9.9 } }) + const priced = await waitFor(async () => { + await waitFor(async () => (await tv.getByTestId('signage-menu').getAttribute('data-page')) === '0', 20_000, 200) + const t = await tv.locator(`[data-testid="signage-menu-item"][data-id="${star.id}"]`).textContent().catch(() => '') + return t.includes('9.90') ? t : null + }, 30_000, 500) + r.check('5.5b: a price change shows on the board within seconds', !!priced, priced || '') + await api('PUT', `/api/products/${star.id}`, { token: boss, body: { is_available: false } }) + const out = await waitFor(async () => { + await waitFor(async () => (await tv.getByTestId('signage-menu').getAttribute('data-page')) === '0', 20_000, 200) + return (await tv.locator(`[data-testid="signage-menu-item"][data-id="${star.id}"]`).getAttribute('data-available').catch(() => null)) === 'false' ? true : null + }, 30_000, 500) + r.check('5.5b: …and a product going sold out is crossed out', !!out && await tv.getByTestId('signage-sold-out').count() > 0) + await api('PUT', `/api/products/${star.id}`, { token: boss, body: { is_available: true } }) + // the same board on a portrait TV fits more on each page + const tall = await (await browser.newContext({ viewport: { width: 720, height: 1280 } })).newPage() + tall.on('pageerror', e => errors.push(e.message)) + await tall.goto(term.url) + await shown(tall, 'pairing-code', 20_000) + const code2 = await tall.getByTestId('pairing-code').getAttribute('data-code') + const dev2 = await api('POST', '/api/devices', { token: boss, body: { code: code2, app_key: 'signage', name: 'Tall TV' } }) + await api('PUT', `/api/signage/screens/${dev2.id}`, { token: boss, body: { playlist_id: board.id, orientation: 'portrait' } }) + await waitFor(async () => (await tall.getByTestId('signage-slide').getAttribute('data-kind').catch(() => null)) === 'menu', 20_000, 300) + const pagesTall = Number(await tall.getByTestId('signage-menu').getAttribute('data-pages')) + r.check('5.5b: on a portrait TV the same board needs fewer pages', pagesTall < pagesWide, `${pagesTall} < ${pagesWide}`) + await tall.screenshot({ path: path.join(OUT, 'signage-menu-portrait.png') }) + await tall.context().close() + await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } }) + await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300) + // ── the server stops: the TV keeps playing ──────────────────────────────── await backend.stop() const offlineOrder = await watch(tv, 14_000)