feat: call a waiter from a menu tablet at a table (platform-v2 step 5.7b)
- backend: menu tablet device config `table` (ref, validated against active
tables) and `call_waiter`; GET /api/menu-tablet/menu gives the table and
whether it can call; POST /api/menu-tablet/call sends a `table_call` staff
message ("Table 5: the guests call a waiter.", venue language) to the table's
waiters (its open order's, else the zone's), at most once a minute per tablet
(menu_tablet.call_too_soon with the seconds left; menu_tablet.no_table).
- terminal: "Call a waiter" only on a tablet at a table; "A waiter is on the
way to table 5", then a countdown before it can call again; a failed call
says to ask at the counter.
- waiter: the call shows with its own look and "Open the table".
- manager: tables as the choices of a device setting.
- tests: backend +2 (535 → 533 passed total), e2e menu_tablet.mjs +3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+1
-1
@@ -49,7 +49,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
|
|||||||
| `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory |
|
| `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory |
|
||||||
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` |
|
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` |
|
||||||
| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out |
|
| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out |
|
||||||
| `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage |
|
| `local_backend/routers/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. **Call a waiter (5.7b):** device config `table` (ref `tables`) + `call_waiter`; `POST /api/menu-tablet/call` sends a `table_call` staff message (the open order's waiters, else the zone's; `qr_orders.waiters_for`) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" |
|
||||||
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
|
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
|
||||||
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
|
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
|
||||||
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
||||||
|
|||||||
@@ -113,6 +113,8 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."),
|
"signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."),
|
||||||
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
|
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
|
||||||
"signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
|
"signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
|
||||||
|
"menu_tablet.no_table": (409, "This tablet isn't at a table, so it can't call a waiter."),
|
||||||
|
"menu_tablet.call_too_soon": (429, "A waiter was just called. Try again in {seconds} seconds."),
|
||||||
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
||||||
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
||||||
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
||||||
|
|||||||
@@ -97,5 +97,9 @@
|
|||||||
"qr": {
|
"qr": {
|
||||||
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
|
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
|
||||||
"sender": "QR μενού"
|
"sender": "QR μενού"
|
||||||
|
},
|
||||||
|
"tablet": {
|
||||||
|
"call_message": "Τραπεζι {table}: οι πελατες καλουν σερβιτορο.",
|
||||||
|
"sender": "Tablet μενου"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,5 +97,9 @@
|
|||||||
"qr": {
|
"qr": {
|
||||||
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
|
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
|
||||||
"sender": "QR menu"
|
"sender": "QR menu"
|
||||||
|
},
|
||||||
|
"tablet": {
|
||||||
|
"call_message": "Table {table}: the guests call a waiter.",
|
||||||
|
"sender": "Menu tablet"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,6 +55,10 @@ def _ref_exists(source: str, value: int, db) -> bool:
|
|||||||
if source == "signage_playlists":
|
if source == "signage_playlists":
|
||||||
from models.signage import SignagePlaylist
|
from models.signage import SignagePlaylist
|
||||||
return db.get(SignagePlaylist, value) is not None
|
return db.get(SignagePlaylist, value) is not None
|
||||||
|
if source == "tables":
|
||||||
|
from models.table import Table
|
||||||
|
t = db.get(Table, value)
|
||||||
|
return t is not None and bool(t.is_active)
|
||||||
if source == "signage_schedules":
|
if source == "signage_schedules":
|
||||||
from models.signage import SignageSchedule
|
from models.signage import SignageSchedule
|
||||||
return db.get(SignageSchedule, value) is not None
|
return db.get(SignageSchedule, value) is not None
|
||||||
|
|||||||
@@ -31,5 +31,8 @@ MODULE = Module(
|
|||||||
ConfigField('search', 'bool', default=True, group='use'),
|
ConfigField('search', 'bool', default=True, group='use'),
|
||||||
ConfigField('languages', 'enum', default='both', choices=('both', 'el', 'en'), group='use'),
|
ConfigField('languages', 'enum', default='both', choices=('both', 'el', 'en'), group='use'),
|
||||||
ConfigField('idle_seconds', 'int', default=120, choices=(0, 30, 60, 120, 300, 600), group='use'),
|
ConfigField('idle_seconds', 'int', default=120, choices=(0, 30, 60, 120, 300, 600), group='use'),
|
||||||
|
# A tablet on a table (5.7b): only then guests can call a waiter
|
||||||
|
ConfigField('table', 'ref', default=None, choices_from='tables', group='table'),
|
||||||
|
ConfigField('call_waiter', 'bool', default=True, group='table'),
|
||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ products and their categories: no ordering, no tables, no sign-in.
|
|||||||
of the tablet's sales point and whether it is available; the
|
of the tablet's sales point and whether it is available; the
|
||||||
tablet's settings (device config) and the venue's name.
|
tablet's settings (device config) and the venue's name.
|
||||||
|
|
||||||
|
POST /api/menu-tablet/call (a tablet set at a table, 5.7b) call a waiter: a message to the
|
||||||
|
table's waiters (its order's, else the zone's), once a minute at most.
|
||||||
|
|
||||||
How it looks is the tablet's device config (modules/menu_tablet/manifest.py): view, photos,
|
How it looks is the tablet's device config (modules/menu_tablet/manifest.py): view, photos,
|
||||||
descriptions, grouping, whose prices, sold-out style, search, one category or all, languages,
|
descriptions, grouping, whose prices, sold-out style, search, one category or all, languages,
|
||||||
idle reset, light / dark. Any menu change sends `menu_tablet.changed` to every tablet (main.py).
|
idle reset, light / dark. Any menu change sends `menu_tablet.changed` to every tablet (main.py).
|
||||||
@@ -17,14 +20,21 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from core import sales_points
|
from core import sales_points
|
||||||
from core.access.deps import require_device
|
from core.access.deps import require_device
|
||||||
|
from core.errors import XeniaError
|
||||||
from database import get_db
|
from database import get_db
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
CALL_EVERY_S = 60
|
||||||
|
_calls: dict[int, float] = {} # tablet id → its last call (monotonic)
|
||||||
|
_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
def _config(dev) -> dict:
|
def _config(dev) -> dict:
|
||||||
@@ -107,11 +117,67 @@ def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"
|
|||||||
shown = [by_id[i] for i in by_id if i in used]
|
shown = [by_id[i] for i in by_id if i in used]
|
||||||
prices = dict(zip([p.id for p in shown], unit_prices(db, shown, point))) if point and shown else {}
|
prices = dict(zip([p.id for p in shown], unit_prices(db, shown, point))) if point and shown else {}
|
||||||
name_row = db.query(PosSettings).filter(PosSettings.key == "venue.name").first()
|
name_row = db.query(PosSettings).filter(PosSettings.key == "venue.name").first()
|
||||||
|
table = _table(db, cfg)
|
||||||
return {
|
return {
|
||||||
"venue": {"name": (name_row.value if name_row else "") or None},
|
"venue": {"name": (name_row.value if name_row else "") or None},
|
||||||
|
"table": {"id": table.id, "name": _label(table), "can_call": bool(cfg.get("call_waiter"))} if table else None,
|
||||||
"config": cfg,
|
"config": cfg,
|
||||||
"categories": out_cats,
|
"categories": out_cats,
|
||||||
"products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p),
|
"products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p),
|
||||||
"price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available),
|
"price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available),
|
||||||
"image": media_store.image_of(p.media)} for p in shown},
|
"image": media_store.image_of(p.media)} for p in shown},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── calling a waiter from a tablet at a table (5.7b) ──────────────────────────
|
||||||
|
|
||||||
|
def _table(db, cfg):
|
||||||
|
from models.table import Table
|
||||||
|
t = db.get(Table, cfg["table"]) if cfg.get("table") else None
|
||||||
|
return t if t is not None and t.is_active else None
|
||||||
|
|
||||||
|
|
||||||
|
def _label(table) -> str:
|
||||||
|
from services.table_qr import label
|
||||||
|
return label(table)
|
||||||
|
|
||||||
|
|
||||||
|
def _waiters(db, table) -> list[int]:
|
||||||
|
"""The table's waiters: its open order's, else the waiters whose zone covers the table."""
|
||||||
|
from models.order import Order
|
||||||
|
from services.qr_orders import waiters_for
|
||||||
|
order = db.query(Order).filter(Order.table_id == table.id, Order.status.in_(("open", "partially_paid", "paid"))).first()
|
||||||
|
|
||||||
|
class _NoOrder:
|
||||||
|
waiters = []
|
||||||
|
return waiters_for(db, order or _NoOrder(), table)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/call")
|
||||||
|
def call_waiter(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
||||||
|
"""A guest at the table asks for a waiter. The message reaches the table's waiters' phones."""
|
||||||
|
from core.access.queries import holders_filter
|
||||||
|
from core.i18n import t, venue_language
|
||||||
|
from models.user import User
|
||||||
|
from routers.kds import _save_and_broadcast_message
|
||||||
|
cfg = _config(dev)
|
||||||
|
table = _table(db, cfg)
|
||||||
|
if table is None or not cfg.get("call_waiter"):
|
||||||
|
raise XeniaError("menu_tablet.no_table")
|
||||||
|
now = time.monotonic()
|
||||||
|
with _lock:
|
||||||
|
last = _calls.get(dev.id)
|
||||||
|
if last is not None and now - last < CALL_EVERY_S:
|
||||||
|
raise XeniaError("menu_tablet.call_too_soon", seconds=int(CALL_EVERY_S - (now - last)) + 1)
|
||||||
|
_calls[dev.id] = now
|
||||||
|
sender = db.query(User).filter(holders_filter("core.dashboard.access")).first()
|
||||||
|
lang = venue_language()
|
||||||
|
waiters = _waiters(db, table)
|
||||||
|
_save_and_broadcast_message(db, sender.id if sender else 1, t("tablet.call_message", lang, table=_label(table)), waiters,
|
||||||
|
"table_call", t("tablet.sender", lang), table_ids=[table.id])
|
||||||
|
return {"table": {"id": table.id, "name": _label(table)}, "waiters": len(waiters), "again_in": CALL_EVERY_S}
|
||||||
|
|
||||||
|
|
||||||
|
def reset_calls() -> None:
|
||||||
|
with _lock:
|
||||||
|
_calls.clear()
|
||||||
|
|||||||
@@ -86,3 +86,66 @@ def test_only_menu_tablets(client, pair):
|
|||||||
token, _ = pair("kds", "Kitchen")
|
token, _ = pair("kds", "Kitchen")
|
||||||
assert err(client.get("/api/menu-tablet/menu", headers={"X-Xenia-Device": token})) == "device.out_of_scope"
|
assert err(client.get("/api/menu-tablet/menu", headers={"X-Xenia-Device": token})) == "device.out_of_scope"
|
||||||
assert err(client.get("/api/menu-tablet/menu")) == "device.not_paired"
|
assert err(client.get("/api/menu-tablet/menu")) == "device.not_paired"
|
||||||
|
|
||||||
|
|
||||||
|
# ── 5.7b: calling a waiter from a tablet at a table ─────────────────────────
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def table(db):
|
||||||
|
from models.table import Table
|
||||||
|
t = Table(number=5, is_active=True)
|
||||||
|
db.add(t)
|
||||||
|
db.commit()
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _calls():
|
||||||
|
import routers.menu_tablet as mt
|
||||||
|
mt.reset_calls()
|
||||||
|
yield
|
||||||
|
mt.reset_calls()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_tablet_at_a_table_calls_a_waiter(client, owner_h, tablet, menu, table, make_user, db, monkeypatch):
|
||||||
|
"""Done when (5.7b): a tablet set to table 5 calls a waiter and the waiter gets the message."""
|
||||||
|
import routers.kds as kds
|
||||||
|
from models.user import WaiterZone
|
||||||
|
maria = make_user(role="waiter")
|
||||||
|
db.add(WaiterZone(waiter_id=maria.id, group_id=None))
|
||||||
|
db.commit()
|
||||||
|
got = []
|
||||||
|
monkeypatch.setattr(kds, "broadcast_sync", lambda kind, data, **kw: got.append((kind, data, kw)), raising=False)
|
||||||
|
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["table"] is None
|
||||||
|
assert err(client.post("/api/menu-tablet/call", headers=tablet["h"])) == "menu_tablet.no_table"
|
||||||
|
client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": table.id}})
|
||||||
|
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["table"] == {"id": table.id, "name": "5", "can_call": True}
|
||||||
|
r = client.post("/api/menu-tablet/call", headers=tablet["h"])
|
||||||
|
assert r.status_code == 200 and r.json()["waiters"] >= 1 and r.json()["again_in"] == 60
|
||||||
|
from models.message import StaffMessage
|
||||||
|
msg = db.query(StaffMessage).order_by(StaffMessage.id.desc()).first()
|
||||||
|
assert msg.message_type == "table_call" and msg.body == "Table 5: the guests call a waiter." and str(maria.id) in msg.target_waiter_ids
|
||||||
|
assert str(table.id) in msg.table_ids
|
||||||
|
# once a minute at most
|
||||||
|
again = client.post("/api/menu-tablet/call", headers=tablet["h"])
|
||||||
|
assert again.status_code == 429 and err(again) == "menu_tablet.call_too_soon" and again.json()["error"]["params"]["seconds"] <= 60
|
||||||
|
# the option off: no calls, the menu says so
|
||||||
|
client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": table.id, "call_waiter": False}})
|
||||||
|
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["table"]["can_call"] is False
|
||||||
|
assert err(client.post("/api/menu-tablet/call", headers=tablet["h"])) == "menu_tablet.no_table"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_tables_open_order_decides_who_hears_it(client, owner_h, tablet, table, make_user, db):
|
||||||
|
from models.order import Order, OrderWaiter
|
||||||
|
from models.message import StaffMessage
|
||||||
|
nikos, eleni = make_user(role="waiter"), make_user(role="waiter")
|
||||||
|
order = Order(table_id=table.id, opened_by=nikos.id, status="open", order_type="dine_in")
|
||||||
|
db.add(order)
|
||||||
|
db.flush()
|
||||||
|
db.add(OrderWaiter(order_id=order.id, waiter_id=nikos.id))
|
||||||
|
db.commit()
|
||||||
|
client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": table.id}})
|
||||||
|
assert client.post("/api/menu-tablet/call", headers=tablet["h"]).status_code == 200
|
||||||
|
msg = db.query(StaffMessage).order_by(StaffMessage.id.desc()).first()
|
||||||
|
assert msg.target_waiter_ids == f"[{nikos.id}]" and eleni.id
|
||||||
|
assert err(client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": 99999}})) == "validation.device_config"
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import client from '../../api/client'
|
|||||||
import { configGroups, configValue, refOptions } from './devicesLogic'
|
import { configGroups, configValue, refOptions } from './devicesLogic'
|
||||||
|
|
||||||
// Where a `ref` field's choices come from (the device list is passed in)
|
// Where a `ref` field's choices come from (the device list is passed in)
|
||||||
const REF_URLS = { prep_zones: '/api/prep-zones', categories: '/api/products/categories', printers: '/api/system/printers', display_looks: '/api/display/looks', signage_playlists: '/api/signage/playlists', signage_schedules: '/api/signage/schedules' }
|
const REF_URLS = { prep_zones: '/api/prep-zones', categories: '/api/products/categories', printers: '/api/system/printers', display_looks: '/api/display/looks', signage_playlists: '/api/signage/playlists', signage_schedules: '/api/signage/schedules', tables: '/api/tables/' }
|
||||||
|
|
||||||
export default function DeviceConfigFields({ appKey, fields = [], value, onChange, devices = [], selfId = null }) {
|
export default function DeviceConfigFields({ appKey, fields = [], value, onChange, devices = [], selfId = null }) {
|
||||||
const { t } = useTranslation('manager')
|
const { t } = useTranslation('manager')
|
||||||
@@ -31,6 +31,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
|
|||||||
const looks = lists.display_looks ?? []
|
const looks = lists.display_looks ?? []
|
||||||
const playlists = lists.signage_playlists ?? []
|
const playlists = lists.signage_playlists ?? []
|
||||||
const schedules = lists.signage_schedules ?? []
|
const schedules = lists.signage_schedules ?? []
|
||||||
|
const tables = lists.tables ?? []
|
||||||
|
|
||||||
if (!fields.length) return null
|
if (!fields.length) return null
|
||||||
const base = key => `modules:${appKey}.config.${key}`
|
const base = key => `modules:${appKey}.config.${key}`
|
||||||
@@ -56,7 +57,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
|
|||||||
<Field key={f.key} label={label} hint={hint}>
|
<Field key={f.key} label={label} hint={hint}>
|
||||||
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
|
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
|
||||||
options={[{ value: '', label: t(`${base(f.key)}.none`, { defaultValue: t('devices.form.none') }) },
|
options={[{ value: '', label: t(`${base(f.key)}.none`, { defaultValue: t('devices.form.none') }) },
|
||||||
...refOptions(f, { zones, categories, printers, looks, playlists, schedules, devices, selfId })]} />
|
...refOptions(f, { zones, categories, printers, looks, playlists, schedules, tables, devices, selfId })]} />
|
||||||
</Field>
|
</Field>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,7 +86,8 @@ export function configGroups(fields = []) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Options of a `ref` field: prep zones, categories, printers, customer display looks, or live devices of one app ("devices:<app>"). */
|
/** Options of a `ref` field: prep zones, categories, printers, customer display looks, or live devices of one app ("devices:<app>"). */
|
||||||
export function refOptions(field, { zones = [], categories = [], printers = [], looks = [], playlists = [], schedules = [], devices = [], selfId = null } = {}) {
|
export function refOptions(field, { zones = [], categories = [], printers = [], looks = [], playlists = [], schedules = [], tables = [], devices = [], selfId = null } = {}) {
|
||||||
|
if (field.choices_from === 'tables') return tables.filter(x => x.is_active !== false).map(x => ({ value: String(x.id), label: x.label || String(x.number) }))
|
||||||
if (field.choices_from === 'signage_schedules') return schedules.map(s => ({ value: String(s.id), label: s.name }))
|
if (field.choices_from === 'signage_schedules') return schedules.map(s => ({ value: String(s.id), label: s.name }))
|
||||||
if (field.choices_from === 'signage_playlists') return playlists.map(p => ({ value: String(p.id), label: p.name }))
|
if (field.choices_from === 'signage_playlists') return playlists.map(p => ({ value: String(p.id), label: p.name }))
|
||||||
if (field.choices_from === 'display_looks') return looks.map(l => ({ value: String(l.id), label: l.name }))
|
if (field.choices_from === 'display_looks') return looks.map(l => ({ value: String(l.id), label: l.name }))
|
||||||
|
|||||||
@@ -149,5 +149,9 @@
|
|||||||
"order_mismatch": "Η λίστα άλλαξε στο μεταξύ. Φορτώστε τη ξανά και δοκιμάστε πάλι.",
|
"order_mismatch": "Η λίστα άλλαξε στο μεταξύ. Φορτώστε τη ξανά και δοκιμάστε πάλι.",
|
||||||
"weather_offline": "Η υπηρεσία καιρού δεν είναι διαθέσιμη: ο διακομιστής του καταστήματος χρειάζεται internet γι' αυτήν.",
|
"weather_offline": "Η υπηρεσία καιρού δεν είναι διαθέσιμη: ο διακομιστής του καταστήματος χρειάζεται internet γι' αυτήν.",
|
||||||
"schedule_unknown": "Το πρόγραμμα {{schedule_id}} δεν βρέθηκε."
|
"schedule_unknown": "Το πρόγραμμα {{schedule_id}} δεν βρέθηκε."
|
||||||
|
},
|
||||||
|
"menu_tablet": {
|
||||||
|
"no_table": "Αυτό το tablet δεν είναι σε τραπέζι, οπότε δεν καλεί σερβιτόρο.",
|
||||||
|
"call_too_soon": "Μόλις κλήθηκε σερβιτόρος. Δοκιμάστε ξανά σε {{seconds}} δευτερόλεπτα."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -282,7 +282,8 @@
|
|||||||
"config_groups": {
|
"config_groups": {
|
||||||
"look": "Εμφάνιση",
|
"look": "Εμφάνιση",
|
||||||
"menu": "Μενού",
|
"menu": "Μενού",
|
||||||
"use": "Χρήση"
|
"use": "Χρήση",
|
||||||
|
"table": "Σε τραπέζι"
|
||||||
},
|
},
|
||||||
"config": {
|
"config": {
|
||||||
"view": {
|
"view": {
|
||||||
@@ -360,6 +361,15 @@
|
|||||||
"300": "5 λεπτά",
|
"300": "5 λεπτά",
|
||||||
"600": "10 λεπτά"
|
"600": "10 λεπτά"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"table": {
|
||||||
|
"label": "Τραπέζι",
|
||||||
|
"hint": "Το τραπέζι όπου βρίσκεται το tablet. Μόνο τότε οι πελάτες καλούν σερβιτόρο.",
|
||||||
|
"none": "Όχι σε τραπέζι"
|
||||||
|
},
|
||||||
|
"call_waiter": {
|
||||||
|
"label": "Οι πελάτες καλούν σερβιτόρο",
|
||||||
|
"hint": "Κουμπί που στέλνει μήνυμα στους σερβιτόρους του τραπεζιού (το πολύ μία φορά το λεπτό)."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -503,6 +503,10 @@
|
|||||||
"noResults": "Δεν βρέθηκε τίποτα για «{{q}}».",
|
"noResults": "Δεν βρέθηκε τίποτα για «{{q}}».",
|
||||||
"empty": "Το μενού είναι άδειο.",
|
"empty": "Το μενού είναι άδειο.",
|
||||||
"soldOut": "Εξαντλήθηκε",
|
"soldOut": "Εξαντλήθηκε",
|
||||||
"close": "Κλείσιμο"
|
"close": "Κλείσιμο",
|
||||||
|
"call": "Κλήση σερβιτόρου",
|
||||||
|
"called": "Ένας σερβιτόρος έρχεται στο τραπέζι {{table}}.",
|
||||||
|
"callAgainIn": "Ξανά σε {{seconds}} δ",
|
||||||
|
"callFailed": "Η κλήση δεν έφτασε: παρακαλούμε ρωτήστε στο ταμείο."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -149,5 +149,9 @@
|
|||||||
"order_mismatch": "The playlist changed in the meantime. Reload it and try again.",
|
"order_mismatch": "The playlist changed in the meantime. Reload it and try again.",
|
||||||
"weather_offline": "The weather service can't be reached: the venue's server needs internet for it.",
|
"weather_offline": "The weather service can't be reached: the venue's server needs internet for it.",
|
||||||
"schedule_unknown": "Schedule {{schedule_id}} not found."
|
"schedule_unknown": "Schedule {{schedule_id}} not found."
|
||||||
|
},
|
||||||
|
"menu_tablet": {
|
||||||
|
"no_table": "This tablet isn't at a table, so it can't call a waiter.",
|
||||||
|
"call_too_soon": "A waiter was just called. Try again in {{seconds}} seconds."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -282,7 +282,8 @@
|
|||||||
"config_groups": {
|
"config_groups": {
|
||||||
"look": "Look",
|
"look": "Look",
|
||||||
"menu": "Menu",
|
"menu": "Menu",
|
||||||
"use": "Use"
|
"use": "Use",
|
||||||
|
"table": "At a table"
|
||||||
},
|
},
|
||||||
"config": {
|
"config": {
|
||||||
"view": {
|
"view": {
|
||||||
@@ -360,6 +361,15 @@
|
|||||||
"300": "5 min",
|
"300": "5 min",
|
||||||
"600": "10 min"
|
"600": "10 min"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"table": {
|
||||||
|
"label": "Table",
|
||||||
|
"hint": "The table this tablet sits on. Only then guests can call a waiter.",
|
||||||
|
"none": "Not at a table"
|
||||||
|
},
|
||||||
|
"call_waiter": {
|
||||||
|
"label": "Guests can call a waiter",
|
||||||
|
"hint": "A button that sends a message to the table's waiters (once a minute at most)."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -503,6 +503,10 @@
|
|||||||
"noResults": "Nothing found for \"{{q}}\".",
|
"noResults": "Nothing found for \"{{q}}\".",
|
||||||
"empty": "The menu is empty.",
|
"empty": "The menu is empty.",
|
||||||
"soldOut": "Sold out",
|
"soldOut": "Sold out",
|
||||||
"close": "Close"
|
"close": "Close",
|
||||||
|
"call": "Call a waiter",
|
||||||
|
"called": "A waiter is on the way to table {{table}}.",
|
||||||
|
"callAgainIn": "Again in {{seconds}} s",
|
||||||
|
"callFailed": "The call didn't go through: please ask at the counter."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,9 @@
|
|||||||
// compact / expanded / full view, photos, descriptions, grouped or one A–Z list, whose prices,
|
// 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 /
|
// 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`).
|
// dark. Keeps the last menu for offline; a menu change arrives live (`menu_tablet.changed`).
|
||||||
|
// A tablet set at a table (5.7b) can call the table's waiters (once a minute at most).
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { Search, X } from 'lucide-react'
|
import { BellRing, Search, X } from 'lucide-react'
|
||||||
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
|
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
|
||||||
import { applyTheme, Dialog, getStoredTheme, Input } from '@xenia/ui'
|
import { applyTheme, Dialog, getStoredTheme, Input } from '@xenia/ui'
|
||||||
import client from '../../api/client'
|
import client from '../../api/client'
|
||||||
@@ -90,6 +91,7 @@ export default function MenuTabletApp() {
|
|||||||
{q && <button type="button" onClick={() => setQ('')} aria-label={t('menuTablet.clear')} className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-ink-3"><X size={16} /></button>}
|
{q && <button type="button" onClick={() => setQ('')} aria-label={t('menuTablet.clear')} className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-ink-3"><X size={16} /></button>}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{data.table?.can_call && <CallWaiter table={data.table} />}
|
||||||
{langs.length > 1 && (
|
{langs.length > 1 && (
|
||||||
<div className="flex rounded-control border border-line overflow-hidden" role="group" aria-label={t('menuTablet.language')}>
|
<div className="flex rounded-control border border-line overflow-hidden" role="group" aria-label={t('menuTablet.language')}>
|
||||||
{langs.map(l => (
|
{langs.map(l => (
|
||||||
@@ -207,3 +209,41 @@ function Details({ product: p, cfg, onClose }) {
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** "Call a waiter" (5.7b): a message to the table's waiters; then it waits before it can call again. */
|
||||||
|
function CallWaiter({ table }) {
|
||||||
|
const { t } = useTranslation('terminal')
|
||||||
|
const [state, setState] = useState({ status: 'idle', until: 0 })
|
||||||
|
const [left, setLeft] = useState(0) // seconds until it can call again
|
||||||
|
useEffect(() => {
|
||||||
|
if (state.status === 'idle') return undefined
|
||||||
|
const id = setInterval(() => {
|
||||||
|
const s = Math.max(0, Math.ceil((state.until - Date.now()) / 1000))
|
||||||
|
setLeft(s)
|
||||||
|
if (s === 0) setState({ status: 'idle', until: 0 })
|
||||||
|
}, 1000)
|
||||||
|
return () => clearInterval(id)
|
||||||
|
}, [state])
|
||||||
|
const call = async () => {
|
||||||
|
try {
|
||||||
|
const { data } = await client.post('/api/menu-tablet/call', {}, quiet)
|
||||||
|
setLeft(data.again_in)
|
||||||
|
setState({ status: 'sent', until: Date.now() + data.again_in * 1000 })
|
||||||
|
} catch (err) {
|
||||||
|
const x = err?.xenia
|
||||||
|
if (x?.code === 'menu_tablet.call_too_soon') { setLeft(x.params?.seconds || 30); setState({ status: 'sent', until: Date.now() + (x.params?.seconds || 30) * 1000 }) }
|
||||||
|
else setState({ status: 'failed', until: Date.now() + 8000 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2" data-testid="menu-call" data-status={state.status}>
|
||||||
|
{state.status === 'sent' && <span className="text-label text-success-ink" role="status" data-testid="menu-call-sent">{t('menuTablet.called', { table: table.name })}</span>}
|
||||||
|
{state.status === 'failed' && <span className="text-label text-danger-ink" role="status" data-testid="menu-call-failed">{t('menuTablet.callFailed')}</span>}
|
||||||
|
<button type="button" onClick={call} disabled={state.status === 'sent'} data-testid="menu-call-button"
|
||||||
|
className="flex items-center gap-2 px-4 py-2 rounded-control bg-accent text-accent-fg text-label font-semibold disabled:opacity-50 whitespace-nowrap">
|
||||||
|
<BellRing size={18} aria-hidden="true" />
|
||||||
|
{state.status === 'sent' ? t('menuTablet.callAgainIn', { seconds: left }) : t('menuTablet.call')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
// Menu tablet suite (plan step 5.7a): a tablet paired as a menu tablet shows the venue's menu with
|
// 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;
|
// 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 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.
|
// the guest's language; back to the start after a while without a touch; a tablet at a table calls
|
||||||
|
// a waiter (5.7b).
|
||||||
// Starts its own backend (:8067) and the terminal (:5195).
|
// Starts its own backend (:8067) and the terminal (:5195).
|
||||||
// node menu_tablet.mjs
|
// node menu_tablet.mjs
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
@@ -13,7 +14,7 @@ import { supportLogin } from './lib/support.mjs'
|
|||||||
const backend = await startBackend({ port: 8067, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } })
|
const backend = await startBackend({ port: 8067, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } })
|
||||||
const term = await startTerminalVite({ port: 5195, backendUrl: backend.url })
|
const term = await startTerminalVite({ port: 5195, backendUrl: backend.url })
|
||||||
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
|
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 r = reporter('menu tablet: the menu, search, views, live prices, languages, idle reset (5.7a), call a waiter (5.7b)')
|
||||||
const errors = []
|
const errors = []
|
||||||
let failures = 0
|
let failures = 0
|
||||||
|
|
||||||
@@ -75,6 +76,18 @@ try {
|
|||||||
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)
|
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)
|
r.check('a price change shows on the tablet without a reload', !!live)
|
||||||
|
|
||||||
|
// 5.7b: a tablet at a table calls a waiter; one without a table has no button
|
||||||
|
r.check('5.7b: a tablet not at a table has no "Call a waiter" button', await tab.getByTestId('menu-call-button').count() === 0)
|
||||||
|
const tables = await api('GET', '/api/tables/', { token: boss })
|
||||||
|
const t5 = tables.find(x => x.is_active !== false) || tables[0]
|
||||||
|
await api('PATCH', `/api/devices/${dev.id}`, { token: boss, body: { config: { table: t5.id } } })
|
||||||
|
r.check('5.7b: set at a table, it gets the button', await shown(tab, 'menu-call-button', 15_000))
|
||||||
|
await tab.getByTestId('menu-call-button').click()
|
||||||
|
r.check('5.7b: calling says a waiter is on the way, and waits before it can call again',
|
||||||
|
await shown(tab, 'menu-call-sent', 5000) && await tab.getByTestId('menu-call-button').isDisabled()
|
||||||
|
&& (await tab.getByTestId('menu-call-sent').textContent()).includes(t5.label || String(t5.number)))
|
||||||
|
await tab.screenshot({ path: path.join(OUT, 'menu-tablet-call.png') })
|
||||||
|
|
||||||
// the guest's language, then back to the start after a while
|
// the guest's language, then back to the start after a while
|
||||||
await tab.getByTestId('menu-lang-en').click()
|
await tab.getByTestId('menu-lang-en').click()
|
||||||
const enPlaceholder = await tab.getByTestId('menu-search').getAttribute('placeholder')
|
const enPlaceholder = await tab.getByTestId('menu-search').getAttribute('placeholder')
|
||||||
|
|||||||
@@ -39,6 +39,11 @@ const TYPE_THEME = {
|
|||||||
bg: 'var(--x-info-fg)', border: 'var(--x-info)', ackBg: 'var(--x-info)',
|
bg: 'var(--x-info-fg)', border: 'var(--x-info)', ackBg: 'var(--x-info)',
|
||||||
labelColor: 'var(--x-info-ink)', icon: '📱',
|
labelColor: 'var(--x-info-ink)', icon: '📱',
|
||||||
},
|
},
|
||||||
|
// the guests at a table called a waiter from the menu tablet on it (plan step 5.7b)
|
||||||
|
table_call: {
|
||||||
|
bg: 'var(--x-warning-fg)', border: 'var(--x-warning)', ackBg: 'var(--x-warning)',
|
||||||
|
labelColor: 'var(--x-warning-ink)', icon: '🙋',
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
function getTheme(messageType) {
|
function getTheme(messageType) {
|
||||||
@@ -132,7 +137,7 @@ function NotificationBanner({ message, onAck, autoDismiss }) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{message.message_type === 'qr_order' && tableIds.length > 0 && (
|
{(message.message_type === 'qr_order' || message.message_type === 'table_call') && tableIds.length > 0 && (
|
||||||
<button
|
<button
|
||||||
data-testid="notify-open-table"
|
data-testid="notify-open-table"
|
||||||
onClick={() => { onAck(message.id); navigate(`/tables/${tableIds[0]}`) }}
|
onClick={() => { onAck(message.id); navigate(`/tables/${tableIds[0]}`) }}
|
||||||
|
|||||||
Reference in New Issue
Block a user