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:
2026-11-18 14:42:37 +02:00
co-authored by Claude Opus 5.5
parent c43dc8b55b
commit c1af7770cf
34 changed files with 1491 additions and 28 deletions
+9
View File
@@ -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})."),
+4 -1
View File
@@ -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}: οι πελάτες ζητούν τον λογαριασμό."
}
}
+4 -1
View File
@@ -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')
+1
View File
@@ -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)
+30
View File
@@ -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)
+13 -1
View File
@@ -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'),
)),
)
+222 -1
View File
@@ -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)
+206
View File
@@ -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()
+1 -1
View File
@@ -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
+152
View File
@@ -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