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:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user