From aa3fe85053272c5437dc6646e470b67136a42970 Mon Sep 17 00:00:00 2001 From: bonamin Date: Sat, 21 Nov 2026 14:17:27 +0200 Subject: [PATCH] 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 --- docs/DESIGN.md | 7 +- local_backend/routers/signage.py | 81 +++++++-- local_backend/services/signage_badges.py | 104 +++++++++++ local_backend/services/signage_menu.py | 4 +- local_backend/tests/test_signage_menu.py | 7 +- local_backend/tests/test_signage_stacks.py | 32 ++++ .../src/pages/overview/BookingsCard.jsx | 13 +- .../src/pages/overview/OrderDialog.jsx | 4 +- .../src/pages/overview/OverviewPage.jsx | 13 +- .../src/pages/overview/ShiftsCard.jsx | 4 +- .../src/pages/platform/DeviceConfigFields.jsx | 7 +- .../src/pages/signage/BadgesSettings.jsx | 102 +++++++++++ .../src/pages/signage/MenuEditor.jsx | 45 +++-- .../src/pages/signage/MenuLook.jsx | 168 +++++++----------- .../src/pages/signage/MessageOfTheDay.jsx | 36 ++++ .../src/pages/signage/PlaylistEditor.jsx | 9 +- .../src/pages/signage/SignageFields.jsx | 93 +--------- .../src/pages/signage/SignageSettingsTab.jsx | 33 ++-- .../src/pages/signage/SlideEditor.jsx | 12 +- .../src/pages/signage/SlidesTab.jsx | 11 +- .../src/pages/signage/WidgetCanvas.jsx | 98 +++++++--- .../src/pages/signage/WidgetsEditor.jsx | 133 ++++++++++++-- .../src/pages/signage/signageApi.js | 4 + .../src/pages/signage/signageLogic.js | 80 +++++---- .../src/pages/signage/useBadges.js | 23 +++ .../src/pages/signage/useSlideDraft.js | 12 +- manager_dashboard/tests/signage.test.mjs | 12 -- packages/i18n/locales/el/common.json | 6 +- packages/i18n/locales/el/manager.json | 62 +++++-- packages/i18n/locales/en/common.json | 6 +- packages/i18n/locales/en/manager.json | 62 +++++-- packages/i18n/src/hooks.js | 4 + packages/signage/src/SlideView.jsx | 2 +- packages/signage/src/Slides.jsx | 84 ++++++--- packages/signage/src/badges.js | 16 ++ packages/signage/src/index.js | 1 + packages/signage/src/logic.js | 39 +++- packages/signage/tests/logic.test.mjs | 14 +- packages/ui/src/components.css | 71 ++++++++ packages/ui/src/components/ColourField.jsx | 75 ++++++++ packages/ui/src/components/ConfirmDialog.jsx | 12 +- packages/ui/src/components/Controls.jsx | 13 +- packages/ui/src/components/FieldRow.jsx | 34 ++++ packages/ui/src/components/IconPicker.jsx | 41 +++++ packages/ui/src/components/Slider.jsx | 18 ++ packages/ui/src/components/colour.js | 28 +++ packages/ui/src/components/labels.js | 4 + packages/ui/src/index.js | 5 + packages/ui/tests/colour.test.mjs | 15 ++ tests/e2e/manager.mjs | 5 +- tests/e2e/signage.mjs | 46 ++++- 51 files changed, 1378 insertions(+), 432 deletions(-) create mode 100644 local_backend/services/signage_badges.py create mode 100644 manager_dashboard/src/pages/signage/BadgesSettings.jsx create mode 100644 manager_dashboard/src/pages/signage/MessageOfTheDay.jsx create mode 100644 manager_dashboard/src/pages/signage/useBadges.js create mode 100644 packages/signage/src/badges.js create mode 100644 packages/ui/src/components/ColourField.jsx create mode 100644 packages/ui/src/components/FieldRow.jsx create mode 100644 packages/ui/src/components/IconPicker.jsx create mode 100644 packages/ui/src/components/Slider.jsx create mode 100644 packages/ui/src/components/colour.js create mode 100644 packages/ui/tests/colour.test.mjs diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 583388e..226fa64 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -49,6 +49,11 @@ Every page is on `` except Inventory → Stock (a placeholder). Two-column | Search | `SearchInput` | icon, clear button; `onChange(text)` | | Choose one / several | `Dropdown` (`multiple`) | **never a native `` | +| An icon from a set | `IconPicker` (`icons` = { key: component }) | a field showing the icon; a grid of the set over the page, "No icon" first | +| A slider with its value | `Slider` (`suffix`) | framed and as tall as the fields beside it | +| Fields that should wrap | `FieldRow` (`min`, `shade` on every other row) | each field keeps its least width; a row that wraps is framed (and tinted with `shade`), a row on one line looks like any row | +| Toggles that go together (bold / italic / underline) | `Segmented multiple` | value is an array | | A toggle filter (a state) | `FilterChip` (`tone`, `count`) | | | Two or three views (List / Map / QR) | `Segmented` | the view in the address (`?view=`) | | Sections of a page or a dialog | `Tabs` (`size="lg"` on pages) | scrolls sideways only, never up/down. `inset`: the strip is a card's header (card padding at the sides, the same room above and below a button in `end`, the labels level with it, no line under it). `fill`: the tabs share the width equally (a narrow column) | @@ -58,7 +63,7 @@ Every page is on `` except Inventory → Stock (a placeholder). Two-column | A quiet text action that warns | `Button variant="ghost" tone="danger"` | grey text, red under the pointer ("Remove" a picture) | | A switch on its own in a row of buttons | `Switch` without a label | lines up with the buttons (centred), never with a text baseline | | Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` | -| Ask before doing something (delete, leave unsaved work) | `useConfirm()` → `confirm({ title, body, confirmLabel, tone })` (or `ConfirmDialog`) | **never the browser's `window.confirm`**; render the returned dialog in the component | +| Ask before doing something (delete, leave unsaved work) | `useConfirm()` → `confirm({ title, body, confirmLabel, tone })` (or `ConfirmDialog`) | **never the browser's `window.confirm`**; render the returned dialog in the component. Leaving unsaved work: add `altLabel` ("Save and leave"): the promise answers `'alt'` | | A switch in a row of fields | `Switch boxed` | framed and as tall as an input: text left, switch right; a click anywhere in the frame toggles it | | Two or three choices that fill a form column (alignment…) | `Segmented fill` | options share the width; icon-only options pass `ariaLabel` | | A side drawer | `Sheet side="right"` (`size="wide"`: 600 px) | the permissions editor is `wide` | diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py index b65026c..4051732 100644 --- a/local_backend/routers/signage.py +++ b/local_backend/routers/signage.py @@ -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): diff --git a/local_backend/services/signage_badges.py b/local_backend/services/signage_badges.py new file mode 100644 index 0000000..08a5a63 --- /dev/null +++ b/local_backend/services/signage_badges.py @@ -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 diff --git a/local_backend/services/signage_menu.py b/local_backend/services/signage_menu.py index 99a86b9..1f5d0b5 100644 --- a/local_backend/services/signage_menu.py +++ b/local_backend/services/signage_menu.py @@ -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 = {} diff --git a/local_backend/tests/test_signage_menu.py b/local_backend/tests/test_signage_menu.py index 497e770..cb7776d 100644 --- a/local_backend/tests/test_signage_menu.py +++ b/local_backend/tests/test_signage_menu.py @@ -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 diff --git a/local_backend/tests/test_signage_stacks.py b/local_backend/tests/test_signage_stacks.py index 3091680..5419a05 100644 --- a/local_backend/tests/test_signage_stacks.py +++ b/local_backend/tests/test_signage_stacks.py @@ -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 diff --git a/manager_dashboard/src/pages/overview/BookingsCard.jsx b/manager_dashboard/src/pages/overview/BookingsCard.jsx index 5fdc0cd..ecf7555 100644 --- a/manager_dashboard/src/pages/overview/BookingsCard.jsx +++ b/manager_dashboard/src/pages/overview/BookingsCard.jsx @@ -9,7 +9,7 @@ import toast from 'react-hot-toast' import { CalendarDays, Check, Pencil, Phone, Plus, Armchair, UserCheck, Users, X } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useFormat, useTranslation } from '@xenia/i18n' -import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Textarea } from '@xenia/ui' +import { Button, Dialog, Dropdown, EmptyState, Field, IconButton, Input, Spinner, Textarea } from '@xenia/ui' import client from '../../api/client' import { useLiveQuery } from '../../live/useLiveQuery' import { BOOKING_OFFSETS, bookingBody, offsetFrom, tableName, tablesByZone, venueWallClock } from './overviewLogic' @@ -168,14 +168,9 @@ export function BookingDialog({ tables, initial, onClose, onSaved }) { ))} - + set('table_id', v ? Number(v) : null)} + options={[{ value: '', label: t('overview.bookings.noTable') }, + ...zones.flatMap(z => z.tables.map(tb => ({ value: String(tb.id), label: tableName(tb), hint: z.zone })))]} />
set('phone', e.target.value)} /> diff --git a/manager_dashboard/src/pages/overview/OrderDialog.jsx b/manager_dashboard/src/pages/overview/OrderDialog.jsx index b800a55..c71db6e 100644 --- a/manager_dashboard/src/pages/overview/OrderDialog.jsx +++ b/manager_dashboard/src/pages/overview/OrderDialog.jsx @@ -8,7 +8,7 @@ import toast from 'react-hot-toast' import { ArrowRight, Printer, X } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useFormat, useTranslation } from '@xenia/i18n' -import { Button, Dialog, EmptyState, IconButton, Select, Spinner, cx } from '@xenia/ui' +import { Button, Dialog, Dropdown, EmptyState, IconButton, Spinner, cx } from '@xenia/ui' import client from '../../api/client' import { useLiveQuery } from '../../live/useLiveQuery' import { lineTotal, orderTotal } from './overviewLogic' @@ -99,7 +99,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull }) {printers.length > 0 && ( - { setWaiterId(e.target.value); setError(null) }} placeholder={t('overview.shifts.pick')} + { setWaiterId(v); setError(null) }} placeholder={t('overview.shifts.pick')} options={waiters.map(w => ({ value: String(w.id), label: w.full_name || w.username }))} data-testid="shift-start-waiter" /> diff --git a/manager_dashboard/src/pages/platform/DeviceConfigFields.jsx b/manager_dashboard/src/pages/platform/DeviceConfigFields.jsx index 31f83b7..f4b237d 100644 --- a/manager_dashboard/src/pages/platform/DeviceConfigFields.jsx +++ b/manager_dashboard/src/pages/platform/DeviceConfigFields.jsx @@ -5,7 +5,7 @@ // Used by the pair and edit dialogs of DevicesPage. import { useEffect, useState } from 'react' import { useTranslation } from '@xenia/i18n' -import { Field, Input, Select, Switch } from '@xenia/ui' +import { ColourField, Field, Input, Select, Switch } from '@xenia/ui' import client from '../../api/client' import { configGroups, configValue, refOptions } from './devicesLogic' @@ -64,10 +64,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang } if (f.type === 'color') { return ( - - set(f, e.target.value)} data-config={f.key} - className="h-10 w-16 rounded-control border border-line bg-surface cursor-pointer" /> - + set(f, c)} opacity={false} testId={`config-${f.key}`} /> ) } return ( diff --git a/manager_dashboard/src/pages/signage/BadgesSettings.jsx b/manager_dashboard/src/pages/signage/BadgesSettings.jsx new file mode 100644 index 0000000..ce7c791 --- /dev/null +++ b/manager_dashboard/src/pages/signage/BadgesSettings.jsx @@ -0,0 +1,102 @@ +// The venue's badges for menu boards (owner review 5, 2026-11-21), under Signage → Message & settings: +// each with its name in Greek and English, its colours (background, text: "Automatic" = white or +// black, whichever reads) and an icon from a set for food and drink venues. Their colours are the +// defaults: a board may give all its badges a colour of its own (Text look). Saved all at once. +import { useEffect, useMemo, useState } from 'react' +import toast from 'react-hot-toast' +import { ArrowDown, ArrowUp, Plus, Trash2 } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useLanguage, useTranslation } from '@xenia/i18n' +import { BADGE_ICONS, badgeColours, badgeName } from '@xenia/signage' +import { Button, ColourField, Field, FieldRow, IconButton, IconPicker, Input, Spinner, useConfirm } from '@xenia/ui' +import * as api from './signageApi' +import { MENU_COLOURS, moved } from './signageLogic' +import { setBadges as shareBadges } from './useBadges' + +const newKey = taken => { + let n = 1 + while (taken.has(`badge-${n}`)) n++ + return `badge-${n}` +} + +export default function BadgesSettings() { + const { t } = useTranslation('manager') + const { language } = useLanguage() + const [saved, setSaved] = useState(null) + const [list, setList] = useState(null) + const [busy, setBusy] = useState(false) + const [confirm, confirmDialog] = useConfirm() + useEffect(() => { + api.getBadges().then(r => { setSaved(r.badges); setList(r.badges) }).catch(err => toast.error(errorMessage(err, t))) + }, [t]) + const dirty = useMemo(() => JSON.stringify(list) !== JSON.stringify(saved), [list, saved]) + if (!list) return
+ + const set = (i, patch) => setList(l => l.map((b, j) => (j === i ? { ...b, ...patch } : b))) + const setName = (i, lang, v) => setList(l => l.map((b, j) => (j === i ? { ...b, names: { ...b.names, [lang]: v } } : b))) + const add = () => setList(l => [...l, { key: newKey(new Set(l.map(b => b.key))), names: { el: '', en: '' }, colour: MENU_COLOURS.newBadge, text_colour: null, icon: null }]) + const remove = async i => { + const b = list[i] + if (await confirm({ title: t('signage.badgesSettings.removeTitle', { name: badgeName(b, language) || b.key }), body: t('signage.badgesSettings.removeBody'), + confirmLabel: t('fees.delete'), tone: 'danger', testId: 'signage-badge-remove-confirm' })) setList(l => l.filter((_, j) => j !== i)) + } + const save = async () => { + if (list.some(b => !b.names?.el?.trim() && !b.names?.en?.trim())) { toast.error(t('signage.badgesSettings.needName')); return } + setBusy(true) + try { + const r = await api.putBadges(list.map(b => ({ ...b, names: Object.fromEntries(Object.entries(b.names || {}).filter(([, v]) => v?.trim())) }))) + setSaved(r.badges); setList(r.badges); shareBadges(r.badges) + toast.success(t('settings.saved')) + } catch (err) { toast.error(errorMessage(err, t)) } + setBusy(false) + } + + return ( +
+
+
+

{t('signage.badgesSettings.title')}

+

{t('signage.badgesSettings.hint')}

+
+ + +
+
+ {list.map((b, i) => { + const Icon = BADGE_ICONS[b.icon] + return ( +
+
+ {/* as the TV draws it */} + + {Icon && + + setList(l => moved(l, i, i - 1))}> + setList(l => moved(l, i, i + 1))}> + remove(i)} data-testid="signage-badge-remove"> +
+ + + setName(i, 'el', e.target.value)} data-testid="signage-badge-name-el" /> + + + setName(i, 'en', e.target.value)} data-testid="signage-badge-name-en" /> + + set(i, { colour })} testId="signage-badge-bg" /> + set(i, { text_colour })} testId="signage-badge-fg" + auto={{ label: t('signage.look.badgeTextAuto'), on: !b.text_colour, pick: () => set(i, { text_colour: null }) }} /> + set(i, { icon })} testId="signage-badge-icon" /> + +
+ ) + })} +
+ {list.length < 30 && ( +
+ )} + {confirmDialog} +
+ ) +} diff --git a/manager_dashboard/src/pages/signage/MenuEditor.jsx b/manager_dashboard/src/pages/signage/MenuEditor.jsx index d5de871..9302e20 100644 --- a/manager_dashboard/src/pages/signage/MenuEditor.jsx +++ b/manager_dashboard/src/pages/signage/MenuEditor.jsx @@ -13,15 +13,19 @@ // Owner review 3 (2026-11-21): the look part by part (MenuLook: headings, names, prices, dots, // spacing, photos); a pencil beside each category and product on the board gives it a name for // this board only (the catalogue keeps its own: the waiters' names stay as they are). +// Owner review 5 (2026-11-21): several badges per product, from the venue's list (Message & settings), +// in the shared multiple-choice dropdown; the list placed up / middle / down as well as left / right. import { useEffect, useMemo, useState } from 'react' -import { AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowUp, Eye, EyeOff, Pencil, RotateCcw, X } from 'lucide-react' +import { AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart, ArrowDown, ArrowUp, Eye, EyeOff, Pencil, RotateCcw, X } from 'lucide-react' import { MENU_LANGUAGES, SALES_POINTS } from '@xenia/access' -import { useFormat, useTranslation } from '@xenia/i18n' -import { Dropdown, Field, IconButton, Input, Segmented, Select, Switch } from '@xenia/ui' +import { useFormat, useLanguage, useTranslation } from '@xenia/i18n' +import { badgeName } from '@xenia/signage' +import { Dropdown, Field, IconButton, Input, Segmented, Slider, Switch } from '@xenia/ui' import client from '../../api/client' -import { BADGES, boardOrder, moveGroup, moveItem, toggled } from './signageLogic' +import { boardOrder, moveGroup, moveItem, toggled } from './signageLogic' +import { useBadges } from './useBadges' import MenuLook from './MenuLook' -import { BackgroundField, Range, Section } from './SignageFields' +import { BackgroundField, Section } from './SignageFields' import WidgetsEditor from './WidgetsEditor' let catalogue = null // categories and products, read once for every menu editor on the page @@ -41,6 +45,9 @@ function useCatalogue() { export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [], widget = null, onWidget, extras, board = false, testid = 'signage-menu-editor' }) { const { t } = useTranslation('manager') const { formatMoney } = useFormat() + const { language } = useLanguage() + const defs = useBadges() + const badgeOptions = defs.map(d => ({ value: d.key, label: badgeName(d, language === 'el' ? 'el' : 'en'), dot: d.colour })) const c = slide.content || {} const setC = patch => onChange({ ...slide, content: { ...c, ...patch } }) const { cats, products } = useCatalogue() @@ -53,6 +60,13 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [ const found = q.trim().length < 1 ? [] : products.filter(p => p.name.toLowerCase().includes(q.trim().toLowerCase()) && !listed.has(p.id)).slice(0, 8) const reorder = next => setC(boardOrder(next)) const badges = c.badges || {} + const badgesOf = id => { const v = badges[String(id)]; return typeof v === 'string' ? [v] : v || [] } + const setBadgesOf = (id, list) => { + const next = { ...badges } + if (list.length) next[String(id)] = list.slice(0, 4) + else delete next[String(id)] + setC({ badges: next }) + } const digits = v => Number(String(v).replace(/\D/g, '')) const hidden = new Set(c.exclude_ids || []) // this board's own names: empty = the catalogue's again @@ -146,14 +160,8 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [ className={`text-label ${off ? 'text-ink-3 opacity-70' : it.available ? 'text-ink' : 'text-ink-3 line-through'}`} /> {off && {t('signage.menu.hiddenTag')}} {it.price != null && {formatMoney(it.price)}} -
{node}
- /** Headings, names or prices: size, colour, font, style, alignment. */ - const partRow = (part, key, { size, colour, font, onSize, onColour, onFont, inherit, align, aligns = ['left', 'center', 'right'] }) => { + const partRow = (part, key, shade, { size, colour, font, onSize, onColour, onFont, inherit, align, aligns = ['left', 'center', 'right'] }) => { const s = style(key) + const styles = [s.bold !== false && 'bold', s.italic && 'italic', s.underline && 'underline'].filter(Boolean) return ( - - {cell('size', )} - {cell('colour', )} - {cell('font', ( - - - - ))} - {cell('style', ( - - setStyle(key, patch)} testid={`signage-look-${key}`} /> - - ))} - {cell('align', ( - - setStyle(key, { align: v })} fill data-testid={`signage-look-${key}-align`} - options={aligns.map(v => { - const Icon = ALIGN_ICONS[v] - return { value: v, icon: - ))} - + + + + + + + + setStyle(key, { bold: list.includes('bold'), italic: list.includes('italic'), underline: list.includes('underline') })} + options={[['bold', Bold], ['italic', Italic], ['underline', Underline]].map(([v, Icon]) => ( + { value: v, icon: + + setStyle(key, { align: v })} fill data-testid={`signage-look-${key}-align`} + options={aligns.map(v => { + const Icon = ALIGN_ICONS[v] + return { value: v, icon: + ) } @@ -81,90 +79,58 @@ export default function MenuLook({ c, setC }) { return (
} onClick={reset} data-testid="signage-look-reset">{t('signage.look.reset')}}> -
- {partRow('heading', 'heading_style', { +
+ {partRow('heading', 'heading_style', false, { size: h.size || base, onSize: v => setStyle('heading_style', { size: v }), colour: h.colour || accent, onColour: v => setStyle('heading_style', { colour: v }), font: h.font || '', onFont: v => setStyle('heading_style', { font: v || null }), inherit: true, align: c.board_align || 'left', })} - {partRow('item', 'item_style', { + {partRow('item', 'item_style', true, { size: base, onSize: setNamesSize, colour: text, onColour: setNamesColour, font: c.font || 'sans', onFont: v => setC({ font: v }), inherit: false, align: 'left', aligns: ['left', 'right'], })} - {partRow('price', 'price_style', { + {partRow('price', 'price_style', false, { size: p.size || base, onSize: v => setStyle('price_style', { size: v }), colour: p.colour || accent, onColour: v => setStyle('price_style', { colour: v }), font: p.font || '', onFont: v => setStyle('price_style', { font: v || null }), inherit: true, align: 'right', })} - - {cell('size', setStyle('dot_style', { size: v })} testid="signage-look-dots-size" />)} - {cell('colour', setStyle('dot_style', { colour: v })} testid="signage-look-dots-colour" />)} - {cell('font', ( - - setStyle('dot_style', { style: v })} data-testid="signage-look-dots-style" - options={['dotted', 'dashed', 'solid', 'none'].map(x => ({ value: x, label: t(`signage.look.dotStyles.${x}`) }))} /> - - ))} - {cell('colour', )} - {cell('colour', setC({ badge_text_colour: v })} - testid="signage-badge-text" auto={{ label: t('signage.look.badgeTextAuto'), on: !c.badge_text_colour, pick: () => setC({ badge_text_colour: null }) }} />)} - - - {cell('font', ( - - setC({ line_height: v === '' ? null : Number(v) })} data-testid="signage-look-line-height" - options={choices(LINE_HEIGHTS, c.line_height, x => `${x}×`)} /> - - ))} - {cell('font', ( - - setC({ letter_spacing: v === '' ? null : Number(v) })} data-testid="signage-look-letter-spacing" - options={choices(LETTER_SPACINGS, c.letter_spacing, x => `${x > 0 ? '+' : ''}${Math.round(x * 100)}%`)} /> - - ))} + + setStyle('dot_style', { size: v })} testId="signage-look-dots-size" /> + setStyle('dot_style', { colour: v })} testId="signage-look-dots-colour" /> + + setStyle('dot_style', { style: v })} data-testid="signage-look-dots-style" + options={['dotted', 'dashed', 'solid', 'none'].map(x => ({ value: x, label: t(`signage.look.dotStyles.${x}`) }))} /> + + + + + setC({ badge_colour: v })} testId="signage-badge-colour" + auto={{ label: t('signage.look.badgeOwn'), on: !c.badge_colour, pick: () => setC({ badge_colour: null }) }} /> + setC({ badge_text_colour: v })} testId="signage-badge-text" + auto={{ label: t('signage.look.badgeOwn'), on: !c.badge_text_colour, pick: () => setC({ badge_text_colour: null }) }} /> + + + + setC({ line_height: v === '' ? null : Number(v) })} data-testid="signage-look-line-height" + options={choices(LINE_HEIGHTS, c.line_height, x => `${x}×`)} /> + + + setC({ letter_spacing: v === '' ? null : Number(v) })} data-testid="signage-look-letter-spacing" + options={choices(LETTER_SPACINGS, c.letter_spacing, x => `${x > 0 ? '+' : ''}${Math.round(x * 100)}%`)} /> + {c.show_photos && <> - {cell('size', setC({ photo_size: v })} testid="signage-look-photo-size" />)} - {cell('font', ( - - setC({ photo_shape: v })} data-testid="signage-look-photo-shape" - options={['square', 'rounded', 'round'].map(x => ({ value: x, label: t(`signage.look.shapes.${x}`) }))} /> - - ))} + setC({ photo_size: v })} testId="signage-look-photo-size" /> + + setC({ photo_shape: v })} data-testid="signage-look-photo-shape" + options={['square', 'rounded', 'round'].map(x => ({ value: x, label: t(`signage.look.shapes.${x}`) }))} /> + } - -

{t('signage.look.hint')}

+ +

{t('signage.look.hint')}

{confirmDialog}
) } - -/** A row of the look: its fields keep their least width and wrap to a second line, in columns that - * line up from row to row; rows alternate shades. */ -function Band({ testid, children }) { - return ( -
- {children} -
- ) -} - -/** Bold, italic, underline: three toggles as tall as a field. */ -function TextToggles({ s, onChange, testid }) { - const { t } = useTranslation('manager') - const items = [['bold', Bold, s.bold !== false], ['italic', Italic, !!s.italic], ['underline', Underline, !!s.underline]] - return ( -
- {items.map(([k, Icon, on]) => ( - - ))} -
- ) -} diff --git a/manager_dashboard/src/pages/signage/MessageOfTheDay.jsx b/manager_dashboard/src/pages/signage/MessageOfTheDay.jsx new file mode 100644 index 0000000..24aaf2e --- /dev/null +++ b/manager_dashboard/src/pages/signage/MessageOfTheDay.jsx @@ -0,0 +1,36 @@ +// The message of the day (plan step 5.6c; owner review 5, 2026-11-21: one editor, used in Signage → +// Message & settings, on the Overview and from a message widget): every screen shows it at once. +import { useEffect, useState } from 'react' +import toast from 'react-hot-toast' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Input, Spinner } from '@xenia/ui' +import * as api from './signageApi' + +export default function MessageOfTheDay({ onSaved, testId = 'signage-message' }) { + const { t } = useTranslation('manager') + const [text, setText] = useState(null) + const [saved, setSaved] = useState('') + const [busy, setBusy] = useState(false) + useEffect(() => { + api.getMessage().then(m => { setText(m.text || ''); setSaved(m.text || '') }).catch(err => toast.error(errorMessage(err, t))) + }, [t]) + if (text === null) return
+ const save = async () => { + setBusy(true) + try { + const r = await api.putMessage(text.trim()) + setSaved(r.text || ''); setText(r.text || '') + toast.success(t('settings.saved')) + onSaved?.(r.text || '') + } catch (err) { toast.error(errorMessage(err, t)) } + setBusy(false) + } + return ( +
+ setText(e.target.value)} className="flex-1" placeholder={t('signage.settings.messagePlaceholder')} + aria-label={t('signage.settings.message')} data-testid={testId} onKeyDown={e => { if (e.key === 'Enter' && text.trim() !== saved.trim()) save() }} /> + +
+ ) +} diff --git a/manager_dashboard/src/pages/signage/PlaylistEditor.jsx b/manager_dashboard/src/pages/signage/PlaylistEditor.jsx index 6b683e1..96d9bca 100644 --- a/manager_dashboard/src/pages/signage/PlaylistEditor.jsx +++ b/manager_dashboard/src/pages/signage/PlaylistEditor.jsx @@ -86,7 +86,14 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) { catch (err) { toast.error(errorMessage(err, t)); return null } finally { setBusy(false) } } - const leave = async () => !dirty || confirm({ title: t('signage.discardTitle'), body: t('signage.discard'), confirmLabel: t('signage.discardYes'), tone: 'danger', testId: 'signage-discard' }) + // leaving a slide with changes: save them and go, go without them, or stay (owner review 5) + const leave = async () => { + if (!dirty) return true + const how = await confirm({ title: t('signage.discardTitle'), body: t('signage.discard'), confirmLabel: t('signage.discardYes'), tone: 'danger', + altLabel: t('signage.saveAndLeave'), testId: 'signage-discard' }) + if (how !== 'alt') return how + return (await run(() => api.updateSlide(draft.id, slideBody(draft)), t('settings.saved'))) != null + } const pick = async s => { if (s.id === selected || !(await leave())) return setSelected(s.id) diff --git a/manager_dashboard/src/pages/signage/SignageFields.jsx b/manager_dashboard/src/pages/signage/SignageFields.jsx index 886932a..4bef25f 100644 --- a/manager_dashboard/src/pages/signage/SignageFields.jsx +++ b/manager_dashboard/src/pages/signage/SignageFields.jsx @@ -3,13 +3,13 @@ // a background (colour or photo with darkening), a slider with its value. // 2026-11-21 (owner review 2): the slider framed like the fields beside it; a colour as a field // (its swatch and code) that opens the ready colours and the picker, so it fits a row of fields. -// Owner review 4: that colour field everywhere, its panel over the page, see-through colours. -import { useCallback, useRef, useState } from 'react' +// Owner review 4: that colour field everywhere, its panel over the page, see-through colours +// (owner review 5: it is @xenia/ui's ColourField now). +import { useState } from 'react' import { AlertTriangle, Film, ImageIcon, X } from 'lucide-react' import { useTranslation } from '@xenia/i18n' -import { Button, Dropdown, Field, IconButton, Input, Popover } from '@xenia/ui' +import { Button, ColourField, Dropdown, Field, IconButton, Slider } from '@xenia/ui' import MediaPicker from '../media/MediaPicker' -import { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } from './signageLogic' /** A part of the slide editor: its title over a thin line, then its fields (DESIGN.md §3). */ export function Section({ title, aside, children, testid, className = '' }) { @@ -25,19 +25,6 @@ export function Section({ title, aside, children, testid, className = '' }) { ) } -/** A slider with its label and value, framed and as tall as the fields beside it. */ -export function Range({ label, value, min, max, step = 1, onChange, suffix = '', testid }) { - return ( - - - onChange(Number(e.target.value))} - className="flex-1 min-w-0 accent-accent" aria-label={label} data-testid={testid} /> - {value}{suffix} - - - ) -} - /** Pick a picture or a video from the library; `entry` is the media map's item for `value`. */ export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, misfit, label, testid }) { const { t } = useTranslation('manager') @@ -70,74 +57,6 @@ export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, mi ) } -/** - * A colour the venue chooses for its TV (data, not a theme colour: #rrggbb, or #rrggbbaa when - * see-through): a field (its swatch and code) that opens a small panel over the page (owner review - * 4, 2026-11-21: every signage colour): twelve ready colours, then the picker, the opacity and the - * code typed by hand. Each field changes only its own colour. `auto` ({ label, on, pick }): a first - * choice that lets the TV choose (a badge's text: white or black, whichever reads). - */ -export function ColourField({ label, value, onChange, testid, presets = COLOUR_PRESETS, auto, className }) { - const { t } = useTranslation('manager') - const [open, setOpen] = useState(false) - const [typed, setTyped] = useState(null) - const btn = useRef(null) - const v = (value || '#000000').toLowerCase() - const { rgb, alpha } = splitAlpha(v) - const close = useCallback(() => { setOpen(false); setTyped(null) }, []) - return ( - <> - - - - - {auto && ( - - )} -
- {presets.map(c => ( - - ))} -
-
- {t('signage.colourPick.custom')} -
- { setTyped(null); onChange(joinAlpha(e.target.value, alpha)) }} data-testid={testid} aria-label={label} - className="w-10 h-control shrink-0 rounded-control border border-line bg-surface cursor-pointer p-0.5" /> - { setTyped(e.target.value); const c = typedColour(e.target.value); if (c) onChange(c) }} onBlur={() => setTyped(null)} /> -
- -
-
- - ) -} - -/** A colour's swatch, over a checkerboard so a see-through colour shows as one. */ -function Swatch({ colour, className = '' }) { - return ( -
{bg.kind === 'colour' - ? set({ colour })} testid={`${testid}-colour`} className="max-w-xs" /> + ? set({ colour })} testId={`${testid}-colour`} className="max-w-xs" /> : (
{ onMedia(item); set({ media_id: item.id }) }} onRemove={() => set({ media_id: null })} /> - set({ dim })} testid={`${testid}-dim`} /> + set({ dim })} testId={`${testid}-dim`} /> set({ fit })} options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} /> diff --git a/manager_dashboard/src/pages/signage/SignageSettingsTab.jsx b/manager_dashboard/src/pages/signage/SignageSettingsTab.jsx index d43c94e..102b459 100644 --- a/manager_dashboard/src/pages/signage/SignageSettingsTab.jsx +++ b/manager_dashboard/src/pages/signage/SignageSettingsTab.jsx @@ -1,20 +1,21 @@ -// Signage → Message and weather (plan step 5.6c): the message of the day (one place for every -// screen, at once) and the weather's town (picked from a search; the weather needs internet, and -// without it the widget is simply hidden on the TVs). +// Signage → Message & settings (plan step 5.6c; renamed in owner review 5, 2026-11-21): the message +// of the day (one place for every screen, at once; also on the Overview), the weather's town (picked +// from a search; the weather needs internet, and without it the widget is simply hidden on the TVs) +// and the venue's badges for menu boards (BadgesSettings). import { useCallback, useEffect, useState } from 'react' import toast from 'react-hot-toast' import { CloudOff, RefreshCw, Search } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useFormat, useLanguage, useTranslation } from '@xenia/i18n' -import { Button, Field, Input, Select, Spinner } from '@xenia/ui' +import { Button, Dropdown, Field, Input, Spinner } from '@xenia/ui' +import BadgesSettings from './BadgesSettings' +import MessageOfTheDay from './MessageOfTheDay' import * as api from './signageApi' export default function SignageSettingsTab() { const { t } = useTranslation('manager') const { formatDateTime } = useFormat() const { language: lang } = useLanguage() - const [message, setMessage] = useState(null) - const [savedMessage, setSavedMessage] = useState('') const [status, setStatus] = useState(null) const [q, setQ] = useState('') const [places, setPlaces] = useState(null) @@ -23,29 +24,25 @@ export default function SignageSettingsTab() { const load = useCallback(async () => { try { - const [m, w] = await Promise.all([api.getMessage(), api.weatherStatus()]) - setMessage(m.text || ''); setSavedMessage(m.text || ''); setStatus(w) + const w = await api.weatherStatus() + setStatus(w) if (w.place?.units) setUnits(w.place.units) - } catch (err) { toast.error(errorMessage(err, t)) } + } catch (err) { toast.error(errorMessage(err, t)); setStatus(s => s || {}) } }, [t]) useEffect(() => { load() }, [load]) const act = async (fn, done) => { setBusy(true) try { const r = await fn(); if (done) toast.success(done); return r } catch (err) { toast.error(errorMessage(err, t)); return null } finally { setBusy(false) } } - if (message === null) return
+ if (status === null) return
const w = status?.weather return ( -
+

{t('signage.settings.message')}

{t('signage.settings.messageHint')}

-
- setMessage(e.target.value)} className="flex-1" aria-label={t('signage.settings.message')} data-testid="signage-message" /> - -
+
@@ -68,7 +65,7 @@ export default function SignageSettingsTab() { setQ(e.target.value)} placeholder={t('signage.settings.townPlaceholder')} data-testid="signage-weather-search" /> - { setTyped(null); onChange(opacity ? joinAlpha(e.target.value, alpha) : e.target.value) }} /> + { setTyped(e.target.value); const c = typedColour(e.target.value); if (c && (opacity || c.length === 7)) onChange(c) }} + onBlur={() => setTyped(null)} /> +
+ {opacity && ( + + )} +
+ + + ) +} + +/** A colour's swatch over a checkerboard, so a see-through colour shows as one. */ +export function Swatch({ colour, className }) { + return