- backend: menu tablet device config `table` (ref, validated against active
tables) and `call_waiter`; GET /api/menu-tablet/menu gives the table and
whether it can call; POST /api/menu-tablet/call sends a `table_call` staff
message ("Table 5: the guests call a waiter.", venue language) to the table's
waiters (its open order's, else the zone's), at most once a minute per tablet
(menu_tablet.call_too_soon with the seconds left; menu_tablet.no_table).
- terminal: "Call a waiter" only on a tablet at a table; "A waiter is on the
way to table 5", then a countdown before it can call again; a failed call
says to ask at the counter.
- waiter: the call shows with its own look and "Open the table".
- manager: tables as the choices of a device setting.
- tests: backend +2 (535 → 533 passed total), e2e menu_tablet.mjs +3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
184 lines
7.7 KiB
Python
184 lines
7.7 KiB
Python
"""The menu tablet (plan step 5.7a): the venue's menu on a tablet, for staff ("how much is the
|
|
steak?") and for guests (a menu at the entrance, later a digital menu at the table). Just the
|
|
products and their categories: no ordering, no tables, no sign-in.
|
|
|
|
GET /api/menu-tablet/menu (a paired menu tablet) the categories in the catalogue's order
|
|
(sub-categories after their parent), each with its products in its
|
|
own order (a product listed in several categories shows in each),
|
|
the products once with name, description, tags, photo, the price
|
|
of the tablet's sales point and whether it is available; the
|
|
tablet's settings (device config) and the venue's name.
|
|
|
|
POST /api/menu-tablet/call (a tablet set at a table, 5.7b) call a waiter: a message to the
|
|
table's waiters (its order's, else the zone's), once a minute at most.
|
|
|
|
How it looks is the tablet's device config (modules/menu_tablet/manifest.py): view, photos,
|
|
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).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import threading
|
|
import time
|
|
|
|
from fastapi import APIRouter, Depends
|
|
from sqlalchemy.orm import Session
|
|
|
|
from core import sales_points
|
|
from core.access.deps import require_device
|
|
from core.errors import XeniaError
|
|
from database import get_db
|
|
|
|
router = APIRouter()
|
|
CALL_EVERY_S = 60
|
|
_calls: dict[int, float] = {} # tablet id → its last call (monotonic)
|
|
_lock = threading.Lock()
|
|
|
|
|
|
def _config(dev) -> dict:
|
|
from core.modules.device_config import effective, for_app
|
|
return effective(for_app("menu_tablet"), dev.config)
|
|
|
|
|
|
def tablets(db) -> list[int]:
|
|
from models.device import Device
|
|
return [i for (i,) in db.query(Device.id).filter(Device.app_key == "menu_tablet", Device.revoked_at.is_(None))]
|
|
|
|
|
|
def menu_changed(db) -> None:
|
|
"""Products, categories or prices changed (main.py): every tablet reads its menu again."""
|
|
from services.ws_bus import broadcast_sync
|
|
ids = tablets(db)
|
|
if ids:
|
|
broadcast_sync("menu_tablet.changed", {}, device_ids=ids)
|
|
|
|
|
|
def _tags(p) -> list[str]:
|
|
raw = getattr(p, "tags", None)
|
|
if isinstance(raw, str):
|
|
try:
|
|
raw = json.loads(raw)
|
|
except ValueError:
|
|
raw = []
|
|
return [t for t in (raw or []) if isinstance(t, str)]
|
|
|
|
|
|
@router.get("/menu")
|
|
def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
|
from models.product import Category, Product, ProductCategory
|
|
from models.settings import PosSettings
|
|
from services import media as media_store
|
|
from services.pos_cart import unit_prices
|
|
cfg = _config(dev)
|
|
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
|
|
by_parent: dict = {}
|
|
for c in cats:
|
|
by_parent.setdefault(c.parent_id, []).append(c)
|
|
ordered = [] # parents, each followed by its sub-categories
|
|
|
|
def walk(parent_id, depth):
|
|
for c in by_parent.get(parent_id, []):
|
|
ordered.append((c, depth))
|
|
walk(c.id, depth + 1)
|
|
walk(None, 0)
|
|
if cfg.get("category"):
|
|
root = next(((c, d) for c, d in ordered if c.id == cfg["category"]), None)
|
|
keep = set()
|
|
if root:
|
|
stack = [root[0].id]
|
|
while stack:
|
|
cid = stack.pop()
|
|
keep.add(cid)
|
|
stack.extend(x.id for x in by_parent.get(cid, []))
|
|
ordered = [(c, d) for c, d in ordered if c.id in keep]
|
|
|
|
point = None if cfg["sales_point"] == "none" else cfg["sales_point"]
|
|
products = db.query(Product).filter(Product.lifecycle_status == "active", Product.system_key.is_(None)).all()
|
|
if point:
|
|
products = [p for p in products if sales_points.is_sold_at(p, point)]
|
|
if cfg["sold_out"] == "hide":
|
|
products = [p for p in products if p.is_available]
|
|
by_id = {p.id: p for p in products}
|
|
members = db.query(ProductCategory).order_by(ProductCategory.sort_order).all()
|
|
in_cat: dict = {}
|
|
for m in members:
|
|
if m.product_id in by_id:
|
|
in_cat.setdefault(m.category_id, []).append(m.product_id)
|
|
|
|
out_cats, used = [], set()
|
|
for c, depth in ordered:
|
|
ids = in_cat.get(c.id, [])
|
|
has_sub = any(in_cat.get(x.id) for x in by_parent.get(c.id, []))
|
|
if ids or has_sub:
|
|
out_cats.append({"id": c.id, "name": c.name, "parent_id": c.parent_id, "depth": depth, "products": ids})
|
|
used.update(ids)
|
|
shown = [by_id[i] for i in by_id if i in used]
|
|
prices = dict(zip([p.id for p in shown], unit_prices(db, shown, point))) if point and shown else {}
|
|
name_row = db.query(PosSettings).filter(PosSettings.key == "venue.name").first()
|
|
table = _table(db, cfg)
|
|
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,
|
|
"config": cfg,
|
|
"categories": out_cats,
|
|
"products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p),
|
|
"price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available),
|
|
"image": media_store.image_of(p.media)} for p in shown},
|
|
}
|
|
|
|
|
|
# ── calling a waiter from a tablet at a table (5.7b) ──────────────────────────
|
|
|
|
def _table(db, cfg):
|
|
from models.table import Table
|
|
t = db.get(Table, cfg["table"]) if cfg.get("table") else None
|
|
return t if t is not None and t.is_active else None
|
|
|
|
|
|
def _label(table) -> str:
|
|
from services.table_qr import label
|
|
return label(table)
|
|
|
|
|
|
def _waiters(db, table) -> list[int]:
|
|
"""The table's waiters: its open order's, else the waiters whose zone covers the table."""
|
|
from models.order import Order
|
|
from services.qr_orders import waiters_for
|
|
order = db.query(Order).filter(Order.table_id == table.id, Order.status.in_(("open", "partially_paid", "paid"))).first()
|
|
|
|
class _NoOrder:
|
|
waiters = []
|
|
return waiters_for(db, order or _NoOrder(), table)
|
|
|
|
|
|
@router.post("/call")
|
|
def call_waiter(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
|
|
"""A guest at the table asks for a waiter. The message reaches the table's waiters' phones."""
|
|
from core.access.queries import holders_filter
|
|
from core.i18n import t, venue_language
|
|
from models.user import User
|
|
from routers.kds import _save_and_broadcast_message
|
|
cfg = _config(dev)
|
|
table = _table(db, cfg)
|
|
if table is None or not cfg.get("call_waiter"):
|
|
raise XeniaError("menu_tablet.no_table")
|
|
now = time.monotonic()
|
|
with _lock:
|
|
last = _calls.get(dev.id)
|
|
if last is not None and now - last < CALL_EVERY_S:
|
|
raise XeniaError("menu_tablet.call_too_soon", seconds=int(CALL_EVERY_S - (now - last)) + 1)
|
|
_calls[dev.id] = now
|
|
sender = db.query(User).filter(holders_filter("core.dashboard.access")).first()
|
|
lang = venue_language()
|
|
waiters = _waiters(db, table)
|
|
_save_and_broadcast_message(db, sender.id if sender else 1, t("tablet.call_message", lang, table=_label(table)), waiters,
|
|
"table_call", t("tablet.sender", lang), table_ids=[table.id])
|
|
return {"table": {"id": table.id, "name": _label(table)}, "waiters": len(waiters), "again_in": CALL_EVERY_S}
|
|
|
|
|
|
def reset_calls() -> None:
|
|
with _lock:
|
|
_calls.clear()
|