Files
xenia-pos-local/local_backend/routers/menu_tablet.py
T
bonaminandClaude Opus 5.5 e395d99704 feat(menu): the menu in English and Greek (platform-v2 step 6.4, D-29)
- products.translations / categories.translations (Alembic 0033, core/menu_languages.py: el + en,
  name / description / quick options by their base name; catalog.translation). Empty = the text
  as typed; no machine translation (owner).
- In the manager's product editor ("In English" / "In Greek", quick extras), the category dialog,
  and a menu board's Language (signage MenuContent.language).
- Customer screens only: cloud snapshot names / descriptions per language (C-2), the menu tablet's
  EL / EN switch the names (localize), signage boards; tickets, KDS, counter, phones keep the base.
- Catalogue bundles carry translations; @xenia/access menuLanguages.js (a backend test compares).
- e2e: manager (the other language saved), menu tablet (EN / EL names), QR table (English on
  the menu, the base name on the kitchen's order, Greek page as typed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:47:03 +02:00

186 lines
7.9 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 allergens, menu_languages, 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, "names": menu_languages.texts(c.name, menu_languages.of(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),
"allergens": allergens.of(p), **menu_languages.product_texts(p, customer=False),
"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()