feat(signage): venue badges, widgets' own look, widgets placed inside stacks, Save and leave, shared controls (owner review 5)
- Badges: the venue's list (setting signage.badges: names el/en, colours, an icon from a food and drink set) edited under Signage -> "Message & settings"; sent with the venue to screens and previews; several badges per product (MenuList.badges lists, a single one still read) in the shared multiple Dropdown; a board's badge colour / text colour override them (None = each own). - Widgets: colour, background plate, font, bold / italic / underline, text size, QR colours; widgets in a stack's part get every setting, vertical alignment, and a custom box inside their place, picked (stack, then widget) and dragged on the preview (selection by path "2.1.0"). - Menu slides: vertical alignment of the list (board_valign); "Where the list sits" is now "Horizontal alignment". - Message of the day: one component in the settings tab, on the Overview and from its widget. - Leaving a slide with changes: "Save and leave" (ConfirmDialog altLabel). - @xenia/ui: ColourField (with colour.js helpers), FieldRow (framed only while wrapped), Slider, IconPicker, Segmented multiple; native selects on the Overview and signage replaced by Dropdown, the device settings' colour input by ColourField. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -75,7 +75,7 @@ WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"
|
||||
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"]
|
||||
BADGE_KEY = r"^[a-z0-9][a-z0-9_-]{0,23}$" # a badge of the venue's list (services/signage_badges.py)
|
||||
Align = Literal["left", "center", "right"]
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ class MenuList(_Strict):
|
||||
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
|
||||
badges: Dict[str, List[str]] = Field(default_factory=dict) # product id → its badges (keys of the venue's list; up to 4)
|
||||
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)
|
||||
@@ -133,8 +133,9 @@ class MenuList(_Strict):
|
||||
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) # badges, page dots (headings and prices unless their own)
|
||||
badge_text_colour: Optional[str] = Field(default=None, pattern=HEX) # None: white or black, to read on the badge
|
||||
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # page dots; headings and prices until their own
|
||||
badge_colour: Optional[str] = Field(default=None, pattern=HEX) # None: each badge its own (the venue's list)
|
||||
badge_text_colour: Optional[str] = Field(default=None, pattern=HEX) # None: each badge its own (else white / black)
|
||||
text_size: int = Field(default=100, ge=50, le=250)
|
||||
# the look of each part (owner review 3, 2026-11-21)
|
||||
heading_style: TextStyle = Field(default_factory=TextStyle)
|
||||
@@ -162,12 +163,23 @@ class MenuList(_Strict):
|
||||
raise ValueError(f"one of {', '.join(sales_points.ALL)}")
|
||||
return v
|
||||
|
||||
@field_validator("badges")
|
||||
@field_validator("badges", mode="before")
|
||||
@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
|
||||
import re as _re
|
||||
if not isinstance(v, dict):
|
||||
return v
|
||||
out = {}
|
||||
for k, x in v.items():
|
||||
if not str(k).isdigit():
|
||||
raise ValueError("badges are keyed by product id")
|
||||
keys = [x] if isinstance(x, str) else list(x or []) # one badge (before owner review 5) or several
|
||||
keys = list(dict.fromkeys(str(b) for b in keys))
|
||||
if len(keys) > 4 or any(not _re.match(BADGE_KEY, b) for b in keys):
|
||||
raise ValueError("up to 4 badges of the venue's list")
|
||||
if keys:
|
||||
out[str(k)] = keys
|
||||
return out
|
||||
|
||||
|
||||
class Box(_Strict):
|
||||
@@ -237,6 +249,17 @@ class Widget(_Strict):
|
||||
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
|
||||
# its look (owner review 5, 2026-11-21): None = the slide's
|
||||
vertical: Literal["auto", "top", "middle", "bottom"] = "auto" # inside its place (a stack's part, its box)
|
||||
colour: Optional[str] = Field(default=None, pattern=HEX) # its text and pictures (weather, clock…)
|
||||
background_colour: Optional[str] = Field(default=None, pattern=HEX) # a plate behind it
|
||||
font: Optional[Font] = None
|
||||
bold: Optional[bool] = None # None: as the widget usually is
|
||||
italic: bool = False
|
||||
underline: bool = False
|
||||
text_size: int = Field(default=100, ge=50, le=200) # % of its usual text
|
||||
qr_colour: Optional[str] = Field(default=None, pattern=HEX) # the code's dots (default black)
|
||||
qr_background: Optional[str] = Field(default=None, pattern=HEX) # around them (default white)
|
||||
direction: Literal["row", "column"] = "row" # stack: side by side / one over the other
|
||||
cells: List[Cell] = Field(default_factory=list, max_length=6)
|
||||
|
||||
@@ -316,6 +339,7 @@ class MenuContent(MenuList):
|
||||
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
|
||||
board_valign: Literal["top", "middle", "bottom"] = "top" # where a shorter list sits (owner review 5)
|
||||
background: Background = Field(default_factory=Background)
|
||||
widgets: List[Widget] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@@ -1116,8 +1140,7 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
|
||||
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
|
||||
"playlist": playlist, "schedule": schedule, "playlists": playlists,
|
||||
# for the widgets (5.4c): weather None = hide it (no internet, no place, too old)
|
||||
"venue": {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None,
|
||||
"weather": weather.current(db)}}
|
||||
"venue": _venue(db)}
|
||||
out["version"] = hashlib.sha256(json.dumps(out, sort_keys=True, default=str).encode()).hexdigest()[:16]
|
||||
return out
|
||||
|
||||
@@ -1217,6 +1240,33 @@ def put_message(body: MessageBody, db: Session = Depends(get_db), user=Depends(r
|
||||
return {"text": (body.text or "").strip() or None}
|
||||
|
||||
|
||||
class BadgesBody(BaseModel):
|
||||
badges: list = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.get("/badges")
|
||||
def get_badges(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""The badges boards can put on products (owner review 5), with the icons they may have."""
|
||||
from services import signage_badges
|
||||
return {"badges": signage_badges.load(db), "icons": list(signage_badges.ICONS)}
|
||||
|
||||
|
||||
@router.put("/badges")
|
||||
def put_badges(body: BadgesBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""The venue's badges, all at once: their names, colours (the boards' defaults) and icons."""
|
||||
from pydantic import ValidationError
|
||||
from services import signage_badges
|
||||
try:
|
||||
parsed = signage_badges.BadgeList(badges=body.badges)
|
||||
except ValidationError as e:
|
||||
first = e.errors()[0]
|
||||
raise XeniaError("signage.content_invalid", field=".".join(str(x) for x in first.get("loc", ())), reason=first.get("msg", ""))
|
||||
out = signage_badges.save(db, parsed.badges)
|
||||
db.commit()
|
||||
tell_all_screens(db)
|
||||
return {"badges": out, "icons": list(signage_badges.ICONS)}
|
||||
|
||||
|
||||
@router.get("/weather")
|
||||
def weather_status(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from services import weather
|
||||
@@ -1273,8 +1323,15 @@ class MenuPreviewBody(BaseModel):
|
||||
@router.get("/venue")
|
||||
def preview_venue(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""What the widgets show (the same as a screen gets), for the editor's previews."""
|
||||
from services import weather
|
||||
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, "weather": weather.current(db)}
|
||||
return _venue(db)
|
||||
|
||||
|
||||
def _venue(db) -> dict:
|
||||
"""What the widgets need of the venue: its name, the message of the day, the weather (None = hide
|
||||
it: no internet, no place, too old) and its badges (owner review 5)."""
|
||||
from services import signage_badges, weather
|
||||
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None,
|
||||
"weather": weather.current(db), "badges": signage_badges.load(db)}
|
||||
|
||||
|
||||
class SlidePreviewBody(BaseModel):
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""The badges a menu board can put on a product (owner review 5, 2026-11-21): the venue's own list,
|
||||
kept in the setting `signage.badges` (JSON), edited under Signage → Message & settings. Each badge
|
||||
has a key (what boards store), its name in Greek and English, its colours (background, text: None =
|
||||
white or black, whichever reads) and an icon (a name from ICONS, drawn by @xenia/signage). Its
|
||||
colours are the defaults: a board may give all its badges one colour of its own.
|
||||
|
||||
Until the venue changes it, the list is DEFAULTS (the seven badges boards had before)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
SETTING = "signage.badges"
|
||||
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"
|
||||
KEY = r"^[a-z0-9][a-z0-9_-]{0,23}$"
|
||||
|
||||
# the icons a badge can have (lucide names; @xenia/signage BADGE_ICONS draws the same list)
|
||||
ICONS = (
|
||||
"sparkles", "chef-hat", "tag", "star", "flame", "sprout", "leaf", "vegan", "wheat", "wheat-off", "fish", "shrimp", "beef",
|
||||
"drumstick", "egg", "milk", "nut", "carrot", "salad", "pizza", "hamburger", "sandwich", "soup", "croissant",
|
||||
"ice-cream-cone", "cake-slice", "coffee", "cup-soda", "wine", "beer", "martini", "glass-water", "citrus", "cherry",
|
||||
"apple", "heart", "award", "thumbs-up", "clock", "percent", "gift", "crown", "zap", "snowflake",
|
||||
)
|
||||
|
||||
DEFAULTS = [
|
||||
{"key": "new", "names": {"el": "Νέο", "en": "New"}, "colour": "#22c55e", "text_colour": None, "icon": "sparkles"},
|
||||
{"key": "chef", "names": {"el": "Πρόταση σεφ", "en": "Chef's pick"}, "colour": "#f59e0b", "text_colour": None, "icon": "chef-hat"},
|
||||
{"key": "offer", "names": {"el": "Προσφορά", "en": "Offer"}, "colour": "#ef4444", "text_colour": None, "icon": "tag"},
|
||||
{"key": "popular", "names": {"el": "Δημοφιλές", "en": "Popular"}, "colour": "#f472b6", "text_colour": None, "icon": "star"},
|
||||
{"key": "spicy", "names": {"el": "Καυτερό", "en": "Spicy"}, "colour": "#dc2626", "text_colour": None, "icon": "flame"},
|
||||
{"key": "vegetarian", "names": {"el": "Χορτοφαγικό", "en": "Vegetarian"}, "colour": "#16a34a", "text_colour": None, "icon": "sprout"},
|
||||
{"key": "vegan", "names": {"el": "Vegan", "en": "Vegan"}, "colour": "#15803d", "text_colour": None, "icon": "vegan"},
|
||||
]
|
||||
|
||||
|
||||
class BadgeDef(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
key: str = Field(pattern=KEY)
|
||||
names: Dict[str, str] = Field(default_factory=dict)
|
||||
colour: str = Field(default="#f59e0b", pattern=HEX)
|
||||
text_colour: Optional[str] = Field(default=None, pattern=HEX)
|
||||
icon: Optional[str] = None
|
||||
|
||||
@field_validator("names")
|
||||
@classmethod
|
||||
def _names(cls, v):
|
||||
out = {k: " ".join(str(x).split())[:24] for k, x in v.items() if k in ("el", "en")}
|
||||
out = {k: x for k, x in out.items() if x}
|
||||
if not out:
|
||||
raise ValueError("a badge has a name")
|
||||
return out
|
||||
|
||||
@field_validator("icon")
|
||||
@classmethod
|
||||
def _icon(cls, v):
|
||||
if v is not None and v not in ICONS:
|
||||
raise ValueError("an icon of the list")
|
||||
return v
|
||||
|
||||
|
||||
class BadgeList(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
badges: List[BadgeDef] = Field(default_factory=list, max_length=30)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _unique(self):
|
||||
keys = [b.key for b in self.badges]
|
||||
if len(set(keys)) != len(keys):
|
||||
raise ValueError("each badge has its own key")
|
||||
return self
|
||||
|
||||
|
||||
def load(db) -> list[dict]:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
|
||||
if row is None or not row.value:
|
||||
return [dict(b) for b in DEFAULTS]
|
||||
try:
|
||||
return BadgeList(badges=json.loads(row.value)).model_dump()["badges"]
|
||||
except Exception: # noqa: BLE001 — a broken setting falls back to the defaults
|
||||
return [dict(b) for b in DEFAULTS]
|
||||
|
||||
|
||||
def save(db, badges: list[BadgeDef]) -> list[dict]:
|
||||
from models.settings import PosSettings
|
||||
value = json.dumps([b.model_dump() for b in badges], ensure_ascii=False)
|
||||
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
|
||||
if row is None:
|
||||
db.add(PosSettings(key=SETTING, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
return [b.model_dump() for b in badges]
|
||||
|
||||
|
||||
def new_key(name: str, taken: set) -> str:
|
||||
"""A key for a new badge from its name (the editor makes its own; kept for scripts)."""
|
||||
base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:20] or "badge"
|
||||
key, n = base, 2
|
||||
while key in taken:
|
||||
key, n = f"{base}-{n}", n + 1
|
||||
return key
|
||||
@@ -80,7 +80,7 @@ def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> dict:
|
||||
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()}
|
||||
badges = {int(k): ([v] if isinstance(v, str) else list(v or [])) for k, v in (content.get("badges") or {}).items() if str(k).isdigit()}
|
||||
|
||||
lang = content.get("language") # 6.4: the board's language; None = the base texts
|
||||
|
||||
@@ -102,7 +102,7 @@ def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> 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), **({"hidden": True} if p.id in excluded else {})}
|
||||
"badges": badges.get(p.id) or [], **({"hidden": True} if p.id in excluded else {})}
|
||||
|
||||
if content.get("group_by_category", True):
|
||||
groups: dict = {}
|
||||
|
||||
@@ -97,7 +97,7 @@ def test_prices_sold_out_badges_photos(client, owner_h, tv, menu, db):
|
||||
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 (souv["price"], souv["badges"], 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"]
|
||||
@@ -136,7 +136,7 @@ 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": {"badges": {"3": "Shiny!"}}})) == "signage.content_invalid"
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"columns": 4}})) == "signage.content_invalid"
|
||||
|
||||
|
||||
@@ -148,4 +148,5 @@ def test_the_editor_previews(client, owner_h, tv, menu):
|
||||
assert names(draft["menu"]) == [["Grill", ["Steak"]]] and draft["content"]["columns"] == 2
|
||||
assert err(client.post("/api/signage/preview/menu", headers=owner_h, json={"content": {"columns": 9}})) == "signage.content_invalid"
|
||||
client.put("/api/signage/message", headers=owner_h, json={"text": "Hello"})
|
||||
assert client.get("/api/signage/venue", headers=owner_h).json() == {"name": None, "message": "Hello", "weather": None}
|
||||
v = client.get("/api/signage/venue", headers=owner_h).json()
|
||||
assert {k: v[k] for k in ("name", "message", "weather")} == {"name": None, "message": "Hello", "weather": None} and len(v["badges"]) == 7
|
||||
|
||||
@@ -141,3 +141,35 @@ def test_a_part_holds_several_widgets_and_colours_can_be_see_through(client, own
|
||||
assert m["badge_text_colour"] == "#fde68aCC" and m["accent_colour"] == "#1e3a8a"
|
||||
for bad in ({"badge_text_colour": "#fff"}, {"text_colour": "#12345"}):
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
|
||||
|
||||
|
||||
def test_the_venues_badges_and_a_widgets_own_look(client, owner_h, menu, screens):
|
||||
"""Owner review 5 (2026-11-21): the venue's badges (names, colours, icons) edited in one place and
|
||||
sent with the venue; a product with several badges; a widget's own look; a board's list placed
|
||||
up or down."""
|
||||
got = client.get("/api/signage/badges", headers=owner_h).json()
|
||||
assert [b["key"] for b in got["badges"]][:3] == ["new", "chef", "offer"] and "flame" in got["icons"]
|
||||
mine = got["badges"][:2] + [{"key": "gluten-free", "names": {"el": "Χωρίς γλουτένη", "en": "Gluten free"}, "colour": "#0ea5e9", "text_colour": "#ffffff", "icon": "wheat-off"}]
|
||||
r = client.put("/api/signage/badges", headers=owner_h, json={"badges": mine})
|
||||
assert r.status_code == 200, r.text and [b["key"] for b in r.json()["badges"]] == ["new", "chef", "gluten-free"]
|
||||
for bad in ([{"key": "x", "names": {}}], [{"key": "x", "names": {"en": "X"}, "icon": "unicorn"}],
|
||||
[{"key": "x", "names": {"en": "X"}}, {"key": "x", "names": {"en": "Y"}}]):
|
||||
assert err(client.put("/api/signage/badges", headers=owner_h, json={"badges": bad})) == "signage.content_invalid", bad
|
||||
assert client.get("/api/signage/venue", headers=owner_h).json()["badges"][2]["icon"] == "wheat-off"
|
||||
p = playlist(client, owner_h)
|
||||
sid = str(menu["steak"].id)
|
||||
s = slide(client, owner_h, p["id"], "menu", content={"product_ids": [menu["steak"].id], "badges": {sid: ["chef", "gluten-free"]},
|
||||
"board_valign": "middle", "badge_colour": "#000000", "widgets": [
|
||||
{"kind": "qr", "qr_colour": "#1e3a8a", "qr_background": "#fde68a", "colour": "#ff0000", "bold": False, "italic": True, "font": "serif", "text_size": 150,
|
||||
"background_colour": "#00000080"},
|
||||
stack({"share": 100, "widgets": [{"kind": "clock", "vertical": "bottom", "align": "right"},
|
||||
{"kind": "date", "position": "custom", "box": {"x": 10, "y": 10, "w": 50, "h": 40}}]})]})
|
||||
c = s["content"]
|
||||
assert c["badges"] == {sid: ["chef", "gluten-free"]} and c["board_valign"] == "middle" and c["badge_colour"] == "#000000"
|
||||
q = c["widgets"][0]
|
||||
assert (q["qr_colour"], q["qr_background"], q["bold"], q["italic"], q["text_size"], q["font"]) == ("#1e3a8a", "#fde68a", False, True, 150, "serif")
|
||||
part = c["widgets"][1]["cells"][0]["widgets"]
|
||||
assert part[0]["vertical"] == "bottom" and part[1]["box"] == {"x": 10, "y": 10, "w": 50, "h": 40}
|
||||
url = f"/api/signage/playlists/{p['id']}/slides"
|
||||
for bad in ({"badges": {sid: ["a", "b", "c", "d", "e"]}}, {"board_valign": "centre"}, {"widgets": [{"kind": "clock", "text_size": 400}]}):
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
|
||||
|
||||
Reference in New Issue
Block a user