From c1af7770cf1aceefbc3f2413e647780be550f7ce Mon Sep 17 00:00:00 2001 From: bonamin Date: Wed, 18 Nov 2026 14:42:37 +0200 Subject: [PATCH] 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 --- docs/README.md | 2 +- local_backend/core/errors.py | 9 + local_backend/core/i18n/el.json | 5 +- local_backend/core/i18n/en.json | 5 +- .../migrations/versions/0034_tablet_orders.py | 47 ++++ local_backend/models/all.py | 1 + local_backend/models/tablet_order.py | 30 +++ local_backend/modules/menu_tablet/manifest.py | 14 +- local_backend/routers/menu_tablet.py | 223 +++++++++++++++++- local_backend/services/tablet_orders.py | 206 ++++++++++++++++ local_backend/tests/test_menu_tablet.py | 2 +- local_backend/tests/test_tablet_orders.py | 152 ++++++++++++ .../src/pages/Settings/SettingsPage.jsx | 10 +- .../Settings/sections/MenuTabletSettings.jsx | 74 ++++++ packages/i18n/locales/el/errors.json | 11 +- packages/i18n/locales/el/manager.json | 30 ++- packages/i18n/locales/el/modules.json | 63 ++++- packages/i18n/locales/el/terminal.json | 35 ++- packages/i18n/locales/el/waiter.json | 11 + packages/i18n/locales/en/errors.json | 11 +- packages/i18n/locales/en/manager.json | 30 ++- packages/i18n/locales/en/modules.json | 63 ++++- packages/i18n/locales/en/terminal.json | 35 ++- packages/i18n/locales/en/waiter.json | 11 + .../src/apps/menu-tablet/MenuTabletApp.jsx | 20 +- .../src/apps/menu-tablet/TableOrdering.jsx | 209 ++++++++++++++++ terminal/src/apps/menu-tablet/ordering.js | 28 +++ terminal/src/apps/pos/ProductDialog.jsx | 5 +- terminal/src/apps/pos/usePos.js | 6 +- terminal/tests/menu-tablet.test.mjs | 12 + tests/e2e/menu_tablet.mjs | 60 ++++- waiter_pwa/src/components/TabletRequests.jsx | 87 +++++++ .../src/context/NotificationContext.jsx | 8 +- waiter_pwa/src/pages/TableDetailPage.jsx | 4 + 34 files changed, 1491 insertions(+), 28 deletions(-) create mode 100644 local_backend/migrations/versions/0034_tablet_orders.py create mode 100644 local_backend/models/tablet_order.py create mode 100644 local_backend/services/tablet_orders.py create mode 100644 local_backend/tests/test_tablet_orders.py create mode 100644 manager_dashboard/src/pages/Settings/sections/MenuTabletSettings.jsx create mode 100644 terminal/src/apps/menu-tablet/TableOrdering.jsx create mode 100644 terminal/src/apps/menu-tablet/ordering.js create mode 100644 waiter_pwa/src/components/TabletRequests.jsx diff --git a/docs/README.md b/docs/README.md index e17cc76..fcc149e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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///` (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//` 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()` | diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 3c60962..0a39893 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -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})."), diff --git a/local_backend/core/i18n/el.json b/local_backend/core/i18n/el.json index c7e85aa..a0a7341 100644 --- a/local_backend/core/i18n/el.json +++ b/local_backend/core/i18n/el.json @@ -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}: οι πελάτες ζητούν τον λογαριασμό." } } diff --git a/local_backend/core/i18n/en.json b/local_backend/core/i18n/en.json index edc91dd..227ecc3 100644 --- a/local_backend/core/i18n/en.json +++ b/local_backend/core/i18n/en.json @@ -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." } } diff --git a/local_backend/migrations/versions/0034_tablet_orders.py b/local_backend/migrations/versions/0034_tablet_orders.py new file mode 100644 index 0000000..61d7c3e --- /dev/null +++ b/local_backend/migrations/versions/0034_tablet_orders.py @@ -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') diff --git a/local_backend/models/all.py b/local_backend/models/all.py index d15cff7..fd198da 100644 --- a/local_backend/models/all.py +++ b/local_backend/models/all.py @@ -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) diff --git a/local_backend/models/tablet_order.py b/local_backend/models/tablet_order.py new file mode 100644 index 0000000..9542228 --- /dev/null +++ b/local_backend/models/tablet_order.py @@ -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) diff --git a/local_backend/modules/menu_tablet/manifest.py b/local_backend/modules/menu_tablet/manifest.py index 4789b28..8ae1a8c 100644 --- a/local_backend/modules/menu_tablet/manifest.py +++ b/local_backend/modules/menu_tablet/manifest.py @@ -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'), )), ) diff --git a/local_backend/routers/menu_tablet.py b/local_backend/routers/menu_tablet.py index 6cb61ec..54aaf65 100644 --- a/local_backend/routers/menu_tablet.py +++ b/local_backend/routers/menu_tablet.py @@ -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) diff --git a/local_backend/services/tablet_orders.py b/local_backend/services/tablet_orders.py new file mode 100644 index 0000000..0def22f --- /dev/null +++ b/local_backend/services/tablet_orders.py @@ -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() diff --git a/local_backend/tests/test_menu_tablet.py b/local_backend/tests/test_menu_tablet.py index 58158df..1824502 100644 --- a/local_backend/tests/test_menu_tablet.py +++ b/local_backend/tests/test_menu_tablet.py @@ -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 diff --git a/local_backend/tests/test_tablet_orders.py b/local_backend/tests/test_tablet_orders.py new file mode 100644 index 0000000..c0cda36 --- /dev/null +++ b/local_backend/tests/test_tablet_orders.py @@ -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 diff --git a/manager_dashboard/src/pages/Settings/SettingsPage.jsx b/manager_dashboard/src/pages/Settings/SettingsPage.jsx index 2f6d87d..334b2f7 100644 --- a/manager_dashboard/src/pages/Settings/SettingsPage.jsx +++ b/manager_dashboard/src/pages/Settings/SettingsPage.jsx @@ -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 (
@@ -30,6 +35,7 @@ export default function SettingsPage() { {activeTab === 'app-info' && } {activeTab === 'venue' &&
} {activeTab === 'customer-display' && display &&
} + {activeTab === 'menu-tablets' && tablets &&
} {activeTab === 'security' && } {activeTab === 'operation' && } {activeTab === 'colours' && } diff --git a/manager_dashboard/src/pages/Settings/sections/MenuTabletSettings.jsx b/manager_dashboard/src/pages/Settings/sections/MenuTabletSettings.jsx new file mode 100644 index 0000000..73c6458 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/MenuTabletSettings.jsx @@ -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
+ + 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 ( + + + save('no_order', e.target.value)} + options={['open', 'refuse'].map(v => ({ value: v, label: t(`menuTabletSettings.noOrders.${v}`) }))} /> + + + save('max_of_one', Number(e.target.value))} options={numbers('max_of_one', String)} /> + + +