feat(signage): stacks, menu and text widgets, widget order (owner review 2)

- Stacks: horizontal / vertical, 2-6 parts with % shares; each part shows
  a widget, a stack one level deep, or a whole Slides-library slide
- Menu widget (a board's list in its box), text widget, weather for
  tomorrow / the day after and in picture / degrees / both styles
- Widgets' order (arrows, drag with a drop line), drawn in list order;
  arrow keys move the picked widget from its card too
- Server: extras by widget path (QR links, menus, embedded slides),
  POST /preview/slide, resolve(keep_hidden) so hidden products stay
  greyed in the editor's list; screens told when an embedded slide changes
- Editor rows tidied: framed sliders, colours as fields, text look on one
  row, Switch boxed toggles from its whole frame

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 09:44:23 +02:00
co-authored by Claude Opus 5.5
parent 83551714f7
commit 1b993e4573
23 changed files with 1231 additions and 377 deletions
+216 -65
View File
@@ -71,10 +71,59 @@ class Background(_Strict):
fit: Literal["cover", "contain"] = "cover"
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"]
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack"]
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"]
class MenuList(_Strict):
"""What a menu board lists and how its lines look (5.4b): services/signage_menu.py resolves it.
A menu slide (MenuContent) adds its background, widgets and width; a menu widget (2026-11-21)
carries one as its `board`."""
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"
language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed
# pages (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)
@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
class Box(_Strict):
"""Where a widget moved by hand sits (2026-11-21): % of the slide's width / height."""
x: float = Field(ge=0, le=100)
@@ -92,9 +141,28 @@ class Box(_Strict):
return self
class Cell(_Strict):
"""A part of a stack (2026-11-21): its share of the stack (the parts' shares are weights; the
editor keeps them adding up to 100) and what it shows: a widget (another stack too, one level
deep) or a slide of the Slides library, drawn whole inside the part; or nothing."""
share: float = Field(default=50, ge=1, le=100)
widget: Optional["Widget"] = None
slide_id: Optional[int] = None
@model_validator(mode="after")
def _one(self):
if self.widget is not None and self.slide_id is not None:
raise ValueError("a part shows a widget or a slide, not both")
self.share = round(self.share, 2)
return self
class Widget(_Strict):
"""Something small on a menu, text or blank slide (5.4c), in a corner or a bar, or (moved and
sized by hand on the editor's preview, 2026-11-21) in its own box: position and size "custom"."""
sized by hand on the editor's preview, 2026-11-21) in its own box: position and size "custom".
2026-11-21: a text of its own, a menu (a board's list in the widget's place) and stacks: parts
side by side (direction "row") or one over the other ("column"), each showing a widget or a
whole library slide."""
kind: WidgetKind
position: Position = "top-right"
size: Literal["small", "medium", "large", "custom"] = "medium"
@@ -107,7 +175,12 @@ class Widget(_Strict):
qr_target: Literal["ordering", "menu", "custom"] = "ordering"
qr_url: Optional[str] = Field(default=None, max_length=300)
qr_caption: Optional[str] = Field(default=None, max_length=80)
weather_days: int = Field(default=1, ge=1, le=3) # today, or today + the next days
weather_days: int = Field(default=1, ge=1, le=3) # how many days, from weather_from
weather_from: int = Field(default=0, ge=0, le=2) # 0 today (now), 1 tomorrow, 2 the day after
weather_style: Literal["both", "icon", "text"] = "both" # picture and degrees, the picture, the degrees
board: Optional[MenuList] = None # menu: what it lists and how
direction: Literal["row", "column"] = "row" # stack: side by side / one over the other
cells: List[Cell] = Field(default_factory=list, max_length=6)
@model_validator(mode="after")
def _place(self):
@@ -121,6 +194,20 @@ class Widget(_Strict):
self.size = "medium"
return self
@model_validator(mode="after")
def _kind_fields(self):
if self.kind == "stack" and not self.cells:
raise ValueError("a stack has at least one part")
if self.kind != "stack":
self.cells = []
if self.kind == "menu" and self.board is None:
self.board = MenuList(select="all", columns=1)
if self.kind != "menu":
self.board = None
if self.weather_from + self.weather_days > 3:
self.weather_days = 3 - self.weather_from # the forecast has three days
return self
@field_validator("qr_url")
@classmethod
def _url(cls, v):
@@ -131,6 +218,9 @@ class Widget(_Strict):
return v
Cell.model_rebuild()
class ImageContent(_Strict):
media_id: Optional[int] = None # a picture
fit: Literal["cover", "contain"] = "cover"
@@ -162,57 +252,15 @@ class BlankContent(_Strict):
widgets: List[Widget] = Field(default_factory=list, max_length=10)
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"]
class MenuContent(_Strict):
class MenuContent(MenuList):
"""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"
language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed
# how it's laid out (the player pages through what doesn't fit, 5.5b)
columns: int = Field(default=2, ge=1, le=3)
own order, with a sales point's live prices, and how it looks (MenuList), on its background
with its widgets."""
board_width: int = Field(default=100, ge=40, le=100) # % of the screen the list takes (2026-11-21)
board_align: Literal["left", "center", "right"] = "left" # where a narrower list sits, and its title
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)
widgets: List[Widget] = Field(default_factory=list, max_length=10)
@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, "blank": BlankContent}
Kind = Literal["menu", "image", "video", "text", "blank"]
@@ -367,6 +415,60 @@ def media_ids(value) -> list[int]:
return out
def walk_widgets(widgets, prefix: str = ""):
"""Every widget of a slide, inside stacks too, with its path ("2", "2.0", "2.1.1": the widget's
index, then its part's): → (path, widget, None), and (path, None, slide id) for a part that
shows a library slide. The editor and the player find a widget's extras by its path."""
for i, w in enumerate(widgets or []):
yield from _walk_one(w, f"{prefix}{i}")
def _walk_one(w: dict, path: str):
yield path, w, None
for j, c in enumerate(w.get("cells") or []):
cp = f"{path}.{j}"
if c.get("widget"):
yield from _walk_one(c["widget"], cp)
elif c.get("slide_id"):
yield cp, None, c["slide_id"]
def embedded_ids(content: dict) -> set:
"""The library slides a slide's stacks show."""
return {sid for _, _, sid in walk_widgets((content or {}).get("widgets")) if sid}
def _needs_menu(kind: str, content: dict) -> bool:
"""Does a slide show products (a menu board, a menu widget, a library slide inside a stack)?"""
return kind == "menu" or any((w and w.get("kind") == "menu") or sid for _, w, sid in walk_widgets((content or {}).get("widgets")))
def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0):
"""What a slide's widgets need beyond what is stored (2026-11-21), by widget path: a QR code's
link, a menu widget's products (`menu`), a part's library slide (`slide`: its kind, content,
menu and extras; slides inside it don't show further slides). → (extras, media ids they show)."""
from services.signage_menu import resolve
out, mids = {}, []
for path, w, sid in walk_widgets((content or {}).get("widgets")):
if w is not None:
if w.get("kind") == "qr":
out[path] = {"link": _qr_link(w)}
elif w.get("kind") == "menu":
out[path] = {"menu": resolve(db, w.get("board") or {}, keep_hidden=keep_hidden)}
elif depth == 0:
s = db.get(SignageSavedSlide, sid)
if s is None:
continue
inner, inner_media = extras(db, s.content or {}, depth=1)
one = {"id": s.id, "name": s.name, "kind": s.kind, "content": s.content or {}, "extras": inner,
"orientation": s.orientation}
if s.kind == "menu":
one["menu"] = resolve(db, one["content"])
out[path] = {"slide": one}
mids += media_ids(one["content"]) + inner_media
return out, mids
def _content(db, kind: str, raw: dict | None) -> dict:
"""The content as stored: typed for its kind, every media id an existing file of the right kind."""
from pydantic import ValidationError
@@ -389,9 +491,16 @@ def _content(db, kind: str, raw: dict | None) -> dict:
raise XeniaError("signage.not_a_video")
if kind != "video" and m.kind != "image":
raise XeniaError("media.not_a_picture")
pictures = [(data.get("background") or {}).get("media_id")] + [w.get("media_id") for w in data.get("widgets") or []]
found = list(walk_widgets(data.get("widgets")))
pictures = [(data.get("background") or {}).get("media_id")] + [w.get("media_id") for _, w, _ in found if w]
if any(i is not None and db.get(Media, i).kind != "image" for i in pictures):
raise XeniaError("media.not_a_picture")
for path, w, sid in found:
# a stack inside a stack, not deeper (2026-11-21)
if w and w.get("kind") == "stack" and path.count(".") > 1:
raise XeniaError("signage.content_invalid", field=f"widgets.{path}", reason="a stack goes at most one stack deep")
if sid and db.get(SignageSavedSlide, sid) is None:
raise XeniaError("signage.slide_unknown", slide_id=sid)
return data
@@ -472,10 +581,13 @@ def _playlist_out(db, p: SignagePlaylist, slides: bool = False) -> dict:
if slides:
from services.signage_menu import resolve
out["slides"] = [_slide_out(s) for s in p.slides]
more = []
for s in out["slides"]:
if s["kind"] == "menu":
s["menu"] = resolve(db, s["content"]) # the editor's preview (5.6a)
out["media"] = _media_map(db, [i for s in p.slides for i in media_ids(s.content or {})])
s["menu"] = resolve(db, s["content"], keep_hidden=True) # the editor's preview (5.6a)
s["extras"], m = extras(db, s["content"], keep_hidden=True)
more += m
out["media"] = _media_map(db, [i for s in p.slides for i in media_ids(s.content or {})] + more)
return out
@@ -539,8 +651,8 @@ def tell_all_screens(db) -> None:
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 (or as their default slide) read it again."""
playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")}
boards = {slide_key(sid) for (sid,) in db.query(SignageSavedSlide.id).filter(SignageSavedSlide.kind == "menu")}
playlists = {x.playlist_id for x in db.query(SignageSlide) if _needs_menu(x.kind, x.content)}
boards = {slide_key(x.id) for x in db.query(SignageSavedSlide) if _needs_menu(x.kind, x.content)}
if playlists or boards:
_tell([d.id for d in _screens(db) if _screen_playlists(db, d) & playlists or default_of(_screen_config(d)) in boards])
@@ -705,12 +817,29 @@ def _saved_out(s: SignageSavedSlide, db=None) -> dict:
if db is not None:
if s.kind == "menu":
from services.signage_menu import resolve
out["menu"] = resolve(db, out["content"])
out["menu"] = resolve(db, out["content"], keep_hidden=True)
out["extras"], out["extra_media"] = extras(db, out["content"], keep_hidden=True)
showing = set(_screens_showing_slide(db, s.id))
out["screens"] = [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in showing]
return out
def _saved_one(db, s: SignageSavedSlide) -> dict:
"""One library slide for the editor, with the media it shows (its own and its stacks')."""
out = _saved_out(s, db)
out["media"] = _media_map(db, media_ids(s.content or {}) + out.pop("extra_media"))
return out
def _embedding_screens(db, sid: int) -> list[int]:
"""The screens that may show a library slide inside a stack (of a playlist's slide, or of a
library slide that is a screen's default): told when it changes."""
playlists = {x.playlist_id for x in db.query(SignageSlide) if sid in embedded_ids(x.content)}
saved = {x.id for x in db.query(SignageSavedSlide) if sid in embedded_ids(x.content)}
return [d.id for d in _screens(db) if _screen_playlists(db, d) & playlists
or (not _screen_config(d).get("playlist") and _screen_config(d).get("slide") in saved)]
def _saved_name(body) -> str:
name = (body.name or "").strip()
if not name:
@@ -722,8 +851,9 @@ def _saved_name(body) -> str:
def list_saved(db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Every kept slide, with its menu resolved (the gallery's previews) and the media they show."""
rows = db.query(SignageSavedSlide).order_by(SignageSavedSlide.name, SignageSavedSlide.id).all()
return {"slides": [_saved_out(s, db) for s in rows],
"media": _media_map(db, [i for s in rows for i in media_ids(s.content or {})])}
slides = [_saved_out(s, db) for s in rows]
return {"slides": slides,
"media": _media_map(db, [i for s in rows for i in media_ids(s.content or {})] + [i for x in slides for i in x.pop("extra_media")])}
@router.post("/library", status_code=201)
@@ -739,14 +869,14 @@ def create_saved(body: SavedSlideBody, db: Session = Depends(get_db), user=Depen
db.add(s)
db.commit()
db.refresh(s)
return _saved_out(s, db)
return _saved_one(db, s)
@router.get("/library/{slide_id}")
def get_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
out = _saved_out(s, db)
out["media"] = _media_map(db, media_ids(s.content or {}))
out["media"] = _media_map(db, media_ids(s.content or {}) + out.pop("extra_media"))
return out
@@ -764,14 +894,14 @@ def update_saved(slide_id: int, body: SavedSlideBody, db: Session = Depends(get_
s.orientation = body.orientation
db.commit()
db.refresh(s)
_tell(_screens_showing_slide(db, s.id))
return _saved_out(s, db)
_tell(_screens_showing_slide(db, s.id) + _embedding_screens(db, s.id))
return _saved_one(db, s)
@router.delete("/library/{slide_id}", status_code=204)
def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
showing = _screens_showing_slide(db, s.id)
showing = _screens_showing_slide(db, s.id) + _embedding_screens(db, s.id)
for d in _screens(db):
if (d.config or {}).get("slide") == s.id:
d.config = {**(d.config or {}), "slide": None}
@@ -791,7 +921,7 @@ def duplicate_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(r
db.add(copy)
db.commit()
db.refresh(copy)
return _saved_out(copy, db)
return _saved_one(db, copy)
# ── screens ────────────────────────────────────────────────────────────────────
@@ -851,15 +981,18 @@ def _resolved(db, p: SignagePlaylist) -> dict:
"""A playlist as a screen plays it: enabled slides, transitions filled in, menus, QR links, media."""
from services.signage_menu import resolve
slides = [_slide_out(s) for s in p.slides if s.enabled]
more = []
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)
s["extras"], m = extras(db, s["content"]) # menus, library slides inside stacks, links (2026-11-21)
more += m
for w in s["content"].get("widgets") or []:
if w["kind"] == "qr":
w["link"] = _qr_link(w)
return {"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"])])}
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])] + more)}
def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict:
@@ -869,12 +1002,13 @@ def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict:
one["transition"] = one["transition"] or "fade"
if one["kind"] == "menu":
one["menu"] = resolve(db, one["content"])
one["extras"], more = extras(db, one["content"])
for w in one["content"].get("widgets") or []:
if w["kind"] == "qr":
w["link"] = _qr_link(w)
slides = [one] if s.enabled else []
return {"id": slide_key(s.id), "name": s.name, "orientation": orientation, "transition": "fade", "slides": slides,
"media": _media_map(db, media_ids(one["content"]))}
"media": _media_map(db, media_ids(one["content"]) + more)}
def _default_resolved(db, cfg: dict):
@@ -1079,9 +1213,26 @@ def preview_venue(db: Session = Depends(get_db), user=Depends(require(KEY))):
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, "weather": weather.current(db)}
class SlidePreviewBody(BaseModel):
kind: Kind
content: dict = Field(default_factory=dict)
@router.post("/preview/slide")
def preview_slide(body: SlidePreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""A slide not saved yet, as the editor's preview needs it (2026-11-21): a menu board's
products (hidden ones kept, marked), the extras of its widgets (menus, library slides inside
stacks, QR links) and the media they show."""
from services.signage_menu import resolve
content = _content(db, body.kind, body.content)
ex, more = extras(db, content, keep_hidden=True)
return {"menu": resolve(db, content, keep_hidden=True) if body.kind == "menu" else None, "extras": ex,
"media": _media_map(db, more)}
@router.post("/preview/menu")
def preview_menu(body: MenuPreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""A menu board not saved yet, resolved like a screen gets it (the editor's live preview)."""
from services.signage_menu import resolve
content = _content(db, "menu", body.content)
return {"content": content, "menu": resolve(db, content)}
return {"content": content, "menu": resolve(db, content, keep_hidden=True)}