feat(backend): signage menu boards: any products, the board's own order, live prices (platform-v2 step 5.4b)

- MenuContent: select all / whole categories (with sub-categories, live: new
  products join) / single products, exclusions; grouped by category or not,
  headings; the board's own category and product order; a sales point's
  prices or none; photos, descriptions, badges (new, chef, offer, popular,
  spicy, vegetarian, vegan); sold-out crossed out or hidden; columns, items
  per page, seconds per page, font, colours, size, background.
- services/signage_menu.resolve: the products in that order with
  customer-facing names, prices from pos_cart.unit_prices (what the counter
  charges right now), availability, card-size photos. GET /api/signage/screen
  includes each menu slide's `menu`.
- Every request that changes the menu (the online menu's paths) also sends
  signage.changed to the screens with a menu board (main.py, off the loop).
- tests: test_signage_menu.py (6); 515 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 18:38:55 +02:00
co-authored by Claude Opus 5.5
parent a2d9e55222
commit 97140b13f9
5 changed files with 307 additions and 3 deletions
+1 -1
View File
@@ -48,7 +48,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
| `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory |
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` |
| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed |
| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`) |
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
+15
View File
@@ -106,9 +106,24 @@ async def _menu_change_push(request, call_next):
from services.cloud_sync import menu_changed, request_menu_push
if menu_changed(request.method, request.url.path, response.status_code):
request_menu_push()
from starlette.concurrency import run_in_threadpool
await run_in_threadpool(_signage_menu_changed)
return response
def _signage_menu_changed() -> None:
"""The signage screens showing a menu board read it again (plan step 5.4b)."""
try:
from routers.signage import menu_changed as signage_menu_changed
db = SessionLocal()
try:
signage_menu_changed(db)
finally:
db.close()
except Exception as e: # never breaks the request that changed the menu
logger.warning("signage: menu change not sent: %s", e)
# Added last = outermost: the request id exists before any other middleware runs.
app.add_middleware(RequestContextMiddleware)
+52 -2
View File
@@ -26,7 +26,7 @@ from __future__ import annotations
import hashlib
import json
from typing import List, Literal, Optional
from typing import Dict, List, Literal, Optional
from fastapi import APIRouter, Depends, Response
from pydantic import BaseModel, ConfigDict, Field, field_validator
@@ -87,14 +87,53 @@ class TextContent(_Strict):
background: Background = Field(default_factory=Background)
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"]
class MenuContent(_Strict):
"""The menu board's look; what it lists comes with step 5.4b."""
"""A menu board (5.4b): which products (services/signage_menu.py resolves them), in the board's
own order, with a sales point's live prices, and how it looks."""
title: Optional[str] = Field(default=None, max_length=120)
# what it lists
select: Literal["all", "custom"] = "custom"
category_ids: List[int] = Field(default_factory=list, max_length=200) # whole categories (live)
product_ids: List[int] = Field(default_factory=list, max_length=1000) # single products
exclude_ids: List[int] = Field(default_factory=list, max_length=1000)
group_by_category: bool = True
category_titles: bool = True # a heading over each group
category_order: List[int] = Field(default_factory=list, max_length=200) # the board's own order
product_order: List[int] = Field(default_factory=list, max_length=1000)
# what each line shows
sales_point: Optional[str] = "in_store" # whose prices; None = no prices
show_photos: bool = False
show_descriptions: bool = False
badges: Dict[str, Badge] = Field(default_factory=dict) # product id → badge
sold_out: Literal["strike", "hide"] = "strike"
# how it's laid out (the player pages through what doesn't fit, 5.5b)
columns: int = Field(default=2, ge=1, le=3)
page_size: Optional[int] = Field(default=None, ge=3, le=60) # items per page; None = as many as fit
page_seconds: int = Field(default=10, ge=3, le=120)
font: Font = "sans"
text_colour: str = Field(default="#ffffff", pattern=HEX)
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # prices, headings, badges
text_size: int = Field(default=100, ge=50, le=250)
background: Background = Field(default_factory=Background)
@field_validator("sales_point")
@classmethod
def _point(cls, v):
from core import sales_points
if v is not None and v not in sales_points.ALL:
raise ValueError(f"one of {', '.join(sales_points.ALL)}")
return v
@field_validator("badges")
@classmethod
def _badge_keys(cls, v):
if any(not k.isdigit() for k in v):
raise ValueError("badges are keyed by product id")
return v
CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent}
Kind = Literal["menu", "image", "video", "text"]
@@ -294,6 +333,14 @@ def _uses(db, media_id: int) -> list:
media_store.register_usage("signage_slide", _uses)
def menu_changed(db) -> None:
"""Products, categories or prices changed (main.py, the same requests that push the online menu):
the screens with a menu board on their playlist read it again."""
playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")}
if playlists:
_tell([d.id for d in _screens(db) if _screen_config(d).get("playlist") in playlists])
# ── playlists ──────────────────────────────────────────────────────────────────
@router.get("/playlists")
@@ -479,9 +526,12 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
playlist = None
if p is not None:
from services.signage_menu import resolve
slides = [_slide_out(s) for s in p.slides if s.enabled]
for s in slides:
s["transition"] = s["transition"] or p.transition
if s["kind"] == "menu":
s["menu"] = resolve(db, s["content"]) # live prices and availability (5.4b)
playlist = {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides,
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])}
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
+99
View File
@@ -0,0 +1,99 @@
"""The menu board's content (plan step 5.4b): which products a menu slide lists, in its own order,
with live prices and availability.
A menu slide picks products three ways, combined (routers/signage.py MenuContent):
select = "all" every active product
category_ids whole categories (and their sub-categories): products added to them later join
product_ids single products, from any category
minus `exclude_ids`. System products (the delivery fee line) and archived products never show.
With a `sales_point`, products not sold there are left out and prices are that sales point's,
right now (services/pos_cart.unit_prices, the same rules the counter uses); without one there
are no prices.
The order is the board's own (`category_order`, `product_order`), never the waiters' or the
counter's: listed ids first in that order, the rest after them in the catalogue's order.
"""
from __future__ import annotations
from core import sales_points
def _descendants(cats_by_parent: dict, roots: list[int]) -> set[int]:
out, stack = set(), list(roots)
while stack:
c = stack.pop()
if c in out:
continue
out.add(c)
stack.extend(cats_by_parent.get(c, []))
return out
def _rank(order: list[int]):
pos = {v: i for i, v in enumerate(order or [])}
return lambda v: (0, pos[v]) if v in pos else (1, 0)
def resolve(db, content: dict, now=None) -> dict:
"""{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide."""
from models.product import Category, Product, ProductCategory
from services import media as media_store
from services.pos_cart import unit_prices
cats = db.query(Category).all()
by_id = {c.id: c for c in cats}
by_parent: dict = {}
for c in cats:
by_parent.setdefault(c.parent_id, []).append(c.id)
q = db.query(Product).filter(Product.lifecycle_status == "active", Product.system_key.is_(None))
if content.get("select") == "all":
products = q.all()
else:
wanted_cats = _descendants(by_parent, [i for i in content.get("category_ids") or [] if i in by_id])
in_cats = {pid for (pid,) in db.query(ProductCategory.product_id).filter(ProductCategory.category_id.in_(wanted_cats))} if wanted_cats else set()
ids = in_cats | set(content.get("product_ids") or [])
products = q.filter(Product.id.in_(ids)).all() if ids else []
excluded = set(content.get("exclude_ids") or [])
products = [p for p in products if p.id not in excluded]
point = content.get("sales_point")
if point:
products = [p for p in products if sales_points.is_sold_at(p, point)]
if content.get("sold_out") == "hide":
products = [p for p in products if p.is_available]
# the catalogue's order inside each product's main category (the fallback after the board's own)
member_order = {(m.category_id, m.product_id): m.sort_order for m in db.query(ProductCategory).all()}
cat_rank = _rank(content.get("category_order"))
prod_rank = _rank(content.get("product_order"))
def cat_key(cid):
c = by_id.get(cid)
return (cat_rank(cid), c.sort_order if c else 0, c.name.lower() if c else "")
def prod_key(p):
return (prod_rank(p.id), member_order.get((p.primary_category_id, p.id), p.sort_order or 0), (p.name or "").lower())
prices = dict(zip([p.id for p in products], unit_prices(db, products, point, now=now))) if point and products else {}
badges = {int(k): v for k, v in (content.get("badges") or {}).items() if str(k).isdigit()}
def item(p):
image = media_store.image_of(p.media) if content.get("show_photos") else None
return {"id": p.id, "name": p.digital_name or p.name,
"description": (p.digital_description or p.description or None) if content.get("show_descriptions") else None,
"price": round(prices[p.id], 2) if p.id in prices else None,
"available": bool(p.is_available), "image": image["card"] if image else None,
"badge": badges.get(p.id)}
if content.get("group_by_category", True):
groups: dict = {}
for p in products:
groups.setdefault(p.primary_category_id, []).append(p)
out = [{"category": {"id": cid, "name": by_id[cid].name} if cid in by_id else None,
"items": [item(p) for p in sorted(ps, key=prod_key)]}
for cid, ps in sorted(groups.items(), key=lambda kv: cat_key(kv[0]))]
else:
ordered = sorted(products, key=lambda p: (prod_rank(p.id), cat_key(p.primary_category_id), prod_key(p)))
out = [{"category": None, "items": [item(p) for p in ordered]}] if ordered else []
return {"groups": out, "count": len(products)}
+140
View File
@@ -0,0 +1,140 @@
"""The menu board's content (plan step 5.4b): any products (all, whole categories that stay live,
single products), grouped or not, in the board's own order, with a sales point's live prices,
sold-out products crossed out or hidden; menu changes reach the screens showing a menu board."""
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)
from tests.test_signage import playlist, slide
@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, cat, price, order, **kw):
p = Product(name=name, base_price=price, primary_category_id=cat.id, sort_order=order, **kw)
db.add(p)
db.flush()
db.add(ProductCategory(product_id=p.id, category_id=cat.id, sort_order=order))
return p
out = {
"souvlaki": prod("Souvlaki", grill, 3.5, 0, description="Pork, on a stick"),
"steak": prod("Steak", grill, 12.0, 1),
"gyros": prod("Gyros pita", pita, 4.0, 0),
"beer": prod("Beer", drinks, 4.5, 0),
"wine": prod("Wine", drinks, 5.0, 1, sold_at='["online_delivery"]'),
"old": prod("Old dish", grill, 9.0, 2, lifecycle_status="archived"),
}
db.commit()
out["cats"] = {"grill": grill.id, "drinks": drinks.id, "pita": pita.id}
return out
@pytest.fixture
def tv(client, owner_h, pair):
token, r = pair("signage", "TV")
p = playlist(client, owner_h, "Menu")
client.put(f"/api/signage/screens/{r.json()['id']}", headers=owner_h, json={"playlist_id": p["id"]})
return {"h": {"X-Xenia-Device": token}, "id": r.json()["id"], "playlist": p["id"]}
def board(client, owner_h, tv, **content):
s = slide(client, owner_h, tv["playlist"], "menu", content=content)
got = client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"]
return s, next(x for x in got if x["id"] == s["id"])["menu"]
def names(menu):
return [[g["category"]["name"] if g["category"] else None, [i["name"] for i in g["items"]]] for g in menu["groups"]]
def test_whole_categories_stay_live(client, owner_h, tv, menu, db):
s, m = board(client, owner_h, tv, category_ids=[menu["cats"]["grill"]])
assert names(m) == [["Grill", ["Souvlaki", "Steak"]], ["Pita", ["Gyros pita"]]] # sub-categories too, never archived
from models.product import Product, ProductCategory
lamb = Product(name="Lamb chops", base_price=14.0, primary_category_id=menu["cats"]["grill"], sort_order=3)
db.add(lamb)
db.flush()
db.add(ProductCategory(product_id=lamb.id, category_id=menu["cats"]["grill"], sort_order=3))
db.commit()
m = next(x for x in client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"] if x["id"] == s["id"])["menu"]
assert names(m)[0] == ["Grill", ["Souvlaki", "Steak", "Lamb chops"]] and m["count"] == 4
def test_any_products_and_exclusions(client, owner_h, tv, menu):
_, m = board(client, owner_h, tv, product_ids=[menu["beer"].id, menu["souvlaki"].id])
assert names(m) == [["Grill", ["Souvlaki"]], ["Drinks", ["Beer"]]]
_, m = board(client, owner_h, tv, select="all", exclude_ids=[menu["steak"].id])
# everything active at the shop's prices: Wine is sold only for delivery, Steak excluded, never archived
assert sorted(i["name"] for g in m["groups"] for i in g["items"]) == ["Beer", "Gyros pita", "Souvlaki"]
_, m = board(client, owner_h, tv, select="all", sales_point="online_delivery")
assert "Wine" in [i["name"] for g in m["groups"] for i in g["items"]]
def test_the_boards_own_order(client, owner_h, tv, menu):
c = menu["cats"]
_, m = board(client, owner_h, tv, category_ids=[c["grill"], c["drinks"]], category_order=[c["drinks"], c["pita"]],
product_order=[menu["steak"].id])
assert names(m) == [["Drinks", ["Beer"]], ["Pita", ["Gyros pita"]], ["Grill", ["Steak", "Souvlaki"]]]
_, m = board(client, owner_h, tv, category_ids=[c["grill"], c["drinks"]], group_by_category=False,
product_order=[menu["beer"].id, menu["gyros"].id])
assert names(m) == [[None, ["Beer", "Gyros pita", "Souvlaki", "Steak"]]]
def test_prices_sold_out_badges_photos(client, owner_h, tv, menu, db):
photo = up(client, owner_h, jpeg(800, 600)).json()
client.put(f"/api/products/{menu['souvlaki'].id}", headers=owner_h, json={"media_id": photo["id"]})
menu["steak"].is_available = False
db.commit()
content = dict(category_ids=[menu["cats"]["grill"]], show_photos=True, show_descriptions=True,
badges={str(menu["souvlaki"].id): "chef"})
_, m = board(client, owner_h, tv, **content)
souv, steak = m["groups"][0]["items"]
assert (souv["price"], souv["badge"], souv["description"], souv["image"]) == (3.5, "chef", "Pork, on a stick", photo["urls"]["card"])
assert steak["available"] is False and steak["price"] == 12.0 and steak["image"] is None
_, m = board(client, owner_h, tv, **content, sold_out="hide")
assert [i["name"] for i in m["groups"][0]["items"]] == ["Souvlaki"]
_, m = board(client, owner_h, tv, category_ids=[menu["cats"]["grill"]], sales_point=None)
assert {i["price"] for g in m["groups"] for i in g["items"]} == {None}
# a price change shows on the next read, at the price the counter charges
client.put(f"/api/products/{menu['souvlaki'].id}", headers=owner_h, json={"base_price": 3.8})
_, m = board(client, owner_h, tv, category_ids=[menu["cats"]["grill"]])
assert m["groups"][0]["items"][0]["price"] == 3.8
def test_menu_changes_reach_the_screens_with_a_menu_board(client, owner_h, menu, pair, db, monkeypatch):
import main
import routers.signage as sg
calls = []
monkeypatch.setattr(main, "_signage_menu_changed", lambda: calls.append(1))
client.put(f"/api/products/{menu['beer'].id}", headers=owner_h, json={"base_price": 4.9})
assert calls == [1] # every request that changes the menu
client.get("/api/products/", headers=owner_h)
assert calls == [1]
# who hears it: only the screens whose playlist has a menu board
t1, r1 = pair("signage", "Menu TV")
t2, r2 = pair("signage", "Promo TV")
with_menu, without = playlist(client, owner_h, "With menu"), playlist(client, owner_h, "Pictures")
slide(client, owner_h, with_menu["id"], "menu", content={"select": "all"})
slide(client, owner_h, without["id"], "text", content={"title": "Hi"})
client.put(f"/api/signage/screens/{r1.json()['id']}", headers=owner_h, json={"playlist_id": with_menu["id"]})
client.put(f"/api/signage/screens/{r2.json()['id']}", headers=owner_h, json={"playlist_id": without["id"]})
sent = []
monkeypatch.setattr(sg, "broadcast_sync", lambda kind, data, **kw: sent.append((kind, kw.get("device_ids"))))
sg.menu_changed(db)
assert sent == [("signage.changed", [r1.json()["id"]])]
def test_menu_settings_are_checked(client, owner_h, tv):
url = f"/api/signage/playlists/{tv['playlist']}/slides"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"sales_point": "moon"}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"x": "new"}}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"3": "shiny"}}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"columns": 4}})) == "signage.content_invalid"