feat: ordering from the menu tablet at a table (platform-v2 step 6.6, D-30)
- tablet_orders (0034) + services/tablet_orders.py: venue rules (menu_tablet.ordering) with
per-tablet overrides: kitchen or waiter confirms first, no open order open/refuse, limits
(items per order, of one dish, time between orders)
- /api/menu-tablet: quote, order, order/{id}, bill (see + ask), requests accept/decline, ordering
- terminal: Add to the order (POS ProductDialog), cart, note, send, live status, the bill
- waiter: TabletRequests on the table page, tablet_order message theme with Open the table
- manager: Settings -> Menu tablets
- tests: test_tablet_orders.py, menu-tablet unit, menu_tablet.mjs e2e (the done-when)
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/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). **`data/media` belongs in every site backup together with `pos.db`** (the database only holds ids and hashes; DEPLOYMENT_GUIDE → Backups). 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`. **Videos (5.4e, `services/video.py`):** MP4 / MOV / WebM kept as uploaded; a background thread (`start_worker` in `main.py`'s lifespan, one video at a time, low priority, 2 threads) makes the still frame (the same `thumb` / `card` / `full` WebP) and, when `needs_version()` says so (not H.264 MP4, over 1920 px, 10-bit / HDR, other audio, > 12 Mbps), `play.mp4` (H.264 + AAC, ≤ 1920 px, HDR tone-mapped, faststart). `Media.processing` waiting → working (`progress`) → done | failed; migration 0031 queues existing videos. ffmpeg comes from the pinned `imageio-ffmpeg` wheel (static, Linux x86-64 / ARM64 / Windows; `XENIA_FFMPEG` overrides); without it videos stay as uploaded (`processing` null). `urls` gains `thumb`/`card`/`full`/`play` as they exist; `media.video_src()` is what a screen plays; `video.on_done(fn)` listeners (signage tells the screens playing 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`). **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. **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/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" **Ordering at the table (6.6, D-30):** `services/tablet_orders.py` + `models/tablet_order.py` (`tablet_orders`, 0034). Device config `ordering` (off), `bill`, and per-tablet overrides `order_confirm` / `order_no_order` / `order_max_items` / `order_max_of_one` / `order_min_seconds` (-1 / `venue` = the venue's); the venue's rules are the JSON setting `menu_tablet.ordering` (`GET/PUT /api/menu-tablet/ordering`, Settings → Menu tablets). `/menu` adds `table.can_order`, `table.can_see_bill` and `ordering` (rules + `choices`: the POS product shape at in-store prices, so the tablet reuses `pos/ProductDialog`). `POST /quote` / `/order` take POS lines by id (`pos_cart.resolve_line`, never prices or discounts); every order is a `TabletOrder` row (it also times the limit); kitchen mode places it with `orders_api.add_priced_items(source="tablet")`, waiter mode leaves it `waiting` until `POST /requests/{id}/accept|decline` (`ordering.orders.open`; the phone's `TabletRequests` on the table page). Events: `tablet_order_updated` {id, table_id, status} to all (the phones refresh their list), `menu_tablet.order` to the tablet. Staff message type `tablet_order`. `GET/POST /bill`: the table's open order and asking for the bill (a `table_call` message, once a minute) |
|
||||
| `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()` |
|
||||
|
||||
@@ -115,6 +115,15 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"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."),
|
||||
"menu_tablet.no_ordering": (409, "Ordering isn't on for this tablet."),
|
||||
"menu_tablet.too_many": (422, "At most {most} items in one order."),
|
||||
"menu_tablet.too_many_of": (422, "At most {most} of \"{name}\" in one order."),
|
||||
"menu_tablet.too_soon": (429, "An order was just sent. Try again in {seconds} seconds."),
|
||||
"menu_tablet.table_closed": (409, "Please ask a waiter to open your table first."),
|
||||
"menu_tablet.day_closed": (409, "The venue isn't taking orders right now. Please ask a waiter."),
|
||||
"menu_tablet.no_staff": (409, "There is no staff account to place the order with."),
|
||||
"menu_tablet.order_not_found": (404, "This order was not found."),
|
||||
"menu_tablet.order_answered": (409, "This order was already answered."),
|
||||
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
||||
"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})."),
|
||||
|
||||
@@ -100,6 +100,9 @@
|
||||
},
|
||||
"tablet": {
|
||||
"call_message": "Τραπεζι {table}: οι πελατες καλουν σερβιτορο.",
|
||||
"sender": "Tablet μενου"
|
||||
"sender": "Tablet μενου",
|
||||
"order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.",
|
||||
"order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.",
|
||||
"bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +100,9 @@
|
||||
},
|
||||
"tablet": {
|
||||
"call_message": "Table {table}: the guests call a waiter.",
|
||||
"sender": "Menu tablet"
|
||||
"sender": "Menu tablet",
|
||||
"order_sent": "Table {table} ordered from the tablet ({count} items): sent to the kitchen.",
|
||||
"order_waiting": "Table {table} ordered from the tablet ({count} items): confirm it on the table.",
|
||||
"bill_message": "Table {table}: the guests ask for the bill."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Orders from a menu tablet at a table (plan step 6.6, D-30, models/tablet_order.py).
|
||||
|
||||
Revision ID: 0034_tablet_orders
|
||||
Revises: 0033_menu_translations
|
||||
Create Date: 2026-11-18 16:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from core.timeutil import UTCDateTime
|
||||
|
||||
revision = '0034_tablet_orders'
|
||||
down_revision = '0033_menu_translations'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
'tablet_orders',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('device_id', sa.Integer(), nullable=True),
|
||||
sa.Column('table_id', sa.Integer(), nullable=True),
|
||||
sa.Column('lines', sa.JSON(), nullable=False),
|
||||
sa.Column('note', sa.Text(), nullable=True),
|
||||
sa.Column('total', sa.Float(), nullable=False),
|
||||
sa.Column('status', sa.String(), nullable=False),
|
||||
sa.Column('order_id', sa.Integer(), nullable=True),
|
||||
sa.Column('reason', sa.String(), nullable=True),
|
||||
sa.Column('decided_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('decided_at', UTCDateTime(), nullable=True),
|
||||
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['decided_by_id'], ['users.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['device_id'], ['devices.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['table_id'], ['tables.id'], ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
with op.batch_alter_table('tablet_orders', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_tablet_orders_created_at'), ['created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_tablet_orders_device_id'), ['device_id'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_tablet_orders_id'), ['id'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_tablet_orders_status'), ['status'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_tablet_orders_table_id'), ['table_id'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table('tablet_orders')
|
||||
@@ -41,3 +41,4 @@ import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
|
||||
import models.media # noqa: F401 Media (media library, step 5.1)
|
||||
import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3)
|
||||
import models.signage # noqa: F401 SignagePlaylist, SignageSlide (signage, step 5.4a)
|
||||
import models.tablet_order # noqa: F401 TabletOrder (ordering from a menu tablet, step 6.6)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Orders from a menu tablet at a table (plan step 6.6, D-30).
|
||||
|
||||
Every order a tablet sends is a row: what was sent (`lines`, as the counter's lines by id,
|
||||
services/pos_cart.py), its note, the total it was quoted at, and what happened:
|
||||
waiting a waiter must confirm it first (the venue's or the tablet's setting)
|
||||
sent on the table's order and in the kitchen (`order_id`)
|
||||
declined a waiter declined it (`reason` for the guests)
|
||||
The rows also give the time limit between two orders from one tablet.
|
||||
"""
|
||||
from sqlalchemy import JSON, Column, Float, ForeignKey, Integer, String, Text
|
||||
|
||||
from core.timeutil import UTCDateTime, utcnow
|
||||
from database import Base
|
||||
|
||||
|
||||
class TabletOrder(Base):
|
||||
__tablename__ = "tablet_orders"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||
table_id = Column(Integer, ForeignKey("tables.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||
lines = Column(JSON, nullable=False, default=list)
|
||||
note = Column(Text, nullable=True)
|
||||
total = Column(Float, nullable=False, default=0.0)
|
||||
status = Column(String, nullable=False, default="waiting", index=True)
|
||||
order_id = Column(Integer, ForeignKey("orders.id", ondelete="SET NULL"), nullable=True)
|
||||
reason = Column(String, nullable=True)
|
||||
decided_by_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||
decided_at = Column(UTCDateTime, nullable=True)
|
||||
created_at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
|
||||
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm, SettingDef
|
||||
|
||||
POINTS = ('in_store', 'in_store_takeaway', 'qr_table', 'online_takeaway', 'online_delivery', 'online_preorder', 'none')
|
||||
|
||||
@@ -18,6 +18,10 @@ MODULE = Module(
|
||||
routers=(
|
||||
Mount('routers.menu_tablet', '/api/menu-tablet'),
|
||||
),
|
||||
# Ordering from a tablet at a table (6.6, D-30): the venue's rules, each overridable per tablet
|
||||
settings=(
|
||||
SettingDef('menu_tablet.ordering', '{}', 'Ordering from menu tablets at tables (plan step 6.6): confirm (kitchen | waiter), no_order (open | refuse), max_items, max_of_one, min_seconds. Edited in Settings > Menu tablets.', type='json'),
|
||||
),
|
||||
# How the menu looks on this tablet (owner 2026-11-17: views, photos, descriptions, grouping…)
|
||||
device_app=DeviceApp(login_modes=('none',), scope=(), config=(
|
||||
ConfigField('view', 'enum', default='expanded', choices=('compact', 'expanded', 'full'), group='look'),
|
||||
@@ -34,5 +38,13 @@ MODULE = Module(
|
||||
# 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'),
|
||||
# Guests order from it (6.6, D-30): off until the venue turns it on; the rest -1 / venue = the venue's setting
|
||||
ConfigField('ordering', 'bool', default=False, group='order'),
|
||||
ConfigField('bill', 'bool', default=True, group='order'),
|
||||
ConfigField('order_confirm', 'enum', default='venue', choices=('venue', 'kitchen', 'waiter'), group='order'),
|
||||
ConfigField('order_no_order', 'enum', default='venue', choices=('venue', 'open', 'refuse'), group='order'),
|
||||
ConfigField('order_max_items', 'int', default=-1, choices=(-1, 5, 10, 15, 20, 30, 50), group='order'),
|
||||
ConfigField('order_max_of_one', 'int', default=-1, choices=(-1, 1, 2, 3, 5, 10, 20), group='order'),
|
||||
ConfigField('order_min_seconds', 'int', default=-1, choices=(-1, 0, 30, 60, 120, 300, 600), group='order'),
|
||||
)),
|
||||
)
|
||||
|
||||
@@ -12,6 +12,15 @@ products and their categories: no ordering, no tables, no sign-in.
|
||||
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.
|
||||
|
||||
Ordering at the table (6.6, D-30, services/tablet_orders.py), a tablet at a table with
|
||||
"Guests can order" on:
|
||||
POST /quote {lines} the cart priced by the server (the counter's lines by id)
|
||||
POST /order {lines, note} sent to the kitchen, or waiting for a waiter (the rules)
|
||||
GET /order/{id} what happened to one of this tablet's orders
|
||||
GET /bill · POST /bill the table's bill so far · ask for the bill (a message)
|
||||
Staff (phones): GET /requests?table_id=, POST /requests/{id}/accept | decline (waiting orders).
|
||||
The venue's rules: GET / PUT /ordering (menu_tablet.manage).
|
||||
|
||||
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,
|
||||
idle reset, light / dark. Any menu change sends `menu_tablet.changed` to every tablet (main.py).
|
||||
@@ -24,9 +33,13 @@ import threading
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core import allergens, menu_languages, sales_points
|
||||
from core.access.deps import require
|
||||
from services import tablet_orders
|
||||
from core.access.deps import require_device
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
@@ -119,9 +132,18 @@ def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"
|
||||
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()
|
||||
table = _table(db, cfg)
|
||||
ordering = bool(table and cfg.get("ordering"))
|
||||
choices = {}
|
||||
if ordering: # what a guest can choose (the counter's shape)
|
||||
from routers.pos import _product_out
|
||||
order_prices = dict(zip([p.id for p in shown], unit_prices(db, shown, tablet_orders.POINT))) if shown else {}
|
||||
choices = {str(p.id): _product_out(p, order_prices.get(p.id, p.base_price)) for p in shown
|
||||
if p.is_available and sales_points.is_sold_at(p, tablet_orders.POINT)}
|
||||
return {
|
||||
"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,
|
||||
"table": {"id": table.id, "name": _label(table), "can_call": bool(cfg.get("call_waiter")),
|
||||
"can_order": ordering, "can_see_bill": bool(cfg.get("bill"))} if table else None,
|
||||
"ordering": {**tablet_orders.rules(db, cfg), "choices": choices} if ordering else None,
|
||||
"config": cfg,
|
||||
"categories": out_cats,
|
||||
"products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p),
|
||||
@@ -183,3 +205,202 @@ def call_waiter(db: Session = Depends(get_db), dev=Depends(require_device("menu_
|
||||
def reset_calls() -> None:
|
||||
with _lock:
|
||||
_calls.clear()
|
||||
|
||||
|
||||
# ── ordering at the table (6.6, D-30) ─────────────────────────────────────────
|
||||
|
||||
class LinesBody(BaseModel):
|
||||
lines: List[dict] = Field(min_length=1, max_length=100)
|
||||
note: Optional[str] = Field(default=None, max_length=300)
|
||||
|
||||
|
||||
def _ordering_table(db, dev):
|
||||
cfg = _config(dev)
|
||||
table = _table(db, cfg)
|
||||
if table is None or not cfg.get("ordering"):
|
||||
raise XeniaError("menu_tablet.no_ordering")
|
||||
return cfg, table
|
||||
|
||||
|
||||
def _lines(db, body: LinesBody):
|
||||
"""The guest's lines, resolved and checked by the server; never a discount or a price."""
|
||||
from services import pos_cart
|
||||
out = []
|
||||
for n, raw in enumerate(body.lines):
|
||||
raw = {k: v for k, v in (raw if isinstance(raw, dict) else {}).items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")}
|
||||
line = pos_cart.resolve_line(db, raw, n)
|
||||
if not line.product.is_available or not sales_points.is_sold_at(line.product, tablet_orders.POINT):
|
||||
raise XeniaError("order.product_unavailable", product_id=line.product.id)
|
||||
out.append(line)
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/quote")
|
||||
def quote(body: LinesBody, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
||||
from services import pos_cart
|
||||
_ordering_table(db, dev)
|
||||
return pos_cart.quote(db, _lines(db, body), "here", point=tablet_orders.POINT)
|
||||
|
||||
|
||||
@router.post("/order")
|
||||
def send_order(body: LinesBody, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
||||
"""The guests' order: on the table's order and in the kitchen, or waiting for a waiter."""
|
||||
from models.tablet_order import TabletOrder
|
||||
from services import pos_cart
|
||||
cfg, table = _ordering_table(db, dev)
|
||||
rules = tablet_orders.rules(db, cfg)
|
||||
lines = _lines(db, body)
|
||||
tablet_orders.check(db, dev.id, lines, rules)
|
||||
if rules["no_order"] == "refuse" and tablet_orders.open_order_of(db, table) is None:
|
||||
raise XeniaError("menu_tablet.table_closed")
|
||||
priced = pos_cart.quote(db, lines, "here", point=tablet_orders.POINT)
|
||||
row = TabletOrder(device_id=dev.id, table_id=table.id, note=(body.note or "").strip() or None, total=priced["total"],
|
||||
lines=[{**{k: v for k, v in raw.items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")},
|
||||
"name": q["name"], "quantity": q["quantity"], "total": q["total"],
|
||||
"entries": [e["name"] for e in q["entries"]], "removed_names": q["removed"]}
|
||||
for raw, q in zip(body.lines, priced["lines"])],
|
||||
status="waiting")
|
||||
db.add(row)
|
||||
db.commit()
|
||||
actor = tablet_orders.system_user(db)
|
||||
count = sum(line.quantity for line in lines)
|
||||
if rules["confirm"] == "kitchen":
|
||||
try:
|
||||
tablet_orders.place(db, row, table, lines, actor=actor, no_order=rules["no_order"])
|
||||
except XeniaError:
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
raise
|
||||
tablet_orders.tell_waiters(db, table, "tablet.order_sent", actor.id, count=count)
|
||||
else:
|
||||
tablet_orders.tell_waiters(db, table, "tablet.order_waiting", actor.id, count=count)
|
||||
tablet_orders.announce(row)
|
||||
return tablet_orders.out(db, row)
|
||||
|
||||
|
||||
@router.get("/order/{order_id}")
|
||||
def tablet_order(order_id: int, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
||||
from models.tablet_order import TabletOrder
|
||||
row = db.get(TabletOrder, order_id)
|
||||
if row is None or row.device_id != dev.id:
|
||||
raise XeniaError("menu_tablet.order_not_found")
|
||||
return tablet_orders.out(db, row)
|
||||
|
||||
|
||||
@router.get("/bill")
|
||||
def bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
||||
"""The table's bill so far: the open order's lines (cancelled ones left out) and what's left to pay."""
|
||||
cfg = _config(dev)
|
||||
table = _table(db, cfg)
|
||||
if table is None or not cfg.get("bill"):
|
||||
raise XeniaError("menu_tablet.no_table")
|
||||
order = tablet_orders.open_order_of(db, table)
|
||||
if order is None:
|
||||
return {"lines": [], "total": 0, "paid": 0, "due": 0}
|
||||
lines = []
|
||||
for i in order.items:
|
||||
if i.status == "cancelled":
|
||||
continue
|
||||
unit = (i.unit_price or 0) + (i.price_adjustment or 0)
|
||||
texts = menu_languages.product_texts(i.product, customer=False) if i.product else {}
|
||||
lines.append({"name": i.product_name or (i.product.name if i.product else ""), "names": texts.get("names"),
|
||||
"quantity": i.quantity, "total": round(unit * i.quantity, 2), "paid": i.status == "paid"})
|
||||
total = round(sum(x["total"] for x in lines), 2)
|
||||
paid = round(sum(x["total"] for x in lines if x["paid"]), 2)
|
||||
return {"lines": lines, "total": total, "paid": paid, "due": round(total - paid, 2)}
|
||||
|
||||
|
||||
_bills: dict[int, float] = {}
|
||||
|
||||
|
||||
@router.post("/bill")
|
||||
def ask_for_bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
||||
"""The guests ask for the bill: a message to the table's waiters, once a minute at most."""
|
||||
cfg = _config(dev)
|
||||
table = _table(db, cfg)
|
||||
if table is None or not cfg.get("bill"):
|
||||
raise XeniaError("menu_tablet.no_table")
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
last = _bills.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)
|
||||
_bills[dev.id] = now
|
||||
actor = tablet_orders.system_user(db)
|
||||
from core.i18n import t, venue_language
|
||||
from routers.kds import _save_and_broadcast_message
|
||||
lang = venue_language()
|
||||
_save_and_broadcast_message(db, actor.id, t("tablet.bill_message", lang, table=_label(table)), tablet_orders.waiters(db, table),
|
||||
"table_call", t("tablet.sender", lang), table_ids=[table.id])
|
||||
return {"again_in": CALL_EVERY_S}
|
||||
|
||||
|
||||
# ── staff: the orders that wait for a waiter ──────────────────────────────────
|
||||
|
||||
class DeclineBody(BaseModel):
|
||||
reason: Optional[str] = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
@router.get("/requests")
|
||||
def waiting(table_id: Optional[int] = None, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
|
||||
from models.tablet_order import TabletOrder
|
||||
tablet_orders.expire_waiting(db)
|
||||
q = db.query(TabletOrder).filter(TabletOrder.status == "waiting")
|
||||
if table_id is not None:
|
||||
q = q.filter(TabletOrder.table_id == table_id)
|
||||
return [tablet_orders.out(db, r) for r in q.order_by(TabletOrder.created_at).all()]
|
||||
|
||||
|
||||
def _waiting(db, request_id: int):
|
||||
from models.tablet_order import TabletOrder
|
||||
row = db.get(TabletOrder, request_id)
|
||||
if row is None:
|
||||
raise XeniaError("menu_tablet.order_not_found")
|
||||
if row.status != "waiting":
|
||||
raise XeniaError("menu_tablet.order_answered")
|
||||
return row
|
||||
|
||||
|
||||
@router.post("/requests/{request_id}/accept")
|
||||
def accept(request_id: int, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
|
||||
"""A waiter confirms the guests' order: on the table's order and in the kitchen."""
|
||||
from core.timeutil import utcnow
|
||||
from models.device import Device
|
||||
from models.table import Table
|
||||
from services import pos_cart
|
||||
row = _waiting(db, request_id)
|
||||
table = db.get(Table, row.table_id) if row.table_id else None
|
||||
if table is None or not table.is_active:
|
||||
raise XeniaError("menu_tablet.no_table")
|
||||
dev = db.get(Device, row.device_id) if row.device_id else None
|
||||
rules = tablet_orders.rules(db, _config(dev) if dev is not None else {})
|
||||
lines = [pos_cart.resolve_line(db, {k: v for k, v in raw.items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")}, n)
|
||||
for n, raw in enumerate(row.lines)]
|
||||
row.decided_by_id, row.decided_at = user.id, utcnow()
|
||||
# the waiter accepts on the table's behalf: opening the table is theirs (refuse only stops guests)
|
||||
tablet_orders.place(db, row, table, lines, actor=user, no_order="open" if rules["no_order"] == "refuse" else rules["no_order"])
|
||||
tablet_orders.announce(row)
|
||||
return tablet_orders.out(db, row)
|
||||
|
||||
|
||||
@router.post("/requests/{request_id}/decline")
|
||||
def decline(request_id: int, body: DeclineBody, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
|
||||
from core.timeutil import utcnow
|
||||
row = _waiting(db, request_id)
|
||||
row.status, row.reason = "declined", (body.reason or "").strip() or None
|
||||
row.decided_by_id, row.decided_at = user.id, utcnow()
|
||||
db.commit()
|
||||
tablet_orders.announce(row)
|
||||
return tablet_orders.out(db, row)
|
||||
|
||||
|
||||
# ── the venue's rules ────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/ordering")
|
||||
def ordering_rules(db: Session = Depends(get_db), user=Depends(require("menu_tablet.manage"))):
|
||||
return tablet_orders.venue_rules(db)
|
||||
|
||||
|
||||
@router.put("/ordering")
|
||||
def save_ordering_rules(body: tablet_orders.Rules, db: Session = Depends(get_db), user=Depends(require("menu_tablet.manage"))):
|
||||
return tablet_orders.save_venue_rules(db, body)
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Ordering from a menu tablet at a table (plan step 6.6, owner decisions D-30).
|
||||
|
||||
A tablet set at a table (device config `table`, 5.7b) with "Guests can order" on takes orders.
|
||||
The lines are the counter's lines by id (services/pos_cart.py: product, quick add-ons, extras,
|
||||
preferences, removed ingredients, a note), priced by the server, at the in-store prices.
|
||||
|
||||
Every rule is a venue setting (`menu_tablet.ordering`, edited in Settings → Menu tablets) that a
|
||||
tablet may override in its device config (-1 / "venue" = the venue's):
|
||||
confirm kitchen: straight to the table's order and the kitchen (like the QR menu)
|
||||
waiter: waits until a waiter of the table confirms it on their phone
|
||||
no_order open: the tablet's order opens the table's order (needs an open business day)
|
||||
refuse: until a waiter opens the table, the tablet says to ask one
|
||||
max_items most items in one order (quantities added up)
|
||||
max_of_one most of one product in one order
|
||||
min_seconds least time between two orders from the tablet
|
||||
Every order is a row (models/tablet_order.py). The table's waiters (its order's, else the zone's)
|
||||
get a message (`tablet_order`): what was sent, or that one waits for them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Literal
|
||||
|
||||
from core.errors import XeniaError
|
||||
from core.timeutil import utcnow
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
SETTING = "menu_tablet.ordering"
|
||||
POINT = "in_store"
|
||||
|
||||
|
||||
class Rules(BaseModel):
|
||||
"""The venue's rules (the setting); a tablet's config can override each."""
|
||||
confirm: Literal["kitchen", "waiter"] = "kitchen"
|
||||
no_order: Literal["open", "refuse"] = "open"
|
||||
max_items: int = Field(default=20, ge=1, le=200)
|
||||
max_of_one: int = Field(default=10, ge=1, le=99)
|
||||
min_seconds: int = Field(default=60, ge=0, le=3600)
|
||||
|
||||
|
||||
def venue_rules(db) -> dict:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
|
||||
try:
|
||||
raw = json.loads(row.value) if row and row.value else {}
|
||||
except ValueError:
|
||||
raw = {}
|
||||
try:
|
||||
return Rules(**{k: v for k, v in raw.items() if k in Rules.model_fields}).model_dump()
|
||||
except Exception:
|
||||
return Rules().model_dump()
|
||||
|
||||
|
||||
def save_venue_rules(db, body: Rules) -> dict:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
|
||||
value = json.dumps(body.model_dump())
|
||||
if row is None:
|
||||
db.add(PosSettings(key=SETTING, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
return body.model_dump()
|
||||
|
||||
|
||||
def rules(db, cfg: dict) -> dict:
|
||||
"""The rules for a tablet: its config's overrides on the venue's."""
|
||||
out = venue_rules(db)
|
||||
if cfg.get("order_confirm") in ("kitchen", "waiter"):
|
||||
out["confirm"] = cfg["order_confirm"]
|
||||
if cfg.get("order_no_order") in ("open", "refuse"):
|
||||
out["no_order"] = cfg["order_no_order"]
|
||||
for key in ("max_items", "max_of_one", "min_seconds"):
|
||||
v = cfg.get(f"order_{key}")
|
||||
if isinstance(v, int) and v >= 0:
|
||||
out[key] = v
|
||||
return out
|
||||
|
||||
|
||||
def check(db, dev_id: int, lines, r: dict) -> None:
|
||||
"""The limits; raises menu_tablet.too_many / too_many_of / too_soon."""
|
||||
from models.tablet_order import TabletOrder
|
||||
count = sum(line.quantity for line in lines)
|
||||
if count > r["max_items"]:
|
||||
raise XeniaError("menu_tablet.too_many", most=r["max_items"])
|
||||
per: dict = {}
|
||||
for line in lines:
|
||||
per[line.product.id] = per.get(line.product.id, 0) + line.quantity
|
||||
for pid, qty in per.items():
|
||||
if qty > r["max_of_one"]:
|
||||
name = next(line.product.name for line in lines if line.product.id == pid)
|
||||
raise XeniaError("menu_tablet.too_many_of", most=r["max_of_one"], name=name)
|
||||
if r["min_seconds"] > 0:
|
||||
last = (db.query(TabletOrder).filter(TabletOrder.device_id == dev_id, TabletOrder.status != "declined")
|
||||
.order_by(TabletOrder.created_at.desc()).first())
|
||||
if last is not None:
|
||||
wait = r["min_seconds"] - (utcnow() - last.created_at).total_seconds()
|
||||
if wait > 0:
|
||||
raise XeniaError("menu_tablet.too_soon", seconds=int(wait) + 1)
|
||||
|
||||
|
||||
def open_order_of(db, table):
|
||||
from models.order import Order
|
||||
return (db.query(Order).filter(Order.table_id == table.id, Order.status.in_(("open", "partially_paid", "paid")))
|
||||
.order_by(Order.id.desc()).first())
|
||||
|
||||
|
||||
def system_user(db):
|
||||
"""Who the server acts as for a guest's order (an active user who may run the venue)."""
|
||||
from core.access.queries import holders_filter
|
||||
from models.user import User
|
||||
user = db.query(User).filter(User.is_active.is_(True), holders_filter("core.dashboard.access")).order_by(User.id).first()
|
||||
if user is None:
|
||||
raise XeniaError("menu_tablet.no_staff")
|
||||
return user
|
||||
|
||||
|
||||
def place(db, tablet_order, table, lines, *, actor, no_order: str = "open") -> int:
|
||||
"""Put the lines on the table's order (opening it when allowed): kitchen, KDS, live. → order id."""
|
||||
from core import sales_points
|
||||
from models.business_day import BusinessDay
|
||||
from models.order import Order
|
||||
from routers import orders as orders_api
|
||||
from routers.orders import _audit
|
||||
from schemas.order import AddItemsRequest, OrderItemInput, SelectedOptionInput
|
||||
from services import pos_cart
|
||||
order = open_order_of(db, table)
|
||||
if order is None:
|
||||
if no_order != "open":
|
||||
raise XeniaError("menu_tablet.table_closed")
|
||||
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
|
||||
if day is None:
|
||||
raise XeniaError("menu_tablet.day_closed")
|
||||
order = Order(table_id=table.id, opened_by=actor.id, status="open", source="pos", order_type="here",
|
||||
sales_point=sales_points.IN_STORE, business_day_id=day.id)
|
||||
db.add(order)
|
||||
db.flush()
|
||||
_audit(db, order.id, "ORDER_OPENED", waiter_id=actor.id, note="menu tablet")
|
||||
db.commit()
|
||||
priced = pos_cart.price_lines(db, lines, order.order_type or "here", pos_cart.order_cart(order))
|
||||
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
|
||||
items = [OrderItemInput(
|
||||
product_id=line.product.id, quantity=line.quantity,
|
||||
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
|
||||
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None, source="tablet",
|
||||
) for line, adj in zip(lines, adjs)]
|
||||
note = (tablet_order.note or "").strip() or None
|
||||
orders_api.add_priced_items(order.id, AddItemsRequest(items=items, order_note=note), db, actor)
|
||||
tablet_order.status = "sent"
|
||||
tablet_order.order_id = order.id
|
||||
db.commit()
|
||||
return order.id
|
||||
|
||||
|
||||
def waiters(db, table) -> list[int]:
|
||||
from services.qr_orders import waiters_for
|
||||
order = open_order_of(db, table)
|
||||
|
||||
class _NoOrder:
|
||||
waiters = []
|
||||
return waiters_for(db, order or _NoOrder(), table)
|
||||
|
||||
|
||||
def tell_waiters(db, table, key: str, actor_id: int, **params) -> None:
|
||||
"""A message to the table's waiters' phones (never raises)."""
|
||||
from core.i18n import t, venue_language
|
||||
from routers.kds import _save_and_broadcast_message
|
||||
from services.table_qr import label
|
||||
try:
|
||||
lang = venue_language()
|
||||
_save_and_broadcast_message(db, actor_id, t(key, lang, table=label(table), **params), waiters(db, table),
|
||||
"tablet_order", t("tablet.sender", lang), table_ids=[table.id])
|
||||
except Exception as e:
|
||||
logger.error("tablet order on table %s: the waiters' message failed: %s", table.id, e)
|
||||
|
||||
|
||||
def announce(tablet_order) -> None:
|
||||
"""Tell the phones (the table's pending list) and the tablet that sent it."""
|
||||
from services.ws_bus import broadcast_sync
|
||||
data = {"id": tablet_order.id, "table_id": tablet_order.table_id, "status": tablet_order.status}
|
||||
broadcast_sync("tablet_order_updated", data)
|
||||
if tablet_order.device_id:
|
||||
broadcast_sync("menu_tablet.order", data, device_ids=[tablet_order.device_id])
|
||||
|
||||
|
||||
def out(db, row) -> dict:
|
||||
from models.table import Table
|
||||
from services.table_qr import label
|
||||
table = db.get(Table, row.table_id) if row.table_id else None
|
||||
return {"id": row.id, "table": {"id": table.id, "name": label(table)} if table else None, "status": row.status,
|
||||
"lines": row.lines, "note": row.note, "total": row.total, "order_id": row.order_id, "reason": row.reason,
|
||||
"created_at": row.created_at}
|
||||
|
||||
|
||||
def expire_waiting(db, hours: int = 6) -> None:
|
||||
"""Waiting orders nobody answered for hours are dropped (declined, no reason)."""
|
||||
from models.tablet_order import TabletOrder
|
||||
old = db.query(TabletOrder).filter(TabletOrder.status == "waiting", TabletOrder.created_at < utcnow() - timedelta(hours=hours)).all()
|
||||
for row in old:
|
||||
row.status = "declined"
|
||||
if old:
|
||||
db.commit()
|
||||
@@ -119,7 +119,7 @@ def test_a_tablet_at_a_table_calls_a_waiter(client, owner_h, tablet, menu, table
|
||||
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}
|
||||
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["table"] == {"id": table.id, "name": "5", "can_call": True, "can_order": False, "can_see_bill": 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
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Ordering from a menu tablet at a table (plan step 6.6, owner decisions D-30)."""
|
||||
import pytest
|
||||
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_menu_tablet import _calls, menu, table, tablet # noqa: F401 (fixtures)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def day(db, make_user):
|
||||
from core.timeutil import business_date_of, utcnow
|
||||
from models.business_day import BusinessDay
|
||||
now = utcnow()
|
||||
d = BusinessDay(status="open", opened_by_id=make_user(role="owner").id, opened_at=now, business_date=business_date_of(now))
|
||||
db.add(d)
|
||||
db.commit()
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def waiter(db, make_user, login):
|
||||
from models.user import WaiterZone
|
||||
w = make_user(role="waiter")
|
||||
db.add(WaiterZone(waiter_id=w.id, group_id=None))
|
||||
db.commit()
|
||||
return {"user": w, "h": login(w, client="waiter")}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def at_table(client, owner_h, tablet, table, menu, db):
|
||||
"""Tablet at table 5, ordering on; the souvlaki has a quick extra (pita)."""
|
||||
from models.product import ProductQuickOption
|
||||
q = ProductQuickOption(product_id=menu["souvlaki"].id, name="Pita", price=0.5)
|
||||
db.add(q)
|
||||
db.commit()
|
||||
menu["pita"] = q.id
|
||||
|
||||
def config(**cfg):
|
||||
r = client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"table": table.id, "ordering": True, **cfg}})
|
||||
assert r.status_code == 200, r.text
|
||||
config()
|
||||
tablet["config"] = config
|
||||
return tablet
|
||||
|
||||
|
||||
def lines(menu, n=2):
|
||||
return [{"product_id": menu["souvlaki"].id, "quantity": n, "quick": [{"id": menu["pita"], "qty": 1}]},
|
||||
{"product_id": menu["beer"].id, "quantity": 1}]
|
||||
|
||||
|
||||
def test_done_when_two_items_with_an_option_reach_the_kitchen_and_the_waiter(client, db, at_table, menu, table, day, waiter, monkeypatch):
|
||||
"""The done-when: two items with an option from the tablet at table 5; the kitchen gets them,
|
||||
the table's order has them, the waiter is told."""
|
||||
import routers.orders as orders_api
|
||||
from models.message import StaffMessage
|
||||
from models.order import Order
|
||||
printed = []
|
||||
monkeypatch.setattr(orders_api, "route_and_print_sync", lambda order_id, ids, db, **kw: printed.append((order_id, ids)) or [])
|
||||
data = client.get("/api/menu-tablet/menu", headers=at_table["h"]).json()
|
||||
assert data["table"]["can_order"] is True and data["ordering"]["confirm"] == "kitchen"
|
||||
assert str(menu["souvlaki"].id) in data["ordering"]["choices"]
|
||||
q = client.post("/api/menu-tablet/quote", headers=at_table["h"], json={"lines": lines(menu)})
|
||||
assert q.status_code == 200 and q.json()["total"] == round(2 * (3.5 + 0.5) + 4.5, 2)
|
||||
r = client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": lines(menu), "note": "no onions"})
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["status"] == "sent"
|
||||
order = db.query(Order).filter(Order.table_id == table.id).one()
|
||||
items = [i for i in order.items if i.status == "active"]
|
||||
assert sorted((i.product_id, i.quantity, i.source) for i in items) == sorted([(menu["souvlaki"].id, 2, "tablet"), (menu["beer"].id, 1, "tablet")])
|
||||
assert printed and printed[0][0] == order.id and len(printed[0][1]) == 2
|
||||
msg = db.query(StaffMessage).order_by(StaffMessage.id.desc()).first()
|
||||
assert msg.message_type == "tablet_order" and str(waiter["user"].id) in msg.target_waiter_ids and "sent to the kitchen" in msg.body
|
||||
# guests never send prices or discounts
|
||||
cheat = client.post("/api/menu-tablet/quote", headers=at_table["h"], json={"lines": [{"product_id": menu["beer"].id, "discount_pct": 100, "unit_price": 0.01}]})
|
||||
assert cheat.json()["total"] == 4.5
|
||||
|
||||
|
||||
def test_a_waiter_confirms_first(client, db, at_table, menu, table, day, waiter, monkeypatch):
|
||||
import routers.orders as orders_api
|
||||
monkeypatch.setattr(orders_api, "route_and_print_sync", lambda *a, **kw: [])
|
||||
at_table["config"](order_confirm="waiter")
|
||||
r = client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": lines(menu, 1)})
|
||||
assert r.json()["status"] == "waiting"
|
||||
rid = r.json()["id"]
|
||||
from models.order import Order
|
||||
assert db.query(Order).filter(Order.table_id == table.id).count() == 0 # nothing in the kitchen yet
|
||||
waiting = client.get(f"/api/menu-tablet/requests?table_id={table.id}", headers=waiter["h"]).json()
|
||||
assert [w["id"] for w in waiting] == [rid] and waiting[0]["lines"][0]["name"] == "Souvlaki"
|
||||
ok = client.post(f"/api/menu-tablet/requests/{rid}/accept", headers=waiter["h"])
|
||||
assert ok.status_code == 200 and ok.json()["status"] == "sent" and ok.json()["order_id"]
|
||||
assert err(client.post(f"/api/menu-tablet/requests/{rid}/accept", headers=waiter["h"])) == "menu_tablet.order_answered"
|
||||
assert client.get(f"/api/menu-tablet/order/{rid}", headers=at_table["h"]).json()["status"] == "sent"
|
||||
# a second one, declined with a reason the tablet shows
|
||||
import routers.menu_tablet # noqa: F401
|
||||
at_table["config"](order_confirm="waiter", order_min_seconds=0)
|
||||
r2 = client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": lines(menu, 1)}).json()
|
||||
no = client.post(f"/api/menu-tablet/requests/{r2['id']}/decline", headers=waiter["h"], json={"reason": "Kitchen closed"})
|
||||
assert no.json()["status"] == "declined"
|
||||
assert client.get(f"/api/menu-tablet/order/{r2['id']}", headers=at_table["h"]).json()["reason"] == "Kitchen closed"
|
||||
|
||||
|
||||
def test_limits_from_the_venue_and_the_tablet(client, owner_h, db, at_table, menu, day, monkeypatch):
|
||||
import routers.orders as orders_api
|
||||
monkeypatch.setattr(orders_api, "route_and_print_sync", lambda *a, **kw: [])
|
||||
r = client.put("/api/menu-tablet/ordering", headers=owner_h, json={"confirm": "kitchen", "no_order": "open", "max_items": 3, "max_of_one": 2, "min_seconds": 60})
|
||||
assert r.status_code == 200
|
||||
too_many = client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": [{"product_id": menu["beer"].id, "quantity": 2}, {"product_id": menu["steak"].id, "quantity": 2}]})
|
||||
assert err(too_many) == "menu_tablet.too_many" and too_many.json()["error"]["params"]["most"] == 3
|
||||
too_many_of = client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": [{"product_id": menu["beer"].id, "quantity": 3}]})
|
||||
assert err(too_many_of) == "menu_tablet.too_many_of"
|
||||
assert client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": [{"product_id": menu["beer"].id, "quantity": 1}]}).status_code == 200
|
||||
soon = client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": [{"product_id": menu["beer"].id, "quantity": 1}]})
|
||||
assert soon.status_code == 429 and err(soon) == "menu_tablet.too_soon"
|
||||
# the tablet's own values win
|
||||
at_table["config"](order_min_seconds=0, order_max_of_one=5)
|
||||
assert client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": [{"product_id": menu["beer"].id, "quantity": 3}]}).status_code == 200
|
||||
|
||||
|
||||
def test_no_open_order_open_or_refuse(client, owner_h, db, at_table, menu, table, day, waiter, monkeypatch):
|
||||
import routers.orders as orders_api
|
||||
monkeypatch.setattr(orders_api, "route_and_print_sync", lambda *a, **kw: [])
|
||||
at_table["config"](order_no_order="refuse")
|
||||
r = client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": lines(menu, 1)})
|
||||
assert err(r) == "menu_tablet.table_closed"
|
||||
from models.tablet_order import TabletOrder
|
||||
assert db.query(TabletOrder).count() == 0
|
||||
# a waiter opens the table: now the tablet adds to it
|
||||
from models.order import Order
|
||||
db.add(Order(table_id=table.id, opened_by=waiter["user"].id, status="open", order_type="here", business_day_id=day.id))
|
||||
db.commit()
|
||||
assert client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": lines(menu, 1)}).json()["status"] == "sent"
|
||||
|
||||
|
||||
def test_the_bill_and_asking_for_it(client, db, at_table, menu, table, day, waiter, monkeypatch):
|
||||
import routers.orders as orders_api
|
||||
from models.message import StaffMessage
|
||||
monkeypatch.setattr(orders_api, "route_and_print_sync", lambda *a, **kw: [])
|
||||
assert client.get("/api/menu-tablet/bill", headers=at_table["h"]).json() == {"lines": [], "total": 0, "paid": 0, "due": 0}
|
||||
client.post("/api/menu-tablet/order", headers=at_table["h"], json={"lines": lines(menu, 1)})
|
||||
bill = client.get("/api/menu-tablet/bill", headers=at_table["h"]).json()
|
||||
assert bill["total"] == round(3.5 + 0.5 + 4.5, 2) and bill["due"] == bill["total"] and len(bill["lines"]) == 2
|
||||
assert client.post("/api/menu-tablet/bill", headers=at_table["h"]).status_code == 200
|
||||
msg = db.query(StaffMessage).order_by(StaffMessage.id.desc()).first()
|
||||
assert msg.body == "Table 5: the guests ask for the bill."
|
||||
assert err(client.post("/api/menu-tablet/bill", headers=at_table["h"])) == "menu_tablet.call_too_soon"
|
||||
at_table["config"](bill=False)
|
||||
assert err(client.get("/api/menu-tablet/bill", headers=at_table["h"])) == "menu_tablet.no_table"
|
||||
|
||||
|
||||
def test_ordering_off_or_not_at_a_table(client, owner_h, tablet, menu):
|
||||
r = client.post("/api/menu-tablet/order", headers=tablet["h"], json={"lines": [{"product_id": menu["beer"].id}]})
|
||||
assert err(r) == "menu_tablet.no_ordering"
|
||||
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["ordering"] is None
|
||||
@@ -2,6 +2,7 @@ import { useState } from 'react'
|
||||
import { useCan, useModule } from '@xenia/access'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import CustomerDisplaySettings from './sections/CustomerDisplaySettings'
|
||||
import MenuTabletSettings from './sections/MenuTabletSettings'
|
||||
import VenueSettings from './sections/VenueSettings'
|
||||
import AppInfoTab from './tabs/AppInfoTab'
|
||||
import ColoursTab from './tabs/ColoursTab'
|
||||
@@ -12,7 +13,7 @@ import DevelopmentTab from './tabs/DevelopmentTab'
|
||||
import FiscalTab from './tabs/FiscalTab'
|
||||
import { TabGroup } from '../../ui/Tabs'
|
||||
|
||||
const TABS = ['app-info', 'venue', 'customer-display', 'security', 'operation', 'colours', 'print-fonts', 'fiscal', 'development']
|
||||
const TABS = ['app-info', 'venue', 'customer-display', 'menu-tablets', 'security', 'operation', 'colours', 'print-fonts', 'fiscal', 'development']
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
@@ -21,7 +22,11 @@ export default function SettingsPage() {
|
||||
const displayOn = useModule('customer_display')
|
||||
const displayKey = useCan('customer_display.manage')
|
||||
const display = displayOn && displayKey
|
||||
const tabs = TABS.filter(id => id !== 'customer-display' || display).map(id => ({ id, label: t(`settings.tabs.${id}`) }))
|
||||
// guests ordering from the menu tablets (6.6): where there are tablets and the user sets them up
|
||||
const tabletOn = useModule('menu_tablet')
|
||||
const tabletKey = useCan('menu_tablet.manage')
|
||||
const tablets = tabletOn && tabletKey
|
||||
const tabs = TABS.filter(id => (id !== 'customer-display' || display) && (id !== 'menu-tablets' || tablets)).map(id => ({ id, label: t(`settings.tabs.${id}`) }))
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
@@ -30,6 +35,7 @@ export default function SettingsPage() {
|
||||
{activeTab === 'app-info' && <AppInfoTab />}
|
||||
{activeTab === 'venue' && <div className="max-w-3xl"><VenueSettings /></div>}
|
||||
{activeTab === 'customer-display' && display && <div className="max-w-4xl"><CustomerDisplaySettings /></div>}
|
||||
{activeTab === 'menu-tablets' && tablets && <div className="max-w-3xl"><MenuTabletSettings /></div>}
|
||||
{activeTab === 'security' && <SecurityTab />}
|
||||
{activeTab === 'operation' && <OperationTab />}
|
||||
{activeTab === 'colours' && <ColoursTab />}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Settings → Menu tablets (plan step 6.6, owner decisions D-30): the venue's rules for guests
|
||||
// ordering from a menu tablet at a table. Each tablet can override any of them in Devices
|
||||
// ("Ordering" group of its settings); a tablet takes orders only with "Guests can order" on.
|
||||
// - who confirms: straight to the kitchen, or a waiter accepts each order on the phone first;
|
||||
// - a table with no open order: the tablet opens one, or the guests wait until a waiter does;
|
||||
// - limits: items in one order, of one dish, and the time between two orders from one tablet.
|
||||
// Backend: GET / PUT /api/menu-tablet/ordering (routers/menu_tablet.py, services/tablet_orders.py).
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Select, Spinner } from '@xenia/ui'
|
||||
import client from '../../../api/client'
|
||||
import { SettingRow, SettingsCard } from './SettingsCard'
|
||||
|
||||
const CHOICES = {
|
||||
max_items: [5, 10, 15, 20, 30, 50, 100],
|
||||
max_of_one: [1, 2, 3, 5, 10, 20],
|
||||
min_seconds: [0, 30, 60, 120, 300, 600],
|
||||
}
|
||||
|
||||
export default function MenuTabletSettings() {
|
||||
const { t } = useTranslation('manager')
|
||||
const [rules, setRules] = useState(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const ids = { confirm: useId(), no_order: useId(), max_items: useId(), max_of_one: useId(), min_seconds: useId() }
|
||||
|
||||
useEffect(() => {
|
||||
client.get('/api/menu-tablet/ordering').then(r => setRules(r.data)).catch(err => toast.error(errorMessage(err, t)))
|
||||
}, [t])
|
||||
if (!rules) return <div className="py-8 flex justify-center"><Spinner /></div>
|
||||
|
||||
const save = async (key, value) => {
|
||||
const next = { ...rules, [key]: value }
|
||||
setSaving(true)
|
||||
try {
|
||||
setRules((await client.put('/api/menu-tablet/ordering', next)).data)
|
||||
toast.success(t('settings.saved'))
|
||||
} catch (err) { toast.error(errorMessage(err, t)) }
|
||||
setSaving(false)
|
||||
}
|
||||
const numbers = (key, label) => {
|
||||
const list = CHOICES[key].includes(rules[key]) ? CHOICES[key] : [...CHOICES[key], rules[key]].sort((a, b) => a - b)
|
||||
return list.map(v => ({ value: String(v), label: label(v) }))
|
||||
}
|
||||
const seconds = v => (v === 0 ? t('menuTabletSettings.noWait') : v < 60 ? t('menuTabletSettings.seconds', { count: v }) : t('menuTabletSettings.minutes', { count: v / 60 }))
|
||||
|
||||
return (
|
||||
<SettingsCard title={t('menuTabletSettings.title')} description={t('menuTabletSettings.intro')} testId="settings-menu-tablets">
|
||||
<SettingRow label={t('menuTabletSettings.confirm')} tip={t('menuTabletSettings.confirmTip')} htmlFor={ids.confirm}>
|
||||
<Select id={ids.confirm} value={rules.confirm} disabled={saving} data-testid="setting-tablet-confirm"
|
||||
onChange={e => save('confirm', e.target.value)}
|
||||
options={['kitchen', 'waiter'].map(v => ({ value: v, label: t(`menuTabletSettings.confirms.${v}`) }))} />
|
||||
</SettingRow>
|
||||
<SettingRow label={t('menuTabletSettings.noOrder')} tip={t('menuTabletSettings.noOrderTip')} htmlFor={ids.no_order}>
|
||||
<Select id={ids.no_order} value={rules.no_order} disabled={saving} data-testid="setting-tablet-no-order"
|
||||
onChange={e => save('no_order', e.target.value)}
|
||||
options={['open', 'refuse'].map(v => ({ value: v, label: t(`menuTabletSettings.noOrders.${v}`) }))} />
|
||||
</SettingRow>
|
||||
<SettingRow label={t('menuTabletSettings.maxItems')} tip={t('menuTabletSettings.maxItemsTip')} htmlFor={ids.max_items}>
|
||||
<Select id={ids.max_items} value={String(rules.max_items)} disabled={saving} data-testid="setting-tablet-max-items"
|
||||
onChange={e => save('max_items', Number(e.target.value))} options={numbers('max_items', String)} />
|
||||
</SettingRow>
|
||||
<SettingRow label={t('menuTabletSettings.maxOfOne')} tip={t('menuTabletSettings.maxOfOneTip')} htmlFor={ids.max_of_one}>
|
||||
<Select id={ids.max_of_one} value={String(rules.max_of_one)} disabled={saving} data-testid="setting-tablet-max-of-one"
|
||||
onChange={e => save('max_of_one', Number(e.target.value))} options={numbers('max_of_one', String)} />
|
||||
</SettingRow>
|
||||
<SettingRow label={t('menuTabletSettings.minTime')} tip={t('menuTabletSettings.minTimeTip')} htmlFor={ids.min_seconds}>
|
||||
<Select id={ids.min_seconds} value={String(rules.min_seconds)} disabled={saving} data-testid="setting-tablet-min-seconds"
|
||||
onChange={e => save('min_seconds', Number(e.target.value))} options={numbers('min_seconds', seconds)} />
|
||||
</SettingRow>
|
||||
</SettingsCard>
|
||||
)
|
||||
}
|
||||
@@ -190,7 +190,16 @@
|
||||
},
|
||||
"menu_tablet": {
|
||||
"no_table": "Αυτό το tablet δεν είναι σε τραπέζι, οπότε δεν καλεί σερβιτόρο.",
|
||||
"call_too_soon": "Μόλις κλήθηκε σερβιτόρος. Δοκιμάστε ξανά σε {{seconds}} δευτερόλεπτα."
|
||||
"call_too_soon": "Μόλις κλήθηκε σερβιτόρος. Δοκιμάστε ξανά σε {{seconds}} δευτερόλεπτα.",
|
||||
"no_ordering": "Η παραγγελία δεν είναι ενεργή σε αυτό το tablet.",
|
||||
"too_many": "Έως {{most}} τεμάχια σε μία παραγγελία.",
|
||||
"too_many_of": "Έως {{most}} από «{{name}}» σε μία παραγγελία.",
|
||||
"too_soon": "Μόλις στάλθηκε παραγγελία. Δοκιμάστε ξανά σε {{seconds}} δευτερόλεπτα.",
|
||||
"table_closed": "Ζητήστε πρώτα από έναν σερβιτόρο να ανοίξει το τραπέζι σας.",
|
||||
"day_closed": "Το κατάστημα δεν δέχεται παραγγελίες αυτή τη στιγμή. Ρωτήστε έναν σερβιτόρο.",
|
||||
"no_staff": "Δεν υπάρχει λογαριασμός προσωπικού για την παραγγελία.",
|
||||
"order_not_found": "Η παραγγελία δεν βρέθηκε.",
|
||||
"order_answered": "Η παραγγελία έχει ήδη απαντηθεί."
|
||||
},
|
||||
"settings": {
|
||||
"invalid_json": "Οι ρυθμίσεις πρέπει να είναι έγκυρο JSON.",
|
||||
|
||||
@@ -322,7 +322,8 @@
|
||||
"print-fonts": "Εκτύπωση",
|
||||
"fiscal": "Ταμειακή",
|
||||
"development": "Developer",
|
||||
"customer-display": "Οθόνη πελάτη"
|
||||
"customer-display": "Οθόνη πελάτη",
|
||||
"menu-tablets": "Tablet μενού"
|
||||
},
|
||||
"mode": {
|
||||
"password": "Κωδικός",
|
||||
@@ -1816,5 +1817,32 @@
|
||||
"trNameHint": "Κενό: το όνομα όπως γράφτηκε.",
|
||||
"trDescription": "Περιγραφή"
|
||||
}
|
||||
},
|
||||
"menuTabletSettings": {
|
||||
"title": "Παραγγελίες από τα tablet μενού",
|
||||
"intro": "Οι κανόνες για τις παραγγελίες των πελατών από το tablet του τραπεζιού τους. Κάθε tablet μπορεί να αλλάξει οποιονδήποτε από τις Συσκευές· ένα tablet δέχεται παραγγελίες μόνο με ενεργό το «Οι πελάτες παραγγέλνουν».",
|
||||
"confirm": "Ποιος επιβεβαιώνει μια παραγγελία",
|
||||
"confirmTip": "Κατευθείαν στην κουζίνα: η παραγγελία τυπώνεται αμέσως στην κουζίνα και ενημερώνονται οι σερβιτόροι του τραπεζιού. Επιβεβαιώνει πρώτα σερβιτόρος: η παραγγελία περιμένει στη σελίδα του τραπεζιού στα κινητά των σερβιτόρων μέχρι κάποιος να την αποδεχτεί (τότε πάει στην κουζίνα) ή να την απορρίψει με έναν λόγο που βλέπουν οι πελάτες.",
|
||||
"confirms": {
|
||||
"kitchen": "Κατευθείαν στην κουζίνα",
|
||||
"waiter": "Επιβεβαιώνει πρώτα σερβιτόρος"
|
||||
},
|
||||
"noOrder": "Τραπέζι χωρίς ανοιχτή παραγγελία",
|
||||
"noOrderTip": "Ανοίγει μία: η πρώτη παραγγελία του tablet ανοίγει το τραπέζι. Περιμένει σερβιτόρο: οι πελάτες παραγγέλνουν μόνο αφού ένας σερβιτόρος ανοίξει το τραπέζι.",
|
||||
"noOrders": {
|
||||
"open": "Το tablet ανοίγει μία",
|
||||
"refuse": "Περιμένει σερβιτόρο να το ανοίξει"
|
||||
},
|
||||
"maxItems": "Μέγιστα τεμάχια σε μία παραγγελία",
|
||||
"maxItemsTip": "Όλα τα τεμάχια μιας παραγγελίας μαζί. Μεγαλύτερες παραγγελίες απορρίπτονται με μήνυμα στο tablet.",
|
||||
"maxOfOne": "Μέγιστα από ένα πιάτο σε μία παραγγελία",
|
||||
"maxOfOneTip": "Πόσα από το ίδιο πιάτο μπορεί να έχει μία παραγγελία.",
|
||||
"minTime": "Χρόνος ανάμεσα σε δύο παραγγελίες",
|
||||
"minTimeTip": "Ο ελάχιστος χρόνος ανάμεσα σε δύο παραγγελίες από το ίδιο tablet, ώστε ένα παιδί που παίζει να μη γεμίσει την κουζίνα.",
|
||||
"noWait": "Χωρίς αναμονή",
|
||||
"seconds_one": "{{count}} δευτερόλεπτο",
|
||||
"seconds_other": "{{count}} δευτερόλεπτα",
|
||||
"minutes_one": "{{count}} λεπτό",
|
||||
"minutes_other": "{{count}} λεπτά"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +283,8 @@
|
||||
"look": "Εμφάνιση",
|
||||
"menu": "Μενού",
|
||||
"use": "Χρήση",
|
||||
"table": "Σε τραπέζι"
|
||||
"table": "Σε τραπέζι",
|
||||
"order": "Παραγγελία από το τραπέζι"
|
||||
},
|
||||
"config": {
|
||||
"view": {
|
||||
@@ -370,6 +371,66 @@
|
||||
"call_waiter": {
|
||||
"label": "Οι πελάτες καλούν σερβιτόρο",
|
||||
"hint": "Κουμπί που στέλνει μήνυμα στους σερβιτόρους του τραπεζιού (το πολύ μία φορά το λεπτό)."
|
||||
},
|
||||
"ordering": {
|
||||
"label": "Οι πελάτες παραγγέλνουν",
|
||||
"hint": "Μόνο σε τραπέζι: καλάθι, επιλογές πιάτων και «Αποστολή». Οι κανόνες του χώρου είναι στις Ρυθμίσεις → Tablet μενού."
|
||||
},
|
||||
"bill": {
|
||||
"label": "Οι πελάτες βλέπουν τον λογαριασμό",
|
||||
"hint": "Τι έχει παραγγείλει το τραπέζι ως τώρα και «Ζητήστε τον λογαριασμό» (μήνυμα στους σερβιτόρους του τραπεζιού)."
|
||||
},
|
||||
"order_confirm": {
|
||||
"label": "Οι παραγγελίες πάνε",
|
||||
"choices": {
|
||||
"venue": "Όπως ο χώρος (Ρυθμίσεις)",
|
||||
"kitchen": "Κατευθείαν στην κουζίνα",
|
||||
"waiter": "Σε σερβιτόρο για επιβεβαίωση"
|
||||
}
|
||||
},
|
||||
"order_no_order": {
|
||||
"label": "Όταν το τραπέζι δεν έχει ανοιχτή παραγγελία",
|
||||
"choices": {
|
||||
"venue": "Όπως ο χώρος (Ρυθμίσεις)",
|
||||
"open": "Την ανοίγει το tablet",
|
||||
"refuse": "Να την ανοίξει πρώτα σερβιτόρος"
|
||||
}
|
||||
},
|
||||
"order_max_items": {
|
||||
"label": "Μέγιστα τεμάχια ανά παραγγελία",
|
||||
"choices": {
|
||||
"-1": "Όπως ο χώρος (Ρυθμίσεις)",
|
||||
"5": "5",
|
||||
"10": "10",
|
||||
"15": "15",
|
||||
"20": "20",
|
||||
"30": "30",
|
||||
"50": "50"
|
||||
}
|
||||
},
|
||||
"order_max_of_one": {
|
||||
"label": "Μέγιστα από ένα πιάτο ανά παραγγελία",
|
||||
"choices": {
|
||||
"-1": "Όπως ο χώρος (Ρυθμίσεις)",
|
||||
"1": "1",
|
||||
"2": "2",
|
||||
"3": "3",
|
||||
"5": "5",
|
||||
"10": "10",
|
||||
"20": "20"
|
||||
}
|
||||
},
|
||||
"order_min_seconds": {
|
||||
"label": "Ελάχιστος χρόνος ανάμεσα σε παραγγελίες",
|
||||
"choices": {
|
||||
"-1": "Όπως ο χώρος (Ρυθμίσεις)",
|
||||
"0": "Χωρίς αναμονή",
|
||||
"30": "30 δλ",
|
||||
"60": "1 λεπτό",
|
||||
"120": "2 λεπτά",
|
||||
"300": "5 λεπτά",
|
||||
"600": "10 λεπτά"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -507,6 +507,39 @@
|
||||
"call": "Κλήση σερβιτόρου",
|
||||
"called": "Ένας σερβιτόρος έρχεται στο τραπέζι {{table}}.",
|
||||
"callAgainIn": "Ξανά σε {{seconds}} δ",
|
||||
"callFailed": "Η κλήση δεν έφτασε: παρακαλούμε ρωτήστε στο ταμείο."
|
||||
"callFailed": "Η κλήση δεν έφτασε: παρακαλούμε ρωτήστε στο ταμείο.",
|
||||
"order": {
|
||||
"add": "Στην παραγγελία",
|
||||
"yours_one": "Η παραγγελία σας · {{count}} τεμάχιο",
|
||||
"yours_other": "Η παραγγελία σας · {{count}} τεμάχια",
|
||||
"title": "Η παραγγελία σας",
|
||||
"more": "Κι άλλα",
|
||||
"send": "Αποστολή στην κουζίνα",
|
||||
"less": "Ένα λιγότερο",
|
||||
"moreOf": "Ένα ακόμα",
|
||||
"remove": "Αφαίρεση",
|
||||
"total": "Σύνολο",
|
||||
"note": "Σημείωση για την κουζίνα (προαιρετικό)",
|
||||
"notePlaceholder": "π.χ. χωρίς κρεμμύδι, ένα χωρίς αλάτι",
|
||||
"confirmTitle": "Αποστολή στην κουζίνα;",
|
||||
"confirmBody": "{{count}} τεμάχια, {{total}}. Πληρώνετε στον σερβιτόρο στο τέλος.",
|
||||
"notYet": "Όχι ακόμα",
|
||||
"yesSend": "Ναι, αποστολή",
|
||||
"status": {
|
||||
"sent": "Η παραγγελία σας είναι στην κουζίνα. Καλή όρεξη!",
|
||||
"waiting": "Η παραγγελία στάλθηκε: ένας σερβιτόρος θα την επιβεβαιώσει σε λίγο.",
|
||||
"declined": "Ο σερβιτόρος δεν μπόρεσε να δεχτεί την παραγγελία."
|
||||
},
|
||||
"reason": "Λόγος: {{reason}}"
|
||||
},
|
||||
"bill": {
|
||||
"title": "Ο λογαριασμός",
|
||||
"ask": "Ζητήστε τον λογαριασμό",
|
||||
"empty": "Δεν έχει παραγγελθεί τίποτα ακόμα.",
|
||||
"due": "Πληρωτέο",
|
||||
"paid": "Έχουν πληρωθεί: {{amount}}",
|
||||
"asked": "Ένας σερβιτόρος φέρνει τον λογαριασμό.",
|
||||
"note": "Πληρώνετε στον σερβιτόρο."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -842,5 +842,16 @@
|
||||
"party": "Ιδιωτική εκδήλωση",
|
||||
"other": "Άλλος λόγος"
|
||||
}
|
||||
},
|
||||
"tabletOrder": {
|
||||
"title": "Παραγγελία από το tablet",
|
||||
"body": "Οι πελάτες το παρήγγειλαν από το tablet του τραπεζιού. Πηγαίνει στην κουζίνα όταν το αποδεχτείτε.",
|
||||
"accept": "Αποδοχή",
|
||||
"decline": "Απόρριψη",
|
||||
"reason": "Λόγος (τον βλέπουν οι πελάτες)",
|
||||
"reasonDefault": "Η κουζίνα δεν μπορεί να το φτιάξει αυτή τη στιγμή.",
|
||||
"accepted": "Στάλθηκε στην κουζίνα",
|
||||
"declined": "Απορρίφθηκε",
|
||||
"note": "Σημείωση: {{note}}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +190,16 @@
|
||||
},
|
||||
"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."
|
||||
"call_too_soon": "A waiter was just called. Try again in {{seconds}} seconds.",
|
||||
"no_ordering": "Ordering isn't on for this tablet.",
|
||||
"too_many": "At most {{most}} items in one order.",
|
||||
"too_many_of": "At most {{most}} of \"{{name}}\" in one order.",
|
||||
"too_soon": "An order was just sent. Try again in {{seconds}} seconds.",
|
||||
"table_closed": "Please ask a waiter to open your table first.",
|
||||
"day_closed": "The venue isn't taking orders right now. Please ask a waiter.",
|
||||
"no_staff": "There is no staff account to place the order with.",
|
||||
"order_not_found": "This order was not found.",
|
||||
"order_answered": "This order was already answered."
|
||||
},
|
||||
"settings": {
|
||||
"invalid_json": "The settings must be valid JSON.",
|
||||
|
||||
@@ -322,7 +322,8 @@
|
||||
"print-fonts": "Printing",
|
||||
"fiscal": "Fiscal device",
|
||||
"development": "Developer",
|
||||
"customer-display": "Customer display"
|
||||
"customer-display": "Customer display",
|
||||
"menu-tablets": "Menu tablets"
|
||||
},
|
||||
"mode": {
|
||||
"password": "Password",
|
||||
@@ -1816,5 +1817,32 @@
|
||||
"trNameHint": "Empty: the name as typed.",
|
||||
"trDescription": "Description"
|
||||
}
|
||||
},
|
||||
"menuTabletSettings": {
|
||||
"title": "Ordering from the menu tablets",
|
||||
"intro": "The rules for guests ordering from a tablet at their table. Each tablet can change any of them in Devices; a tablet takes orders only with “Guests can order” on.",
|
||||
"confirm": "Who confirms an order",
|
||||
"confirmTip": "Straight to the kitchen: the order prints in the kitchen at once and the table’s waiters are told. A waiter confirms first: the order waits on the table’s page in the waiters’ phones until one accepts it (then it goes to the kitchen) or declines it with a reason the guests see.",
|
||||
"confirms": {
|
||||
"kitchen": "Straight to the kitchen",
|
||||
"waiter": "A waiter confirms first"
|
||||
},
|
||||
"noOrder": "A table with no open order",
|
||||
"noOrderTip": "Open one: the tablet’s first order opens the table. Wait for a waiter: the guests can order only after a waiter has opened the table.",
|
||||
"noOrders": {
|
||||
"open": "The tablet opens one",
|
||||
"refuse": "Wait for a waiter to open it"
|
||||
},
|
||||
"maxItems": "Most items in one order",
|
||||
"maxItemsTip": "All the items of one order together. Bigger orders are refused with a message on the tablet.",
|
||||
"maxOfOne": "Most of one dish in one order",
|
||||
"maxOfOneTip": "How many of the same dish one order can have.",
|
||||
"minTime": "Time between two orders",
|
||||
"minTimeTip": "The shortest time between two orders from the same tablet, so a playing child can’t flood the kitchen.",
|
||||
"noWait": "No wait",
|
||||
"seconds_one": "{{count}} second",
|
||||
"seconds_other": "{{count}} seconds",
|
||||
"minutes_one": "{{count}} minute",
|
||||
"minutes_other": "{{count}} minutes"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +283,8 @@
|
||||
"look": "Look",
|
||||
"menu": "Menu",
|
||||
"use": "Use",
|
||||
"table": "At a table"
|
||||
"table": "At a table",
|
||||
"order": "Ordering at the table"
|
||||
},
|
||||
"config": {
|
||||
"view": {
|
||||
@@ -370,6 +371,66 @@
|
||||
"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)."
|
||||
},
|
||||
"ordering": {
|
||||
"label": "Guests can order",
|
||||
"hint": "At a table only: a cart, the dishes' choices and \"Send\". The venue's rules are in Settings → Menu tablets."
|
||||
},
|
||||
"bill": {
|
||||
"label": "Guests see the bill",
|
||||
"hint": "What the table ordered so far and \"Ask for the bill\" (a message to the table's waiters)."
|
||||
},
|
||||
"order_confirm": {
|
||||
"label": "Orders go",
|
||||
"choices": {
|
||||
"venue": "As the venue (Settings)",
|
||||
"kitchen": "Straight to the kitchen",
|
||||
"waiter": "To a waiter to confirm first"
|
||||
}
|
||||
},
|
||||
"order_no_order": {
|
||||
"label": "When the table has no open order",
|
||||
"choices": {
|
||||
"venue": "As the venue (Settings)",
|
||||
"open": "The tablet opens it",
|
||||
"refuse": "Ask a waiter to open it first"
|
||||
}
|
||||
},
|
||||
"order_max_items": {
|
||||
"label": "Most items in one order",
|
||||
"choices": {
|
||||
"-1": "As the venue (Settings)",
|
||||
"5": "5",
|
||||
"10": "10",
|
||||
"15": "15",
|
||||
"20": "20",
|
||||
"30": "30",
|
||||
"50": "50"
|
||||
}
|
||||
},
|
||||
"order_max_of_one": {
|
||||
"label": "Most of one dish in one order",
|
||||
"choices": {
|
||||
"-1": "As the venue (Settings)",
|
||||
"1": "1",
|
||||
"2": "2",
|
||||
"3": "3",
|
||||
"5": "5",
|
||||
"10": "10",
|
||||
"20": "20"
|
||||
}
|
||||
},
|
||||
"order_min_seconds": {
|
||||
"label": "Least time between two orders",
|
||||
"choices": {
|
||||
"-1": "As the venue (Settings)",
|
||||
"0": "No wait",
|
||||
"30": "30 s",
|
||||
"60": "1 min",
|
||||
"120": "2 min",
|
||||
"300": "5 min",
|
||||
"600": "10 min"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -507,6 +507,39 @@
|
||||
"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."
|
||||
"callFailed": "The call didn't go through: please ask at the counter.",
|
||||
"order": {
|
||||
"add": "Add to the order",
|
||||
"yours_one": "Your order · {{count}} item",
|
||||
"yours_other": "Your order · {{count}} items",
|
||||
"title": "Your order",
|
||||
"more": "Order more",
|
||||
"send": "Send to the kitchen",
|
||||
"less": "One less",
|
||||
"moreOf": "One more",
|
||||
"remove": "Remove",
|
||||
"total": "Total",
|
||||
"note": "A note for the kitchen (optional)",
|
||||
"notePlaceholder": "e.g. no onions, one without salt",
|
||||
"confirmTitle": "Send to the kitchen?",
|
||||
"confirmBody": "{{count}} items, {{total}}. You pay the waiter at the end.",
|
||||
"notYet": "Not yet",
|
||||
"yesSend": "Yes, send it",
|
||||
"status": {
|
||||
"sent": "Your order is in the kitchen. Enjoy!",
|
||||
"waiting": "Your order was sent: a waiter will confirm it in a moment.",
|
||||
"declined": "A waiter couldn't take this order."
|
||||
},
|
||||
"reason": "Reason: {{reason}}"
|
||||
},
|
||||
"bill": {
|
||||
"title": "The bill",
|
||||
"ask": "Ask for the bill",
|
||||
"empty": "Nothing ordered yet.",
|
||||
"due": "To pay",
|
||||
"paid": "Already paid: {{amount}}",
|
||||
"asked": "A waiter is bringing the bill.",
|
||||
"note": "You pay the waiter."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -842,5 +842,16 @@
|
||||
"party": "Private event",
|
||||
"other": "Other reason"
|
||||
}
|
||||
},
|
||||
"tabletOrder": {
|
||||
"title": "Ordered from the tablet",
|
||||
"body": "The guests ordered this from the table's tablet. It goes to the kitchen when you accept it.",
|
||||
"accept": "Accept",
|
||||
"decline": "Decline",
|
||||
"reason": "Reason (the guests see it)",
|
||||
"reasonDefault": "The kitchen can't make it right now.",
|
||||
"accepted": "Sent to the kitchen",
|
||||
"declined": "Declined",
|
||||
"note": "Note: {{note}}"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
// compact / expanded / full view, photos, descriptions, grouped or one A–Z list, whose prices,
|
||||
// sold-out style, search, one category or all, languages, back to the start after a while, light /
|
||||
// dark. Keeps the last menu for offline; a menu change arrives live (`menu_tablet.changed`).
|
||||
// A tablet set at a table (5.7b) can call the table's waiters (once a minute at most).
|
||||
// A tablet set at a table (5.7b) can call the table's waiters (once a minute at most), and with
|
||||
// "Guests can order" on take the table's orders and show its bill (6.6, TableOrdering.jsx).
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { BellRing, Search, X } from 'lucide-react'
|
||||
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
|
||||
@@ -13,6 +14,8 @@ import { Allergens } from '@xenia/access'
|
||||
import client from '../../api/client'
|
||||
import { useLiveEvent, useLiveEvents } from '../../device/context'
|
||||
import { idle, languagesOf, localize, search, sections } from './logic'
|
||||
import { addToCart } from './ordering'
|
||||
import { AddToOrder, BillButton, CartBar, OrderStatus } from './TableOrdering'
|
||||
|
||||
const quiet = { xenia: { noOverride: true } }
|
||||
const CACHE_KEY = 'xenia:menu-tablet:menu'
|
||||
@@ -28,6 +31,8 @@ export default function MenuTabletApp() {
|
||||
const [data, setData] = useState(readCache)
|
||||
const [q, setQ] = useState('')
|
||||
const [open, setOpen] = useState(null)
|
||||
const [cart, setCart] = useState([]) // the guests' order before it's sent (6.6)
|
||||
const [lastOrder, setLastOrder] = useState(null) // what happened to the last one sent
|
||||
const lastTouch = useRef(0) // set on the first touch and when the tablet starts (below)
|
||||
const scroller = useRef(null)
|
||||
|
||||
@@ -61,6 +66,7 @@ export default function MenuTabletApp() {
|
||||
const reset = useCallback(() => {
|
||||
setQ('')
|
||||
setOpen(null)
|
||||
setCart([]) // new guests: a new order
|
||||
scroller.current?.scrollTo?.({ top: 0 })
|
||||
if (langs.length > 1 && language !== langs[0]) changeLanguage(langs[0])
|
||||
}, [langs, language, changeLanguage])
|
||||
@@ -93,6 +99,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>}
|
||||
</div>
|
||||
)}
|
||||
{data.table?.can_order && data.table?.can_see_bill && <BillButton language={language} />}
|
||||
{data.table?.can_call && <CallWaiter table={data.table} />}
|
||||
{langs.length > 1 && (
|
||||
<div className="flex rounded-control border border-line overflow-hidden" role="group" aria-label={t('menuTablet.language')}>
|
||||
@@ -113,6 +120,8 @@ export default function MenuTabletApp() {
|
||||
</nav>
|
||||
)}
|
||||
|
||||
<OrderStatus last={lastOrder} setLast={setLastOrder} />
|
||||
|
||||
<div ref={scroller} className="flex-1 overflow-y-auto px-4 py-4">
|
||||
{q ? (
|
||||
found.length ? <Items products={found} cfg={cfg} onOpen={setOpen} testid="menu-results" />
|
||||
@@ -127,7 +136,10 @@ export default function MenuTabletApp() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{open && <Details product={open} cfg={cfg} onClose={() => setOpen(null)} />}
|
||||
{data.table?.can_order && <CartBar cart={cart} setCart={setCart} onSent={setLastOrder} />}
|
||||
|
||||
{open && <Details product={open} cfg={cfg} onClose={() => setOpen(null)}
|
||||
order={data.table?.can_order ? <AddToOrder product={open} ordering={data.ordering} onAdd={item => { setCart(c => addToCart(c, item)); setOpen(null) }} /> : null} />}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -193,7 +205,7 @@ function Items({ products, cfg, onOpen, testid = 'menu-items' }) {
|
||||
}
|
||||
|
||||
/** One product, big: its photo, price, description and tags. */
|
||||
function Details({ product: p, cfg, onClose }) {
|
||||
function Details({ product: p, cfg, onClose, order }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
return (
|
||||
<Dialog open size="md" title={p.name} onClose={onClose} closeLabel={t('menuTablet.close')}>
|
||||
@@ -208,7 +220,7 @@ function Details({ product: p, cfg, onClose }) {
|
||||
<div className="flex flex-wrap gap-1.5">{p.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-control bg-surface-2 text-label text-ink-2">{tag}</span>)}</div>
|
||||
)}
|
||||
<Allergens allergens={p.allergens} />
|
||||
|
||||
{order}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// Ordering from the menu tablet at a table (plan step 6.6, owner decisions D-30). On a tablet set
|
||||
// at a table with "Guests can order" on:
|
||||
// - a dish's "Add to the order" opens its choices (the counter's dialog, priced by the server at
|
||||
// the in-store prices); the cart at the bottom collects them;
|
||||
// - "Your order" shows the lines (more / less / remove), a note for the kitchen and the server's
|
||||
// total; "Send to the kitchen" asks once more, then sends. Depending on the venue's (or this
|
||||
// tablet's) rules the order goes straight to the kitchen, or waits for a waiter to confirm it:
|
||||
// the tablet then says so and shows the answer when it comes (`menu_tablet.order`);
|
||||
// - "The bill" (when on) lists what the table ordered so far and lets the guests ask for the bill.
|
||||
// The limits (items per order, of one dish, time between orders) are the server's; its answer
|
||||
// is shown as it comes.
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Minus, Plus, Receipt, ShoppingBag, Trash2 } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Field, IconButton, Spinner, Textarea } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveEvent } from '../../device/context'
|
||||
import ProductDialog from '../pos/ProductDialog'
|
||||
import { useQuote } from '../pos/usePos'
|
||||
import { QUOTE_URL, cartCount, cartLines, changeQty } from './ordering'
|
||||
|
||||
const quiet = { xenia: { noOverride: true } }
|
||||
|
||||
/** "Add to the order" on a dish's details: its choices, then into the cart. */
|
||||
export function AddToOrder({ product, ordering, onAdd }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const [choosing, setChoosing] = useState(false)
|
||||
const choices = ordering?.choices?.[String(product.id)]
|
||||
if (!choices || !product.available) return null
|
||||
// the dialog shows the dish in the tablet's language
|
||||
const shown = { ...choices, name: product.name, description: product.description || choices.description }
|
||||
return (
|
||||
<>
|
||||
<Button size="lg" icon={<Plus size={18} />} onClick={() => setChoosing(true)} data-testid="menu-order-add">{t('menuTablet.order.add')}</Button>
|
||||
{choosing && <ProductDialog product={shown} orderType="here" quoteUrl={QUOTE_URL} onClose={() => setChoosing(false)}
|
||||
onAdd={line => onAdd({ line, name: product.name })} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** The cart bar and its sheet. `cart` = [{line, name}]. */
|
||||
export function CartBar({ cart, setCart, onSent }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
const [open, setOpen] = useState(false)
|
||||
const lines = cartLines(cart)
|
||||
const { quote } = useQuote(lines, 'here', null, QUOTE_URL)
|
||||
if (cart.length === 0) return null
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)} data-testid="menu-cart"
|
||||
className="mx-4 mb-4 h-14 px-5 rounded-card bg-accent text-accent-fg shadow-overlay flex items-center gap-3 text-body-lg font-semibold">
|
||||
<ShoppingBag size={22} aria-hidden="true" />
|
||||
<span className="flex-1 text-left">{t('menuTablet.order.yours', { count: cartCount(cart) })}</span>
|
||||
{quote && <span className="tabular-nums" data-testid="menu-cart-total">{formatMoney(quote.total)}</span>}
|
||||
</button>
|
||||
{open && <CartDialog cart={cart} setCart={setCart} quote={quote} onClose={() => setOpen(false)}
|
||||
onSent={result => { setOpen(false); onSent(result) }} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function CartDialog({ cart, setCart, quote, onClose, onSent }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
const [note, setNote] = useState('')
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [problem, setProblem] = useState(null)
|
||||
const send = async () => {
|
||||
setBusy(true)
|
||||
setProblem(null)
|
||||
try {
|
||||
const { data } = await client.post('/api/menu-tablet/order', { lines: cartLines(cart), note: note.trim() || null }, quiet)
|
||||
setCart([])
|
||||
onSent(data)
|
||||
} catch (err) {
|
||||
setProblem(errorMessage(err, t))
|
||||
setConfirming(false)
|
||||
} finally { setBusy(false) }
|
||||
}
|
||||
return (
|
||||
<Dialog open size="lg" onClose={onClose} title={t('menuTablet.order.title')} closeLabel={t('menuTablet.close')}
|
||||
footer={<>
|
||||
<Button variant="secondary" size="lg" onClick={onClose}>{t('menuTablet.order.more')}</Button>
|
||||
<Button size="lg" disabled={!cart.length} onClick={() => setConfirming(true)} data-testid="menu-order-send">{t('menuTablet.order.send')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-3" data-testid="menu-order">
|
||||
<ul className="grid gap-2">
|
||||
{cart.map((item, i) => {
|
||||
const priced = quote?.lines?.[i]
|
||||
return (
|
||||
<li key={i} className="flex items-center gap-3 p-3 rounded-card bg-surface-2" data-testid="menu-order-line">
|
||||
<span className="flex-1 min-w-0 grid">
|
||||
<span className="text-body-lg font-medium truncate">{item.name}</span>
|
||||
{priced?.entries?.length > 0 && <span className="text-label text-ink-2 truncate">{priced.entries.map(e => e.name).join(', ')}</span>}
|
||||
</span>
|
||||
<IconButton size="sm" variant="secondary" label={t('menuTablet.order.less')} onClick={() => setCart(c => changeQty(c, i, -1))}><Minus size={16} /></IconButton>
|
||||
<span className="w-8 text-center tabular-nums font-semibold" data-testid="menu-order-qty">{item.line.quantity}</span>
|
||||
<IconButton size="sm" variant="secondary" label={t('menuTablet.order.moreOf')} onClick={() => setCart(c => changeQty(c, i, 1))}><Plus size={16} /></IconButton>
|
||||
<span className="w-20 text-right tabular-nums">{priced ? formatMoney(priced.total) : ''}</span>
|
||||
<IconButton size="sm" variant="ghost" label={t('menuTablet.order.remove')} onClick={() => setCart(c => c.filter((_, j) => j !== i))}><Trash2 size={16} /></IconButton>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
<div className="flex items-baseline justify-between">
|
||||
<span className="text-body text-ink-2">{t('menuTablet.order.total')}</span>
|
||||
<span className="text-heading font-semibold tabular-nums" data-testid="menu-order-total">{quote ? formatMoney(quote.total) : <Spinner size="sm" />}</span>
|
||||
</div>
|
||||
<Field label={t('menuTablet.order.note')}>
|
||||
<Textarea rows={2} maxLength={300} value={note} onChange={e => setNote(e.target.value)} placeholder={t('menuTablet.order.notePlaceholder')} />
|
||||
</Field>
|
||||
{problem && <p role="alert" className="p-3 rounded-control bg-danger-soft text-danger-ink" data-testid="menu-order-problem">{problem}</p>}
|
||||
</div>
|
||||
{confirming && (
|
||||
<Dialog open size="sm" onClose={() => setConfirming(false)} title={t('menuTablet.order.confirmTitle')}
|
||||
footer={<>
|
||||
<Button variant="secondary" size="lg" onClick={() => setConfirming(false)}>{t('menuTablet.order.notYet')}</Button>
|
||||
<Button size="lg" loading={busy} onClick={send} data-testid="menu-order-confirm">{t('menuTablet.order.yesSend')}</Button>
|
||||
</>}>
|
||||
<p>{t('menuTablet.order.confirmBody', { count: cartCount(cart), total: quote ? formatMoney(quote.total) : '' })}</p>
|
||||
</Dialog>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
/** What happened to the last order: sent, waiting for a waiter, then the waiter's answer (live). */
|
||||
export function OrderStatus({ last, setLast }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const check = useCallback(async () => {
|
||||
if (!last) return
|
||||
try {
|
||||
const { data } = await client.get(`/api/menu-tablet/order/${last.id}`, quiet)
|
||||
setLast(data)
|
||||
} catch { /* offline: keep showing what we know */ }
|
||||
}, [last, setLast])
|
||||
useLiveEvent('menu_tablet.order', ev => { if (last && ev?.id === last.id) check() })
|
||||
useLiveEvent('ready', check)
|
||||
useEffect(() => {
|
||||
if (!last || last.status === 'waiting') return undefined
|
||||
const id = setTimeout(() => setLast(null), 15_000)
|
||||
return () => clearTimeout(id)
|
||||
}, [last, setLast])
|
||||
if (!last) return null
|
||||
const tone = last.status === 'declined' ? 'bg-danger-soft text-danger-ink' : last.status === 'waiting' ? 'bg-warning-soft text-warning-ink' : 'bg-success-soft text-success-ink'
|
||||
return (
|
||||
<div className={`mx-4 mt-3 p-3 rounded-card ${tone} flex items-center gap-3`} role="status" data-testid="menu-order-status" data-status={last.status}>
|
||||
<span className="flex-1">
|
||||
{t(`menuTablet.order.status.${last.status}`)}
|
||||
{last.status === 'declined' && last.reason && ` ${t('menuTablet.order.reason', { reason: last.reason })}`}
|
||||
</span>
|
||||
{last.status !== 'waiting' && <Button size="sm" variant="ghost" onClick={() => setLast(null)}>{t('menuTablet.close')}</Button>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** "The bill": what the table ordered so far; ask the waiters for the bill. */
|
||||
export function BillButton({ language }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
const [bill, setBill] = useState(null)
|
||||
const [asked, setAsked] = useState(null) // 'sent' | an error text
|
||||
const open = async () => {
|
||||
setAsked(null)
|
||||
try { setBill((await client.get('/api/menu-tablet/bill', quiet)).data) } catch (err) { setBill({ error: errorMessage(err, t) }) }
|
||||
}
|
||||
const ask = async () => {
|
||||
try { await client.post('/api/menu-tablet/bill', {}, quiet); setAsked('sent') } catch (err) { setAsked(errorMessage(err, t)) }
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={open} data-testid="menu-bill-button"
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-control border border-line bg-surface text-label font-semibold whitespace-nowrap">
|
||||
<Receipt size={18} aria-hidden="true" />{t('menuTablet.bill.title')}
|
||||
</button>
|
||||
{bill && (
|
||||
<Dialog open size="md" onClose={() => setBill(null)} title={t('menuTablet.bill.title')} closeLabel={t('menuTablet.close')}
|
||||
footer={!bill.error && <>
|
||||
<Button variant="secondary" size="lg" onClick={() => setBill(null)}>{t('menuTablet.close')}</Button>
|
||||
<Button size="lg" disabled={asked === 'sent'} onClick={ask} data-testid="menu-bill-ask">{t('menuTablet.bill.ask')}</Button>
|
||||
</>}>
|
||||
{bill.error ? <p className="text-danger-ink">{bill.error}</p> : (
|
||||
<div className="grid gap-3" data-testid="menu-bill">
|
||||
{bill.lines.length === 0 ? <p className="text-ink-2">{t('menuTablet.bill.empty')}</p> : (
|
||||
<ul className="grid gap-1">
|
||||
{bill.lines.map((l, i) => (
|
||||
<li key={i} className={`flex justify-between gap-3 ${l.paid ? 'text-ink-3 line-through' : ''}`} data-testid="menu-bill-line">
|
||||
<span>{l.quantity} × {l.names?.[language] || l.name}</span><span className="tabular-nums">{formatMoney(l.total)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="flex justify-between border-t border-line pt-2 text-body-lg font-semibold">
|
||||
<span>{t('menuTablet.bill.due')}</span><span className="tabular-nums" data-testid="menu-bill-due">{formatMoney(bill.due)}</span>
|
||||
</div>
|
||||
{bill.paid > 0 && <p className="text-label text-ink-2">{t('menuTablet.bill.paid', { amount: formatMoney(bill.paid) })}</p>}
|
||||
{asked === 'sent' && <p className="p-3 rounded-control bg-success-soft text-success-ink" role="status" data-testid="menu-bill-asked">{t('menuTablet.bill.asked')}</p>}
|
||||
{asked && asked !== 'sent' && <p className="p-3 rounded-control bg-danger-soft text-danger-ink" role="alert">{asked}</p>}
|
||||
<p className="text-label text-ink-3">{t('menuTablet.bill.note')}</p>
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// The menu tablet's cart (plan step 6.6). Pure: unit-tested in Node (tests/menu-tablet.test.mjs).
|
||||
// A cart item is { line, name }: the counter's line by id (apps/pos/logic/cart.js toLine) and the
|
||||
// dish's name in the tablet's language. Prices are always the server's (POST /api/menu-tablet/quote).
|
||||
|
||||
export const QUOTE_URL = '/api/menu-tablet/quote'
|
||||
|
||||
/** The lines as the server takes them. */
|
||||
export const cartLines = cart => cart.map(item => item.line)
|
||||
|
||||
/** How many items (quantities added up). */
|
||||
export const cartCount = cart => cart.reduce((s, item) => s + (item.line.quantity || 1), 0)
|
||||
|
||||
/** One more / one less of a line; at 0 the line goes. */
|
||||
export function changeQty(cart, index, step) {
|
||||
return cart.flatMap((item, i) => {
|
||||
if (i !== index) return [item]
|
||||
const quantity = (item.line.quantity || 1) + step
|
||||
return quantity > 0 ? [{ ...item, line: { ...item.line, quantity } }] : []
|
||||
})
|
||||
}
|
||||
|
||||
/** Add a line; the same dish with the same choices joins the existing line. */
|
||||
export function addToCart(cart, item) {
|
||||
const key = l => JSON.stringify({ ...l, quantity: undefined })
|
||||
const at = cart.findIndex(c => key(c.line) === key(item.line))
|
||||
if (at < 0) return [...cart, item]
|
||||
return cart.map((c, i) => (i === at ? { ...c, line: { ...c.line, quantity: c.line.quantity + item.line.quantity } } : c))
|
||||
}
|
||||
@@ -30,7 +30,8 @@ function Price({ value }) {
|
||||
return value ? <span className="text-ink-2 text-label">{value > 0 ? '+' : ''}{formatMoney(value)}</span> : null
|
||||
}
|
||||
|
||||
export default function ProductDialog({ product, orderType, onAdd, onClose }) {
|
||||
// quoteUrl: the menu tablet (6.6) prices a guest's choices with its own endpoint (in-store prices, no discounts)
|
||||
export default function ProductDialog({ product, orderType, onAdd, onClose, quoteUrl }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
const unit = unitOf(product)
|
||||
@@ -38,7 +39,7 @@ export default function ProductDialog({ product, orderType, onAdd, onClose }) {
|
||||
const [qty, setQty] = useState(unit ? unit.start : 1)
|
||||
const missing = missingChoices(product, sel)
|
||||
const line = useMemo(() => toLine(product, sel, qty), [product, sel, qty])
|
||||
const { quote, pending } = useQuote(missing.length ? [] : [line], orderType)
|
||||
const { quote, pending } = useQuote(missing.length ? [] : [line], orderType, null, quoteUrl)
|
||||
const priced = quote?.lines?.[0]
|
||||
|
||||
const add = () => { onAdd(line); onClose() }
|
||||
|
||||
@@ -45,17 +45,17 @@ export function useMenu() {
|
||||
/** The cart priced by POST /api/pos/quote whenever it changes (latest answer wins). With
|
||||
* `orderId` (a table's order) the order's items count for deals, as when it's sent.
|
||||
* → { quote, pending, error } */
|
||||
export function useQuote(lines, orderType, orderId = null) {
|
||||
export function useQuote(lines, orderType, orderId = null, url = '/api/pos/quote') {
|
||||
const [state, setState] = useState({ quote: null, pending: false, error: null })
|
||||
const seq = useRef(0)
|
||||
const key = JSON.stringify([lines, orderType, orderId])
|
||||
const key = JSON.stringify([lines, orderType, orderId, url])
|
||||
useEffect(() => {
|
||||
const mine = ++seq.current
|
||||
if (!lines.length) { setState({ quote: { lines: [], total: 0 }, pending: false, error: null }); return undefined }
|
||||
setState(s => ({ ...s, pending: true }))
|
||||
const id = setTimeout(async () => {
|
||||
try {
|
||||
const { data } = await client.post('/api/pos/quote', { order_type: orderType, lines, order_id: orderId ?? undefined }, quiet)
|
||||
const { data } = await client.post(url, { order_type: orderType, lines, order_id: orderId ?? undefined }, quiet)
|
||||
if (mine === seq.current) setState({ quote: data, pending: false, error: null })
|
||||
} catch (err) {
|
||||
if (mine === seq.current) setState(s => ({ ...s, pending: false, error: err }))
|
||||
|
||||
@@ -46,3 +46,15 @@ test('the menu in the language of the tablet (6.4): names switch, the base name
|
||||
assert.ok(matches(en.products[1], 'souvl') && matches(en.products[1], 'pork'))
|
||||
assert.equal(localize(data, 'el').products[1].name, 'Σουβλάκι')
|
||||
})
|
||||
|
||||
test('the tablet\'s cart (6.6): add, join the same choices, more / less, count', async () => {
|
||||
const { addToCart, cartCount, cartLines, changeQty } = await import('../src/apps/menu-tablet/ordering.js')
|
||||
let cart = addToCart([], { line: { product_id: 5, quantity: 1, quick: [{ id: 9, qty: 1 }] }, name: 'Pork skewer' })
|
||||
cart = addToCart(cart, { line: { product_id: 5, quantity: 2, quick: [{ id: 9, qty: 1 }] }, name: 'Pork skewer' })
|
||||
cart = addToCart(cart, { line: { product_id: 6, quantity: 1 }, name: 'Beer' })
|
||||
assert.equal(cart.length, 2)
|
||||
assert.equal(cart[0].line.quantity, 3)
|
||||
assert.equal(cartCount(cart), 4)
|
||||
assert.deepEqual(cartLines(changeQty(cart, 1, -1)), [{ product_id: 5, quantity: 3, quick: [{ id: 9, qty: 1 }] }])
|
||||
assert.equal(changeQty(cart, 0, 1)[0].line.quantity, 4)
|
||||
})
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
// prices; search finds a product (also typed in Latin letters) and its price; a product opens big;
|
||||
// the view options from the device config change it live; a price change shows without a reload;
|
||||
// the guest's language; back to the start after a while without a touch; a tablet at a table calls
|
||||
// a waiter (5.7b).
|
||||
// a waiter (5.7b); guests at a table order (two of a dish with an extra) and it reaches the
|
||||
// table's order and the kitchen; a waiter confirms first when set so; the bill (6.6).
|
||||
// Starts its own backend (:8067) and the terminal (:5195).
|
||||
// node menu_tablet.mjs
|
||||
import path from 'node:path'
|
||||
@@ -14,7 +15,7 @@ import { supportLogin } from './lib/support.mjs'
|
||||
const backend = await startBackend({ port: 8067, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } })
|
||||
const term = await startTerminalVite({ port: 5195, backendUrl: backend.url })
|
||||
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
|
||||
const r = reporter('menu tablet: the menu, search, views, live prices, languages, idle reset (5.7a), call a waiter (5.7b)')
|
||||
const r = reporter('menu tablet: the menu, search, views, live prices, languages, idle reset (5.7a), call a waiter (5.7b), order and the bill (6.6)')
|
||||
const errors = []
|
||||
let failures = 0
|
||||
|
||||
@@ -102,6 +103,61 @@ try {
|
||||
&& (await tab.getByTestId('menu-call-sent').textContent()).includes(t5.label || String(t5.number)))
|
||||
await tab.screenshot({ path: path.join(OUT, 'menu-tablet-call.png') })
|
||||
|
||||
// 6.6: guests order from the tablet at the table (the done-when): two of a dish with an extra
|
||||
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
|
||||
await api('PUT', `/api/products/${souvlaki.id}`, { token: boss, body: { quick_options: [{ name: 'Extra pita', price: 0.5 }] } })
|
||||
await api('PUT', '/api/menu-tablet/ordering', { token: boss, body: { confirm: 'kitchen', no_order: 'open', max_items: 20, max_of_one: 10, min_seconds: 0 } })
|
||||
await api('PATCH', `/api/devices/${dev.id}`, { token: boss, body: { config: { table: t5.id, ordering: true } } }) // the device's whole config
|
||||
await tab.getByTestId('menu-search').fill('souvl')
|
||||
await tab.getByTestId('menu-results').locator(`[data-testid="menu-item"][data-id="${souvlaki.id}"]`).click()
|
||||
r.check('6.6: with "Guests can order" on, a dish has "Add to the order"', await shown(tab, 'menu-order-add', 15_000))
|
||||
await tab.getByTestId('menu-order-add').click()
|
||||
await shown(tab, 'product-dialog', 5000)
|
||||
await tab.getByTestId('product-dialog').locator('[data-quick]').first().click()
|
||||
await tab.getByTestId('dialog-add').click()
|
||||
await tab.getByTestId('menu-cart').click()
|
||||
await tab.getByTestId('menu-order-line').first().getByRole('button').nth(1).click() // one more
|
||||
const qty = await waitFor(async () => ((await tab.getByTestId('menu-order-qty').first().textContent()) === '2' ? true : null), 5000, 200)
|
||||
const cartTotal = await waitFor(async () => { const x = await tab.getByTestId('menu-order-total').textContent(); return x.includes((2 * (7.7 + 0.5)).toFixed(2)) ? x : null }, 8000, 200) // re-priced after the change
|
||||
r.check('6.6: the cart: two of it, priced by the server with the extra', !!qty && String(cartTotal).includes((2 * (7.7 + 0.5)).toFixed(2)), String(cartTotal))
|
||||
await tab.screenshot({ path: path.join(OUT, 'menu-tablet-cart.png') })
|
||||
await tab.getByTestId('menu-order-send').click()
|
||||
await tab.getByTestId('menu-order-confirm').click()
|
||||
r.check('6.6: sent: the tablet says it is in the kitchen', await tab.locator('[data-testid="menu-order-status"][data-status="sent"]').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false))
|
||||
const tableOrder = async () => (await api('GET', '/api/orders/', { token: boss })).find(o => o.table_id === t5.id)
|
||||
const placed = await tableOrder()
|
||||
const lines = (placed?.items || []).filter(i => i.product_id === souvlaki.id && i.status !== 'cancelled')
|
||||
r.check("6.6: the table's order has them, from the tablet", lines.length > 0 && lines.reduce((n, i) => n + i.quantity, 0) === 2 && lines.every(i => i.source === 'tablet'),
|
||||
JSON.stringify(lines.map(i => [i.quantity, i.source])))
|
||||
|
||||
// a waiter confirms first: it waits, then the waiter accepts and the tablet hears it
|
||||
await api('PATCH', `/api/devices/${dev.id}`, { token: boss, body: { config: { table: t5.id, ordering: true, order_confirm: 'waiter' } } })
|
||||
await sleep(500)
|
||||
await tab.getByTestId('menu-search').fill('souvl')
|
||||
await tab.getByTestId('menu-results').locator(`[data-testid="menu-item"][data-id="${souvlaki.id}"]`).click()
|
||||
await tab.getByTestId('menu-order-add').click()
|
||||
await tab.getByTestId('dialog-add').click()
|
||||
await tab.getByTestId('menu-cart').click()
|
||||
await tab.getByTestId('menu-order-send').click()
|
||||
await tab.getByTestId('menu-order-confirm').click()
|
||||
r.check('6.6: a waiter confirms first: the tablet says it waits', await tab.locator('[data-testid="menu-order-status"][data-status="waiting"]').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false))
|
||||
const waiting = await api('GET', `/api/menu-tablet/requests?table_id=${t5.id}`, { token: boss })
|
||||
r.check("6.6: …and it is on the table's list for the waiters", waiting.length === 1)
|
||||
if (waiting[0]) await api('POST', `/api/menu-tablet/requests/${waiting[0].id}/accept`, { token: boss, body: {} })
|
||||
r.check('6.6: accepted: the tablet shows it in the kitchen, live', await tab.locator('[data-testid="menu-order-status"][data-status="sent"]').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false))
|
||||
|
||||
// the bill: what the table ordered so far, and asking for it
|
||||
await tab.getByTestId('menu-bill-button').click()
|
||||
const due = 2 * (7.7 + 0.5) + 7.7 // two with the extra, then one without
|
||||
r.check("6.6: the bill lists the table's order and what is due", await shown(tab, 'menu-bill', 5000)
|
||||
&& await tab.getByTestId('menu-bill-line').count() >= 2 && (await tab.getByTestId('menu-bill-due').textContent()).includes(due.toFixed(2)),
|
||||
`${due} / ${await tab.getByTestId('menu-bill-due').textContent().catch(() => '')}`)
|
||||
await tab.screenshot({ path: path.join(OUT, 'menu-tablet-bill.png') })
|
||||
await tab.getByTestId('menu-bill-ask').click()
|
||||
r.check('6.6: asking for the bill says a waiter is bringing it', await shown(tab, 'menu-bill-asked', 5000))
|
||||
await tab.keyboard.press('Escape')
|
||||
await tab.getByTestId('menu-search').fill('')
|
||||
|
||||
// the guest's language, then back to the start after a while
|
||||
await tab.getByTestId('menu-lang-en').click()
|
||||
const enPlaceholder = await tab.getByTestId('menu-search').getAttribute('placeholder')
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// Orders from the table's menu tablet that wait for a waiter (plan step 6.6, D-30): when the
|
||||
// venue (or the tablet) says a waiter confirms tablet orders first, they show here on the table,
|
||||
// with what the guests chose and their note. Accept sends it to the table's order and the
|
||||
// kitchen; Decline tells the tablet, with a reason the guests see. Refreshes on the live event
|
||||
// `tablet_order_updated` and after a reconnect. Shows nothing when none wait.
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCan, useModule } from '@xenia/access'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import client from '../api/client'
|
||||
import { apiError } from '../api/errors'
|
||||
import { money } from '../i18n'
|
||||
|
||||
export default function TabletRequests({ tableId }) {
|
||||
const { t } = useTranslation('waiter')
|
||||
const moduleOn = useModule('menu_tablet')
|
||||
const canOpen = useCan('ordering.orders.open')
|
||||
const on = moduleOn && canOpen
|
||||
const [list, setList] = useState([])
|
||||
const [declining, setDeclining] = useState(null)
|
||||
const [reason, setReason] = useState('')
|
||||
const [busy, setBusy] = useState(null)
|
||||
const [problem, setProblem] = useState(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!on) return
|
||||
try { setList((await client.get('/api/menu-tablet/requests', { params: { table_id: tableId } })).data) } catch { /* offline: keep */ }
|
||||
}, [on, tableId])
|
||||
useEffect(() => {
|
||||
const first = setTimeout(load, 0)
|
||||
const onEvent = e => { if (['tablet_order_updated', 'ready'].includes(e.detail?.type) && (!e.detail?.data?.table_id || e.detail.data.table_id === tableId)) load() }
|
||||
window.addEventListener('live-event', onEvent)
|
||||
window.addEventListener('live-reconnected', load)
|
||||
return () => { clearTimeout(first); window.removeEventListener('live-event', onEvent); window.removeEventListener('live-reconnected', load) }
|
||||
}, [load, tableId])
|
||||
|
||||
const answer = async (id, action, body) => {
|
||||
setBusy(id)
|
||||
setProblem(null)
|
||||
try {
|
||||
await client.post(`/api/menu-tablet/requests/${id}/${action}`, body ?? {})
|
||||
setDeclining(null)
|
||||
await load()
|
||||
} catch (err) { setProblem(apiError(err, t('tabletOrder.title'))) } finally { setBusy(null) }
|
||||
}
|
||||
|
||||
if (!on || list.length === 0) return null
|
||||
return (
|
||||
<div style={{ margin: '10px 12px 0', display: 'grid', gap: 8 }} data-testid="tablet-requests">
|
||||
{list.map(r => (
|
||||
<div key={r.id} data-testid="tablet-request" data-id={r.id}
|
||||
style={{ border: '2px solid var(--x-warning)', background: 'var(--x-warning-soft)', borderRadius: 14, padding: 12, display: 'grid', gap: 8 }}>
|
||||
<div style={{ fontWeight: 800, color: 'var(--x-warning-ink)' }}>📱 {t('tabletOrder.title')}</div>
|
||||
<div style={{ fontSize: 13, color: 'var(--x-ink-2)' }}>{t('tabletOrder.body')}</div>
|
||||
<div style={{ display: 'grid', gap: 4 }}>
|
||||
{r.lines.map((l, i) => (
|
||||
<div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 8, color: 'var(--x-ink)' }}>
|
||||
<span><b>{l.quantity}×</b> {l.name}{l.entries?.length ? <span style={{ color: 'var(--x-ink-2)' }}> · {l.entries.join(', ')}</span> : null}</span>
|
||||
<span style={{ fontVariantNumeric: 'tabular-nums' }}>{money(l.total)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{r.note && <div style={{ fontSize: 13, color: 'var(--x-ink)' }}>{t('tabletOrder.note', { note: r.note })}</div>}
|
||||
{declining === r.id ? (
|
||||
<div style={{ display: 'grid', gap: 6 }}>
|
||||
<label style={{ fontSize: 12, color: 'var(--x-ink-2)' }}>{t('tabletOrder.reason')}
|
||||
<input className="input" value={reason} onChange={e => setReason(e.target.value)} style={{ width: '100%', marginTop: 4 }} />
|
||||
</label>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={() => setDeclining(null)}>{t('common.back', { defaultValue: '←' })}</button>
|
||||
<button className="btn btn--danger" style={{ flex: 1 }} disabled={busy === r.id} data-testid="tablet-request-decline-confirm"
|
||||
onClick={() => answer(r.id, 'decline', { reason: reason.trim() || null })}>{t('tabletOrder.decline')}</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn btn--secondary" style={{ flex: 1 }} disabled={busy === r.id} data-testid="tablet-request-decline"
|
||||
onClick={() => { setReason(t('tabletOrder.reasonDefault')); setDeclining(r.id) }}>{t('tabletOrder.decline')}</button>
|
||||
<button className="btn btn--primary" style={{ flex: 2 }} disabled={busy === r.id} data-testid="tablet-request-accept"
|
||||
onClick={() => answer(r.id, 'accept')}>{t('tabletOrder.accept')} · {money(r.total)}</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{problem && <div role="alert" style={{ color: 'var(--x-danger-ink)', fontSize: 13 }}>{problem}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -44,6 +44,12 @@ const TYPE_THEME = {
|
||||
bg: 'var(--x-warning-fg)', border: 'var(--x-warning)', ackBg: 'var(--x-warning)',
|
||||
labelColor: 'var(--x-warning-ink)', icon: '🙋',
|
||||
},
|
||||
// the guests ordered from the table's menu tablet (plan step 6.6): sent to the kitchen, or
|
||||
// waiting on the table's page for a waiter to accept it
|
||||
tablet_order: {
|
||||
bg: 'var(--x-info-fg)', border: 'var(--x-info)', ackBg: 'var(--x-info)',
|
||||
labelColor: 'var(--x-info-ink)', icon: '📱',
|
||||
},
|
||||
}
|
||||
|
||||
function getTheme(messageType) {
|
||||
@@ -137,7 +143,7 @@ function NotificationBanner({ message, onAck, autoDismiss }) {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{(message.message_type === 'qr_order' || message.message_type === 'table_call') && tableIds.length > 0 && (
|
||||
{['qr_order', 'table_call', 'tablet_order'].includes(message.message_type) && tableIds.length > 0 && (
|
||||
<button
|
||||
data-testid="notify-open-table"
|
||||
onClick={() => { onAck(message.id); navigate(`/tables/${tableIds[0]}`) }}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useState, useRef } from 'react'
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import { useAllowed, useCan, useModule } from '@xenia/access'
|
||||
import OrderSummary from '../components/OrderSummary'
|
||||
import TabletRequests from '../components/TabletRequests'
|
||||
import TableHistory from '../components/TableHistory'
|
||||
import useConnectionStore from '../store/connectionStore'
|
||||
import client from '../api/client'
|
||||
@@ -1727,6 +1728,9 @@ export default function TableDetailPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* orders from the table's menu tablet waiting for a waiter (6.6) */}
|
||||
{!isStandalone && <TabletRequests tableId={Number(tableId)} />}
|
||||
|
||||
{!order && !isStandalone && (
|
||||
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<p style={{ color: 'var(--x-ink-2)', marginBottom: 24 }}>{t('tables.quick.noOrder')}</p>
|
||||
|
||||
Reference in New Issue
Block a user