feat(backend): the menu tablet's menu (platform-v2 step 5.7a)

GET /api/menu-tablet/menu for a paired menu tablet: categories in the
catalogue's order (sub-categories after their parent, one category and its
sub-categories when the tablet is set so), each with its products in its own
order (a product in several categories shows in each), the products once with
name, description, tags, photo, the price of the tablet's sales point (or none)
and availability; sold-out hidden when set; the venue's name and the tablet's
settings. Device config: view, photos, descriptions, group, theme, prices of,
sold out, category, search, languages, idle reset (texts in both languages).
Menu changes send menu_tablet.changed to every tablet (main.py, with signage).
tests: test_menu_tablet.py (4); 531 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 23:44:42 +02:00
co-authored by Claude Opus 5.5
parent 6c982e3139
commit 2a6640fe5c
6 changed files with 397 additions and 6 deletions
+3 -1
View File
@@ -112,12 +112,14 @@ async def _menu_change_push(request, call_next):
def _signage_menu_changed() -> None:
"""The signage screens showing a menu board read it again (plan step 5.4b)."""
"""The signage screens showing a menu board (5.4b) and the menu tablets (5.7a) read their menu again."""
try:
from routers.menu_tablet import menu_changed as tablet_menu_changed
from routers.signage import menu_changed as signage_menu_changed
db = SessionLocal()
try:
signage_menu_changed(db)
tablet_menu_changed(db) # the menu tablets read their menu again (5.7a)
finally:
db.close()
except Exception as e: # never breaks the request that changed the menu
+21 -3
View File
@@ -1,11 +1,13 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import DeviceApp, Limit, Module, Perm
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
POINTS = ('in_store', 'in_store_takeaway', 'qr_table', 'online_takeaway', 'online_delivery', 'online_preorder', 'none')
MODULE = Module(
key='menu_tablet',
kind='app',
name='Menu tablet',
description='Self-service catalogue on a tablet (phase 5).',
description="The venue's menu on a tablet: a quick price check for staff and a menu for guests (plan step 5.7a).",
depends=('catalog',),
permissions=(
Perm('menu_tablet.manage', 'Set up menu tablets', roles=('owner', 'store_manager')),
@@ -13,5 +15,21 @@ MODULE = Module(
limits=(
Limit('devices', 'Number of menu tablets', free=0, licensed_default=1),
),
device_app=DeviceApp(login_modes=('none',), scope=()),
routers=(
Mount('routers.menu_tablet', '/api/menu-tablet'),
),
# 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'),
ConfigField('photos', 'bool', default=True, group='look'),
ConfigField('descriptions', 'bool', default=True, group='look'),
ConfigField('group', 'bool', default=True, group='look'),
ConfigField('theme', 'enum', default='light', choices=('light', 'dark'), group='look'),
ConfigField('sales_point', 'enum', default='in_store', choices=POINTS, group='menu'),
ConfigField('sold_out', 'enum', default='strike', choices=('strike', 'hide'), group='menu'),
ConfigField('category', 'ref', default=None, choices_from='categories', group='menu'),
ConfigField('search', 'bool', default=True, group='use'),
ConfigField('languages', 'enum', default='both', choices=('both', 'el', 'en'), group='use'),
ConfigField('idle_seconds', 'int', default=120, choices=(0, 30, 60, 120, 300, 600), group='use'),
)),
)
+117
View File
@@ -0,0 +1,117 @@
"""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.
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
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from core import sales_points
from core.access.deps import require_device
from database import get_db
router = APIRouter()
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()
return {
"venue": {"name": (name_row.value if name_row else "") or 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},
}
+88
View File
@@ -0,0 +1,88 @@
"""The menu tablet (plan step 5.7a): the menu for a paired tablet, categories in the catalogue's
order with their products (a product in several categories shows in each), a sales point's live
prices, sold out crossed out or hidden, one category or all; menu changes reach the tablets."""
import pytest
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
@pytest.fixture
def menu(db):
from models.product import Category, Product, ProductCategory
grill, drinks = Category(name="Grill", sort_order=0), Category(name="Drinks", sort_order=1)
db.add_all([grill, drinks])
db.flush()
pita = Category(name="Pita", sort_order=0, parent_id=grill.id)
db.add(pita)
db.flush()
def prod(name, cats, price, **kw):
p = Product(name=name, base_price=price, primary_category_id=cats[0].id, **kw)
db.add(p)
db.flush()
for i, c in enumerate(cats):
db.add(ProductCategory(product_id=p.id, category_id=c.id, sort_order=kw.get("sort_order", 0)))
return p
out = {"steak": prod("Steak", [grill], 12.0, description="Pork, 300 g", tags='["gluten-free"]', sort_order=1),
"souvlaki": prod("Souvlaki", [grill, pita], 3.5, sort_order=0),
"beer": prod("Beer", [drinks], 4.5),
"wine": prod("Wine", [drinks], 5.0, sold_at='["online_delivery"]'),
"old": prod("Old", [grill], 1.0, lifecycle_status="archived")}
db.commit()
out["cats"] = {"grill": grill.id, "drinks": drinks.id, "pita": pita.id}
return out
@pytest.fixture
def tablet(pair):
token, r = pair("menu_tablet", "Entrance")
assert r.status_code == 201, r.text
return {"h": {"X-Xenia-Device": token}, "id": r.json()["id"]}
def names(data):
return [(c["name"], [data["products"][str(i)]["name"] for i in c["products"]]) for c in data["categories"]]
def test_the_menu_on_a_tablet(client, owner_h, tablet, menu):
photo = up(client, owner_h, jpeg(800, 600)).json()
client.put(f"/api/products/{menu['steak'].id}", headers=owner_h, json={"media_id": photo["id"]})
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert names(data) == [("Grill", ["Souvlaki", "Steak"]), ("Pita", ["Souvlaki"]), ("Drinks", ["Beer"])] # Wine: delivery only
assert [c["depth"] for c in data["categories"]] == [0, 1, 0]
steak = data["products"][str(menu["steak"].id)]
assert (steak["price"], steak["description"], steak["tags"], steak["image"]["card"]) == (12.0, "Pork, 300 g", ["gluten-free"], photo["urls"]["card"])
assert data["config"]["view"] == "expanded" and data["config"]["search"] is True
def test_the_tablets_settings_change_the_menu(client, owner_h, tablet, menu, db):
menu["beer"].is_available = False
db.commit()
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert data["products"][str(menu["beer"].id)]["available"] is False
cfg = {"sold_out": "hide", "category": menu["cats"]["grill"], "sales_point": "none", "view": "full"}
assert client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": cfg}).status_code == 200
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert names(data) == [("Grill", ["Souvlaki", "Steak"]), ("Pita", ["Souvlaki"])]
assert {p["price"] for p in data["products"].values()} == {None} and data["config"]["view"] == "full"
client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"sales_point": "online_delivery"}})
data = client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()
assert names(data)[0][0] == "Grill" and None not in {p["price"] for p in data["products"].values()} # prices again, still only Grill
assert err(client.patch(f"/api/devices/{tablet['id']}", headers=owner_h, json={"config": {"view": "huge"}})) == "validation.device_config"
def test_menu_changes_reach_the_tablets(client, owner_h, tablet, menu, db, monkeypatch):
import routers.menu_tablet as mt
sent = []
monkeypatch.setattr("services.ws_bus.broadcast_sync", lambda kind, data, **kw: sent.append((kind, kw.get("device_ids"))))
mt.menu_changed(db)
assert sent == [("menu_tablet.changed", [tablet["id"]])]
client.put(f"/api/products/{menu['steak'].id}", headers=owner_h, json={"base_price": 13.5})
assert client.get("/api/menu-tablet/menu", headers=tablet["h"]).json()["products"][str(menu["steak"].id)]["price"] == 13.5
def test_only_menu_tablets(client, pair):
token, _ = pair("kds", "Kitchen")
assert err(client.get("/api/menu-tablet/menu", headers={"X-Xenia-Device": token})) == "device.out_of_scope"
assert err(client.get("/api/menu-tablet/menu")) == "device.not_paired"
+84 -1
View File
@@ -272,12 +272,95 @@
},
"menu_tablet": {
"name": "Tablet μενού",
"description": "Κατάλογος αυτοεξυπηρέτησης σε tablet (έρχεται σύντομα).",
"description": "Το μενού του καταστήματος σε tablet: γρήγορος έλεγχος τιμών για το προσωπικό και μενού για τους πελάτες.",
"limits": {
"devices": "Tablet μενού"
},
"permissions": {
"manage": "Ρύθμιση των tablet μενού"
},
"config_groups": {
"look": "Εμφάνιση",
"menu": "Μενού",
"use": "Χρήση"
},
"config": {
"view": {
"label": "Προβολή",
"hint": "Συμπαγής: πυκνή λίστα. Αναλυτική: με μικρή φωτογραφία και περιγραφή. Πλήρης: μεγάλες κάρτες.",
"choices": {
"compact": "Συμπαγής",
"expanded": "Αναλυτική",
"full": "Πλήρης"
}
},
"photos": {
"label": "Φωτογραφίες"
},
"descriptions": {
"label": "Περιγραφές"
},
"group": {
"label": "Ομαδοποίηση ανά κατηγορία",
"hint": "Όχι: μία λίστα με όλα τα προϊόντα (αλφαβητικά)."
},
"theme": {
"label": "Χρώματα",
"choices": {
"light": "Ανοιχτά",
"dark": "Σκούρα"
}
},
"sales_point": {
"label": "Τιμές για",
"hint": "Ποιες τιμές δείχνει.",
"choices": {
"in_store": "Στο κατάστημα",
"in_store_takeaway": "Πακέτο στο ταμείο",
"qr_table": "QR μενού στο τραπέζι",
"online_takeaway": "Online, παραλαβή",
"online_delivery": "Online, διανομή",
"online_preorder": "Online, με κράτηση",
"none": "Χωρίς τιμές"
}
},
"sold_out": {
"label": "Εξαντλημένα",
"choices": {
"strike": "Διαγραμμένα",
"hide": "Κρυμμένα"
}
},
"category": {
"label": "Μόνο αυτή η κατηγορία",
"hint": "Με τις υποκατηγορίες της.",
"none": "Όλο το μενού"
},
"search": {
"label": "Αναζήτηση",
"hint": "Πεδίο αναζήτησης (βολικό για γρήγορο έλεγχο τιμής)."
},
"languages": {
"label": "Γλώσσες",
"hint": "Τα κείμενα του tablet· τα ονόματα των προϊόντων είναι όπως στο μενού.",
"choices": {
"both": "Ελληνικά και Αγγλικά (διαλέγει ο πελάτης)",
"el": "Ελληνικά",
"en": "Αγγλικά"
}
},
"idle_seconds": {
"label": "Επιστροφή στην αρχή μετά από",
"hint": "Δευτερόλεπτα χωρίς άγγιγμα.",
"choices": {
"0": "Ποτέ",
"30": "30 δ",
"60": "1 λεπτό",
"120": "2 λεπτά",
"300": "5 λεπτά",
"600": "10 λεπτά"
}
}
}
},
"notes": {
+84 -1
View File
@@ -272,12 +272,95 @@
},
"menu_tablet": {
"name": "Menu tablet",
"description": "A self-service catalogue on a tablet (coming soon).",
"description": "The venue's menu on a tablet: a quick price check for staff and a menu for guests.",
"limits": {
"devices": "Menu tablets"
},
"permissions": {
"manage": "Set up menu tablets"
},
"config_groups": {
"look": "Look",
"menu": "Menu",
"use": "Use"
},
"config": {
"view": {
"label": "View",
"hint": "Compact: a dense list. Expanded: with a small photo and the description. Full: big cards.",
"choices": {
"compact": "Compact",
"expanded": "Expanded",
"full": "Full"
}
},
"photos": {
"label": "Photos"
},
"descriptions": {
"label": "Descriptions"
},
"group": {
"label": "Group by category",
"hint": "Off: one list of every product (A to Z)."
},
"theme": {
"label": "Colours",
"choices": {
"light": "Light",
"dark": "Dark"
}
},
"sales_point": {
"label": "Prices of",
"hint": "Whose prices it shows.",
"choices": {
"in_store": "In the shop",
"in_store_takeaway": "Takeaway at the counter",
"qr_table": "QR menu at the table",
"online_takeaway": "Online, takeaway",
"online_delivery": "Online, delivery",
"online_preorder": "Online, with a booking",
"none": "No prices"
}
},
"sold_out": {
"label": "Sold-out products",
"choices": {
"strike": "Crossed out",
"hide": "Hidden"
}
},
"category": {
"label": "Only this category",
"hint": "With its sub-categories.",
"none": "The whole menu"
},
"search": {
"label": "Search",
"hint": "A search box (handy for a quick price check)."
},
"languages": {
"label": "Languages",
"hint": "The tablet's own texts; product names are as in the menu.",
"choices": {
"both": "Greek and English (the guest picks)",
"el": "Greek",
"en": "English"
}
},
"idle_seconds": {
"label": "Back to the start after",
"hint": "Seconds without a touch.",
"choices": {
"0": "Never",
"30": "30 s",
"60": "1 min",
"120": "2 min",
"300": "5 min",
"600": "10 min"
}
}
}
},
"notes": {