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)}
+9 -5
View File
@@ -34,8 +34,11 @@ def _rank(order: list[int]):
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."""
def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> dict:
"""{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide.
keep_hidden (the editor's list, 2026-11-21): products hidden from the board (`exclude_ids`) stay
in the list marked `"hidden": true` (greyed there, shown again with a click); `count` and the
TV leave them out."""
from models.product import Category, Product, ProductCategory
from services import media as media_store
from services.pos_cart import unit_prices
@@ -55,7 +58,8 @@ def resolve(db, content: dict, now=None) -> dict:
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]
if not keep_hidden:
products = [p for p in products if p.id not in excluded]
point = content.get("sales_point")
if point:
@@ -89,7 +93,7 @@ def resolve(db, content: dict, now=None) -> dict:
"description": text(p, p.digital_description or p.description or None, "description") 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)}
"badge": badges.get(p.id), **({"hidden": True} if p.id in excluded else {})}
if content.get("group_by_category", True):
groups: dict = {}
@@ -101,4 +105,4 @@ def resolve(db, content: dict, now=None) -> dict:
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)}
return {"groups": out, "count": len([p for p in products if p.id not in excluded])}
@@ -0,0 +1,97 @@
"""Signage widgets, owner review 2026-11-21: a text of its own, a menu widget (a board's list in the
widget's place), stacks (parts side by side or one over the other, each with a widget, another
stack one level deep, or a whole library slide), weather for tomorrow / the day after and in three
styles; products hidden from a board stay in the editor's list (greyed), never on the TV."""
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
from tests.test_signage_menu import menu, names # noqa: F401 (fixture + helper)
BOX = {"x": 5, "y": 10, "w": 90, "h": 80}
def stack(*cells, direction="row"):
return {"kind": "stack", "direction": direction, "position": "custom", "box": BOX, "cells": list(cells)}
def keep(client, h, **body):
r = client.post("/api/signage/library", headers=h, json={"name": "Promo", "kind": "text", **body})
assert r.status_code == 201, r.text
return r.json()
def test_text_weather_and_stack_widgets_are_checked(client, owner_h):
p = playlist(client, owner_h)
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
{"kind": "text", "text": "Happy hour 18-20"},
{"kind": "weather", "weather_from": 1, "weather_days": 3, "weather_style": "icon"},
stack({"share": 30, "widget": {"kind": "clock"}}, {"share": 70, "widget": stack({"share": 50}, {"share": 50}, direction="column")}),
]})
ws = s["content"]["widgets"]
assert ws[0]["text"] == "Happy hour 18-20"
assert ws[1]["weather_from"] == 1 and ws[1]["weather_days"] == 2 and ws[1]["weather_style"] == "icon" # the forecast has 3 days
assert [c["share"] for c in ws[2]["cells"]] == [30, 70] and ws[2]["cells"][1]["widget"]["direction"] == "column"
assert ws[0]["cells"] == [] and ws[0]["board"] is None
url = f"/api/signage/playlists/{p['id']}/slides"
bad = [
stack(), # no parts
stack({"share": 50, "widget": {"kind": "clock"}, "slide_id": 1}), # a widget and a slide
stack({"share": 50, "widget": stack({"share": 50, "widget": stack({"share": 100})})}), # three stacks deep
stack(*[{"share": 10}] * 7), # more than 6 parts
]
for w in bad:
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [w]}})) == "signage.content_invalid", w
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [stack({"share": 100, "slide_id": 999})]}})) == "signage.slide_unknown"
def test_a_stack_shows_a_library_slide_and_a_menu_widget(client, owner_h, screens, sent, menu, db):
promo = keep(client, owner_h, content={"title": "Fresh fish", "widgets": [{"kind": "qr", "position": "bottom-right"}]})
p = playlist(client, owner_h, "Split")
tv = screens[1]
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
board = {"kind": "menu", "board": {"category_ids": [menu["cats"]["drinks"]], "exclude_ids": [menu["beer"].id], "columns": 1}}
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
{"kind": "qr", "position": "top-left"},
stack({"share": 25, "widget": board}, {"share": 75, "slide_id": promo["id"]}),
]})
# the screen: extras by widget path (the QR's link, the menu's products, the slide inside the part)
got = client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]
ex = got["extras"]
assert ex["0"]["link"] and got["content"]["widgets"][0]["link"] == ex["0"]["link"]
assert names(ex["1.0"]["menu"]) == [] and ex["1.0"]["menu"]["count"] == 0 # Beer hidden; Wine: delivery only
inner = ex["1.1"]["slide"]
assert inner["id"] == promo["id"] and inner["kind"] == "text" and inner["content"]["title"] == "Fresh fish"
assert inner["extras"]["0"]["link"] # its own widgets' extras
# the editor: the hidden product stays in the list, marked
ed = client.get(f"/api/signage/playlists/{p['id']}", headers=owner_h).json()["slides"][0]["extras"]["1.0"]["menu"]
assert [(i["name"], i.get("hidden", False)) for g in ed["groups"] for i in g["items"]] == [("Beer", True)] and ed["count"] == 0
# a change to the library slide reaches the screens that show it inside a stack
sent.clear()
client.put(f"/api/signage/library/{promo['id']}", headers=owner_h, json={"content": {"title": "Fresh octopus"}})
assert sent == [("signage.changed", [tv["id"]])]
assert client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]["extras"]["1.1"]["slide"]["content"]["title"] == "Fresh octopus"
# products change: a slide with a menu widget is told too
import routers.signage as sg
sent.clear()
sg.menu_changed(db)
assert sent == [("signage.changed", [tv["id"]])]
# the library slide deleted: the part shows nothing, the screen is told
sent.clear()
client.delete(f"/api/signage/library/{promo['id']}", headers=owner_h)
assert sent == [("signage.changed", [tv["id"]])]
assert "1.1" not in client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]["extras"]
assert s["content"]["widgets"][1]["cells"][1]["slide_id"] == promo["id"]
def test_the_editor_previews_any_slide(client, owner_h, menu):
promo = keep(client, owner_h, content={"title": "Inside"})
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "blank", "content": {"widgets": [
stack({"share": 50, "widget": {"kind": "menu", "board": {"product_ids": [menu["steak"].id], "exclude_ids": [menu["steak"].id]}}},
{"share": 50, "slide_id": promo["id"]})]}})
assert r.status_code == 200, r.text
got = r.json()
assert [i.get("hidden") for g in got["extras"]["0.0"]["menu"]["groups"] for i in g["items"]] == [True]
assert got["extras"]["0.1"]["slide"]["content"]["title"] == "Inside" and got["menu"] is None and got["media"] == {}
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "menu", "content": {"select": "all", "exclude_ids": [menu["beer"].id]}})
m = r.json()["menu"]
assert "Beer" in [i["name"] for g in m["groups"] for i in g["items"] if i.get("hidden")] and m["count"] == 3
assert err(client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "text", "content": {"widgets": [stack()]}})) == "signage.content_invalid"