diff --git a/docs/README.md b/docs/README.md index 88445d1..0b04b74 100644 --- a/docs/README.md +++ b/docs/README.md @@ -50,7 +50,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) | | `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory | | `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media///` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). **`data/media` belongs in every site backup together with `pos.db`** (the database only holds ids and hashes; DEPLOYMENT_GUIDE → Backups). Served public by hash at `/api/media/file//` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m`. **Videos (5.4e, `services/video.py`):** MP4 / MOV / WebM kept as uploaded; a background thread (`start_worker` in `main.py`'s lifespan, one video at a time, low priority, 2 threads) makes the still frame (the same `thumb` / `card` / `full` WebP) and, when `needs_version()` says so (not H.264 MP4, over 1920 px, 10-bit / HDR, other audio, > 12 Mbps), `play.mp4` (H.264 + AAC, ≤ 1920 px, HDR tone-mapped, faststart). `Media.processing` waiting → working (`progress`) → done | failed; migration 0031 queues existing videos. ffmpeg comes from the pinned `imageio-ffmpeg` wheel (static, Linux x86-64 / ARM64 / Windows; `XENIA_FFMPEG` overrides); without it videos stay as uploaded (`processing` null). `urls` gains `thumb`/`card`/`full`/`play` as they exist; `media.video_src()` is what a screen plays; `video.on_done(fn)` listeners (signage tells the screens playing it) | -| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`, and its picture (6R.13): `fit` (keep a slide's shape with bands / stretch) and `area_*` (px cut off each edge, set by Screens → Calibrate the picture; `signage.calibrate` to that screen while calibrating; the TV reports its window with `POST /api/signage/screen/viewport`); playlists and library slides have a shape (`orientation` + `aspect` "21:9", `shapeOf()` in `@xenia/signage`); `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out | +| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`, and its picture (6R.13): `fit` (keep a slide's shape with bands / stretch) and `area_*` (px cut off each edge, set by Screens → Calibrate the picture; `signage.calibrate` to that screen while calibrating; the TV reports its window with `POST /api/signage/screen/viewport`); playlists and library slides have a shape (`orientation` + `aspect` "21:9", `shapeOf()` in `@xenia/signage`); `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); 6R.15 adds shape (rectangle / circle as a box, triangle / polygon / star / own corners as SVG, `shapePoints`; fill or gradient, border), ticker (scrolling text, Web Animations), countdown (`countdownState` / `countdownText` in venue time: every day at HH:MM or a date; from now, a span before or a time), opening hours (`venue.opening_hours`, `GET/PUT /api/identity/hours`, edited on the Schedule page's Opening hours; `hoursRows`), Wi-Fi and contact details (from the identity; editor `MoreWidgetFields.jsx` warns with a link when the venue hasn't set them); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out | | `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage. **Call a waiter (5.7b):** device config `table` (ref `tables`) + `call_waiter`; `POST /api/menu-tablet/call` sends a `table_call` staff message (the open order's waiters, else the zone's; `qr_orders.waiters_for`) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" **Ordering at the table (6.6, D-30):** `services/tablet_orders.py` + `models/tablet_order.py` (`tablet_orders`, 0034). Device config `ordering` (off), `bill`, and per-tablet overrides `order_confirm` / `order_no_order` / `order_max_items` / `order_max_of_one` / `order_min_seconds` (-1 / `venue` = the venue's); the venue's rules are the JSON setting `menu_tablet.ordering` (`GET/PUT /api/menu-tablet/ordering`, Settings → Menu tablets). `/menu` adds `table.can_order`, `table.can_see_bill` and `ordering` (rules + `choices`: the POS product shape at in-store prices, so the tablet reuses `pos/ProductDialog`). `POST /quote` / `/order` take POS lines by id (`pos_cart.resolve_line`, never prices or discounts); every order is a `TabletOrder` row (it also times the limit); kitchen mode places it with `orders_api.add_priced_items(source="tablet")`, waiter mode leaves it `waiting` until `POST /requests/{id}/accept|decline` (`ordering.orders.open`; the phone's `TabletRequests` on the table page). Events: `tablet_order_updated` {id, table_id, status} to all (the phones refresh their list), `menu_tablet.order` to the tablet. Staff message type `tablet_order`. `GET/POST /bill`: the table's open order and asking for the bill (a `table_call` message, once a minute) | | `local_backend/routers/pricing.py`, `services/pricing.py`, `manager_dashboard/src/pages/pricing/` | Pricing (6.7): price groups, modifiers (price rules), deals, discount limits. Every set-up endpoint needs `pricing.manage` and broadcasts `pricing.changed` (the page's `useLiveQuery`); the phones keep reading rules / deals with any signed-in user. Conditions are checked on save (`_condition_ok` → `pricing.bad_condition`): an incomplete one used to raise in `services/pricing.py::_eval_condition` at quote time. Venue limits live in settings `discounts.*` (empty = no limit; `pricing.bad_limit`). The page's rules as data: `pricingLogic.js` (`tests/pricing.test.mjs`) | | `local_backend/routers/floor_plans.py`, `services/floor_live.py`, `packages/floorplan`, manager `src/pages/floor/` | The table map (6.8, D-31): `floor_plans` / `floor_items` (0035) and the tables' `plan_id`, `floor_x/y` (centre), `width`, `height`, `rotation`, `shape`. Set-up `/api/floor-plans` (`catalog.tables.manage`; `PUT /{id}/layout` saves tables + items whole) sends `floor_plans.changed`; `GET /api/floor-plans/live` (any signed-in person, the waiter app's zone rule) gives each table's state, guests (`customer_count`), waiters and time. `@xenia/floorplan`: `FloorView` (inline styles on tokens, so the waiter app can use it), `Floor` / `Item` / `TableShape`, `geometry.js` (grid snap = positions and sizes in whole cells; `@xenia/floorplan/geometry` for node tests). Dockerfiles copy its package.json | diff --git a/local_backend/modules/core/manifest.py b/local_backend/modules/core/manifest.py index 33dba6a..0925071 100644 --- a/local_backend/modules/core/manifest.py +++ b/local_backend/modules/core/manifest.py @@ -33,6 +33,7 @@ MODULE = Module( SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'), SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'), SettingDef('venue.name', '', 'Venue name shown on screens and tickets.', type='str'), + SettingDef('venue.opening_hours', '{}', 'Opening hours, Monday first (6R.15; JSON {days, note}; edited on the Schedule page, shown by signage).', type='json'), SettingDef('venue.identity', '{}', "The venue's identity (6R.14): slogan, colours, logos, Wi-Fi, contact details (JSON; Settings > Identity, routers/identity.py).", type='json'), SettingDef('venue.theme', 'amber', "Accent colour of the staff apps (the waiter's phones first, plan step 4.6): 'teal' | 'amber' | 'blue' | 'violet' | 'rose'", type='enum', choices=('teal', 'amber', 'blue', 'violet', 'rose')), SettingDef('venue.type', '', 'Kind of venue (restaurant, cafe, bar...), chosen in the setup wizard.', type='str'), diff --git a/local_backend/routers/identity.py b/local_backend/routers/identity.py index 129db7c..11f9101 100644 --- a/local_backend/routers/identity.py +++ b/local_backend/routers/identity.py @@ -1,7 +1,9 @@ """The venue's identity (6R.14, owner 2026-11-22): set once, used by every app that shows the venue. - GET /api/identity its name, slogan, colours, logos, Wi-Fi and contact details (anyone who opens the manager) - PUT /api/identity all of it at once (core.settings.manage) + GET /api/identity its name, slogan, colours, logos, Wi-Fi and contact details (anyone who opens the manager) + PUT /api/identity all of it at once (core.settings.manage) + GET /api/identity/hours the opening hours, Monday first (6R.15) + PUT /api/identity/hours {days: [[{from, to}], … 7], note} (core.settings.manage or core.staff.manage: the Schedule page) Stored as the settings `venue.name` (the name everything already shows) and `venue.identity` (JSON, the rest). Logos are media library pictures, protected while used. Signage screens get it with @@ -17,12 +19,14 @@ from fastapi import APIRouter, Depends from pydantic import BaseModel, ConfigDict, Field, field_validator from sqlalchemy.orm import Session -from core.access.deps import require +from core.access.deps import require, require_any from core.errors import XeniaError from database import get_db router = APIRouter() KEY = "venue.identity" +HOURS = "venue.opening_hours" +TIME = r"^([01]\d|2[0-3]):[0-5]\d$" HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$" LOGOS = ("main", "light", "dark", "icon") @@ -191,3 +195,57 @@ def put_identity(body: IdentityBody, db: Session = Depends(get_db), user=Depends except Exception: pass # signage not installed / off: nothing to tell return identity_out(db) + + +# ── opening hours (6R.15): edited on the Schedule page, shown by signage's opening hours widget ── + +class Span(_Strict): + """Open from … to … (venue time; `to` before `from` passes midnight).""" + from_: str = Field(alias="from", pattern=TIME) + to: str = Field(pattern=TIME) + model_config = ConfigDict(extra="forbid", populate_by_name=True) + + +class Hours(_Strict): + days: List[List[Span]] = Field(default_factory=lambda: [[] for _ in range(7)]) # Monday first; [] = closed + note: Optional[str] = Field(default=None, max_length=120) # "Closed on holidays" + + @field_validator("days") + @classmethod + def _seven(cls, v): + if len(v) != 7 or any(len(d) > 3 for d in v): + raise ValueError("seven days, up to three spans a day") + return v + + @field_validator("note") + @classmethod + def _note(cls, v): + return _text(v, 120) + + +def hours_out(db) -> dict: + """{days: [[{from, to}]…7], note, set}: `set` false while no day has hours.""" + try: + h = Hours(**json.loads(_setting(db, HOURS) or "{}")) + except Exception: + h = Hours() + days = [[{"from": x.from_, "to": x.to} for x in d] for d in h.days] + return {"days": days, "note": h.note, "set": any(days)} + + +@router.get("/hours") +def get_hours(db: Session = Depends(get_db), user=Depends(require("core.dashboard.access"))): + return hours_out(db) + + +@router.put("/hours") +def put_hours(body: Hours, db: Session = Depends(get_db), user=Depends(require_any("core.settings.manage", "core.staff.manage"))): + days = [[{"from": x.from_, "to": x.to} for x in sorted(d, key=lambda x: x.from_)] for d in body.days] + _save(db, HOURS, json.dumps({"days": days, "note": body.note}, ensure_ascii=False)) + db.commit() + try: + from routers.signage import tell_all_screens + tell_all_screens(db) + except Exception: + pass + return hours_out(db) diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py index 11746cd..faa4f89 100644 --- a/local_backend/routers/signage.py +++ b/local_backend/routers/signage.py @@ -82,7 +82,10 @@ class Background(_Strict): fit: Literal["cover", "contain"] = "cover" -WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack"] +WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack", + "shape", "ticker", "countdown", "hours", "wifi", "contact"] # 6R.15 +WHEN = r"^(\d{4}-\d{2}-\d{2}T)?([01]\d|2[0-3]):[0-5]\d$" # a countdown's moment: "HH:MM" (every day) or "YYYY-MM-DDTHH:MM" +ContactKey = Literal["phone", "phone2", "email", "address", "website", "google", "facebook", "instagram", "tiktok", "tripadvisor", "whatsapp", "viber"] Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"] @@ -251,7 +254,7 @@ class Widget(_Strict): box: Optional[Box] = None # position "custom" align: Literal["auto", "left", "center", "right"] = "auto" # inside its place; auto: by its corner / box media_id: Optional[int] = None # logo: a picture - text: Optional[str] = Field(default=None, max_length=200) # message: this text instead of the venue's + text: Optional[str] = Field(default=None, max_length=500) # message: this text instead of the venue's; text, ticker, a countdown's / hours' title date_style: Literal["short", "long"] = "long" clock_seconds: bool = False qr_target: Literal["ordering", "menu", "custom"] = "ordering" @@ -274,6 +277,37 @@ class Widget(_Strict): 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) + # a shape (6R.15): in its box; a fill (flat, or a gradient to fill_to at fill_angle), a border + shape: Literal["rectangle", "circle", "triangle", "polygon", "star", "custom"] = "rectangle" + shape_sides: int = Field(default=6, ge=3, le=12) # polygon: its sides; star: its points + shape_inner: int = Field(default=45, ge=15, le=90) # star: its inner corners, % of the outer + shape_points: Optional[str] = Field(default=None, max_length=600) # custom: "x,y x,y …" in % of its box + fill: Optional[str] = Field(default=None, pattern=HEX) + fill_to: Optional[str] = Field(default=None, pattern=HEX) # None: one colour + fill_angle: int = Field(default=180, ge=0, le=359) + stroke: Optional[str] = Field(default=None, pattern=HEX) + stroke_width: int = Field(default=0, ge=0, le=20) # steps of ½ % of the shape's shorter side + radius: int = Field(default=0, ge=0, le=50) # rectangle: rounded corners, % of its shorter side + # scrolling text + ticker_speed: int = Field(default=4, ge=1, le=10) + ticker_direction: Literal["left", "right"] = "left" + # a countdown: to a time every day or a date and time (venue time); it counts from now, from a span + # before, or from a time; before that it shows the whole span or nothing; at the end a text or nothing + countdown_to: Optional[str] = Field(default=None, pattern=WHEN) + countdown_start: Literal["now", "before", "at"] = "now" + countdown_before: int = Field(default=120, ge=1, le=10080) # minutes + countdown_at: Optional[str] = Field(default=None, pattern=WHEN) + countdown_waiting: Literal["full", "hide"] = "full" + countdown_done: Optional[str] = Field(default=None, max_length=80) + countdown_done_hide: bool = False + # the opening hours (from the Schedule page): the week, or today only; days with the same hours on one line + hours_style: Literal["week", "today"] = "week" + hours_group: bool = True + # Wi-Fi (from the identity): its code to join, the password written out + wifi_qr: bool = True + wifi_password: bool = True + # contact details (from the identity): which, in this order + contact_fields: List[ContactKey] = Field(default_factory=lambda: ["phone", "website", "instagram"], max_length=12) @model_validator(mode="after") def _place(self): @@ -1491,12 +1525,13 @@ def _venue(db) -> dict: it: no internet, no place, too old) and its badges (owner review 5); its identity (6R.14: slogan, colours, logos, Wi-Fi, contact) and time zone.""" from core.timeutil import venue_tz - from routers.identity import identity_out + from routers.identity import hours_out, identity_out from services import signage_badges, weather ident = identity_out(db) ident.pop("name", None) return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, - "weather": weather.current(db), "badges": signage_badges.load(db), "identity": ident, "timezone": venue_tz().key} + "weather": weather.current(db), "badges": signage_badges.load(db), "identity": ident, "timezone": venue_tz().key, + "hours": hours_out(db)} class SlidePreviewBody(BaseModel): diff --git a/local_backend/tests/test_identity.py b/local_backend/tests/test_identity.py index 28c7f4a..ade6cb2 100644 --- a/local_backend/tests/test_identity.py +++ b/local_backend/tests/test_identity.py @@ -45,3 +45,42 @@ def test_checked(client, owner_h): assert err(client.put("/api/identity", headers=owner_h, json={"logos": {"main": 99999}})) == "media.not_found" too_many = [{"name": f"c{i}", "colour": "#000000"} for i in range(13)] assert client.put("/api/identity", headers=owner_h, json={"colours": too_many}).status_code == 422 + + +def test_opening_hours(client, owner_h, screens, sent): + assert client.get("/api/identity/hours", headers=owner_h).json() == {"days": [[]] * 7, "note": None, "set": False} + days = [[{"from": "18:00", "to": "23:00"}, {"from": "12:00", "to": "15:00"}]] * 5 + [[{"from": "12:00", "to": "01:00"}], []] + sent.clear() + r = client.put("/api/identity/hours", headers=owner_h, json={"days": days, "note": " Closed on holidays "}) + assert r.status_code == 200, r.text + j = r.json() + assert j["set"] is True and j["days"][0] == [{"from": "12:00", "to": "15:00"}, {"from": "18:00", "to": "23:00"}] + assert j["days"][6] == [] and j["note"] == "Closed on holidays" + assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent + assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]["hours"]["days"][5] == [{"from": "12:00", "to": "01:00"}] + assert client.put("/api/identity/hours", headers=owner_h, json={"days": [[]] * 6}).status_code == 422 + assert client.put("/api/identity/hours", headers=owner_h, json={"days": [[{"from": "25:00", "to": "01:00"}]] + [[]] * 6}).status_code == 422 + + +def test_new_widgets_are_typed(client, owner_h): + from tests.test_signage import playlist, slide + p = playlist(client, owner_h) + widgets = [ + {"kind": "shape", "position": "custom", "box": {"x": 10, "y": 10, "w": 20, "h": 20}, "shape": "star", "shape_sides": 5, "fill": "#ff0000", "fill_to": "#0000ff"}, + {"kind": "ticker", "position": "bottom-bar", "text": "Fresh fish today " * 10, "ticker_speed": 7}, + {"kind": "countdown", "countdown_to": "17:00", "countdown_start": "before", "countdown_before": 120, "countdown_done": "Happy hour!"}, + {"kind": "countdown", "countdown_to": "2026-12-31T23:59"}, + {"kind": "hours", "hours_style": "today"}, + {"kind": "wifi", "wifi_qr": False}, + {"kind": "contact", "contact_fields": ["phone", "instagram"]}, + ] + s = slide(client, owner_h, p["id"], "blank", content={"widgets": widgets}) + got = s["content"]["widgets"] + assert [w["kind"] for w in got] == [w["kind"] for w in widgets] + assert got[0]["shape"] == "star" and got[2]["countdown_before"] == 120 and got[6]["contact_fields"] == ["phone", "instagram"] + bad = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h, + json={"kind": "blank", "content": {"widgets": [{"kind": "countdown", "countdown_to": "5pm"}]}}) + assert err(bad) == "signage.content_invalid" + bad = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h, + json={"kind": "blank", "content": {"widgets": [{"kind": "contact", "contact_fields": ["fax"]}]}}) + assert err(bad) == "signage.content_invalid" diff --git a/manager_dashboard/src/pages/schedule/OpeningHoursDialog.jsx b/manager_dashboard/src/pages/schedule/OpeningHoursDialog.jsx new file mode 100644 index 0000000..649c3cc --- /dev/null +++ b/manager_dashboard/src/pages/schedule/OpeningHoursDialog.jsx @@ -0,0 +1,87 @@ +// The venue's opening hours (6R.15, owner 2026-11-22): each day closed or open in up to three spans +// (a span may pass midnight), and a note. Kept on the server (PUT /api/identity/hours): the +// schedule's timeline shades them and signage's opening hours widget shows them. +import { useState } from 'react' +import toast from 'react-hot-toast' +import { useQueryClient } from '@tanstack/react-query' +import { Copy, Plus, Trash2 } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useFormat, useTranslation } from '@xenia/i18n' +import { Button, Dialog, Field, IconButton, Input, Spinner } from '@xenia/ui' +import client from '../../api/client' +import { HOURS_KEY, useHours } from '../../shell/useIdentity' +import { hoursValid } from './scheduleLogic' + +const MONDAY = '2026-11-16' + +export default function OpeningHoursDialog({ onClose }) { + const { data } = useHours() + return data ? :
+} + +function HoursForm({ saved, onClose }) { + const { t } = useTranslation('manager') + const fmt = useFormat() + const qc = useQueryClient() + const [days, setDays] = useState(() => saved.days.map(d => d.map(x => ({ ...x })))) + const [note, setNote] = useState(saved.note || '') + const [busy, setBusy] = useState(false) + const dayName = i => fmt.formatDateTime(`2026-11-${16 + i}T12:00:00Z`, { weekday: 'long' }) + const setDay = (i, spans) => setDays(ds => ds.map((d, j) => (j === i ? spans : d))) + const ok = hoursValid(days) + const save = async () => { + setBusy(true) + try { + const { data } = await client.put('/api/identity/hours', { days, note: note.trim() || null }) + qc.setQueryData(HOURS_KEY, data) + toast.success(t('schedule.openingSaved')) + onClose() + } catch (err) { toast.error(errorMessage(err, t)) } + setBusy(false) + } + return ( + + + + }> +
+ {days.map((spans, i) => ( +
+ {dayName(i)} +
+ {spans.length === 0 && {t('schedule.closedDay')}} + {spans.map((x, k) => ( +
+ setDay(i, spans.map((y, n) => (n === k ? { ...y, from: e.target.value } : y)))} /> + – + setDay(i, spans.map((y, n) => (n === k ? { ...y, to: e.target.value } : y)))} /> + setDay(i, spans.filter((_, n) => n !== k))}> +
+ ))} +
+ {spans.length < 3 && ( + + )} + {i === 0 && ( + + )} +
+
+
+ ))} + + setNote(e.target.value)} /> + + {!ok &&

{t('schedule.openingInvalid')}

} +
+
+ ) +} diff --git a/manager_dashboard/src/pages/schedule/SchedulePage.jsx b/manager_dashboard/src/pages/schedule/SchedulePage.jsx index 46ead86..363022b 100644 --- a/manager_dashboard/src/pages/schedule/SchedulePage.jsx +++ b/manager_dashboard/src/pages/schedule/SchedulePage.jsx @@ -7,7 +7,7 @@ import { useMemo, useState } from 'react' import { useMutation, useQueryClient } from '@tanstack/react-query' import toast from 'react-hot-toast' -import { ChevronLeft, ChevronRight, Plus, Settings2 } from 'lucide-react' +import { ChevronLeft, ChevronRight, Clock, Plus, Settings2 } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useFormat, useTranslation } from '@xenia/i18n' import { Button, EmptyState, IconButton, Page, PageHeader, Segmented, Spinner, cx } from '@xenia/ui' @@ -15,7 +15,10 @@ import client from '../../api/client' import { useLiveQuery } from '../../live/useLiveQuery' import ShiftDialog from './ShiftDialog' import ViewDialog from './ViewDialog' -import { addDays, gridOf, hourMarks, inOpening, loadView, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals } from './scheduleLogic' +import OpeningHoursDialog from './OpeningHoursDialog' +import { useHours } from '../../shell/useIdentity' +import { useSearchParams } from 'react-router-dom' +import { addDays, gridOf, hourMarks, inSpans, weekdayOf, loadView, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals } from './scheduleLogic' const STATE = { planned: 'border-info bg-info-soft text-info-ink', @@ -33,6 +36,10 @@ export default function SchedulePage() { const [start, setStart] = useState(() => weekStartOf(today, loadView().mondayFirst)) const [editing, setEditing] = useState(null) // { date, userId, shift? } const [settings, setSettings] = useState(false) + const [params, setParams] = useSearchParams() + const hoursOpen = params.get('hours') === '1' + const setHoursOpen = on => setParams(p => { const n = new URLSearchParams(p); if (on) n.set('hours', '1'); else n.delete('hours'); return n }, { replace: true }) + const { data: hours } = useHours() const setView = next => { setViewState(next); saveView(next) } const { data, isPending } = useLiveQuery({ @@ -67,6 +74,7 @@ export default function SchedulePage() { setStart(s => addDays(s, 7))} data-testid="schedule-next"> + setSettings(true)}> } /> @@ -121,7 +129,7 @@ export default function SchedulePage() { ) : ( - setEditing({ date: d, userId: null })} onOpen={(d, s) => setEditing({ date: d, userId: s.user_id, shift: s })} /> )} @@ -134,13 +142,14 @@ export default function SchedulePage() { {editing && setEditing(null)} onDelete={id => { remove.mutate(id); setEditing(null) }} onSaved={() => { setEditing(null); qc.invalidateQueries({ queryKey: ['schedule-week'] }) }} />} + {hoursOpen && setHoursOpen(false)} />} {settings && setSettings(false)} onSave={next => { if (next.mondayFirst !== view.mondayFirst) setStart(weekStartOf(start, next.mondayFirst)); setView(next); setSettings(false) }} />} ) } -function HoursView({ days, today, people, scheduled, view, dayLabel, dateLabel, onAdd, onOpen }) { +function HoursView({ days, today, people, scheduled, view, hours, dayLabel, dateLabel, onAdd, onOpen }) { const { t } = useTranslation('manager') const marks = hourMarks(view.firstHour) const nameOf = id => people.find(p => p.id === id)?.nickname || people.find(p => p.id === id)?.name || `#${id}` @@ -160,7 +169,7 @@ function HoursView({ days, today, people, scheduled, view, dayLabel, dateLabel,
onAdd(d)} title={t('schedule.addOn', { day: dayLabel(d) })} data-testid="schedule-day"> {marks.map((h, i) => ( -
) diff --git a/manager_dashboard/src/pages/schedule/scheduleLogic.js b/manager_dashboard/src/pages/schedule/scheduleLogic.js index 66ab7a3..e8c9746 100644 --- a/manager_dashboard/src/pages/schedule/scheduleLogic.js +++ b/manager_dashboard/src/pages/schedule/scheduleLogic.js @@ -100,8 +100,17 @@ export function inOpening(hour, open, close) { return a <= b ? hour >= a && hour < b : hour >= a || hour < b } +/** Is an hour mark inside any of a day's opening spans ([{from, to}], 6R.15: the venue's hours, kept on the server)? */ +export const inSpans = (hour, spans) => (spans || []).some(x => inOpening(hour, x.from, x.to)) + +/** Monday 0 … Sunday 6 of a "YYYY-MM-DD". */ +export const weekdayOf = d => (new Date(`${d}T12:00:00Z`).getUTCDay() + 6) % 7 + +/** Opening hours that can be saved: every span has both times and they differ. */ +export const hoursValid = days => days.every(d => d.every(x => /^\d\d:\d\d$/.test(x.from || '') && /^\d\d:\d\d$/.test(x.to || '') && x.from !== x.to)) + /** The schedule's view settings kept in this browser (a per-viewer convenience). */ -export const VIEW_DEFAULTS = { view: 'people', mondayFirst: true, firstHour: 6, open: '', close: '' } +export const VIEW_DEFAULTS = { view: 'people', mondayFirst: true, firstHour: 6 } const VIEW_KEY = 'xenia:schedule:view' export function loadView(storage = globalThis.localStorage) { try { return { ...VIEW_DEFAULTS, ...JSON.parse(storage?.getItem(VIEW_KEY) || '{}') } } catch { return { ...VIEW_DEFAULTS } } diff --git a/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx b/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx new file mode 100644 index 0000000..a4db2e2 --- /dev/null +++ b/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx @@ -0,0 +1,173 @@ +// The settings of the widgets added in 6R.15 (owner 2026-11-22): a shape, a scrolling text, a +// countdown, the opening hours, the guests' Wi-Fi and the contact details. The last three read the +// venue (Settings → Identity, the Schedule page's opening hours): when that is missing the card says +// so with a link to where it is set. Used by WidgetsEditor (its row and the part under it). +import { Link } from 'react-router-dom' +import { useTranslation } from '@xenia/i18n' +import { ColourField, Dropdown, Field, Input, Notice, NumberInput, Segmented, Slider, Switch } from '@xenia/ui' +import { useHours, useIdentity } from '../../shell/useIdentity' +import { CONTACT_KEYS, WIDGET_COLOURS } from './signageLogic' + +const SHAPES = ['rectangle', 'circle', 'triangle', 'polygon', 'star', 'custom'] +const isDate = v => !!v && v.length > 5 + +/** On the widget's row (where / size / alignment): its main choices. */ +export function MoreInlineFields({ w, set }) { + const { t } = useTranslation('manager') + const k = 'signage.widgets' + if (w.kind === 'shape') { + return (<> + + set({ shape })} data-testid="signage-widget-shape" + options={SHAPES.map(x => ({ value: x, label: t(`${k}.shape.kinds.${x}`) }))} /> + + {(w.shape === 'polygon' || w.shape === 'star') && ( + + set({ shape_sides: v ?? 3 })} data-testid="signage-widget-shape-sides" /> + + )} + ) + } + if (w.kind === 'ticker') { + return (<> + + set({ text: e.target.value || null })} data-testid="signage-widget-ticker-text" /> + + + set({ ticker_direction })} + options={['left', 'right'].map(v => ({ value: v, label: t(`${k}.ticker.directions.${v}`) }))} /> + + ) + } + if (w.kind === 'countdown') { + const to = w.countdown_to || '' + return (<> + + set({ text: e.target.value || null })} /> + + + set({ countdown_to: m === 'date' ? `${new Date().toISOString().slice(0, 10)}T${to.slice(-5) || '17:00'}` : (to.slice(-5) || '17:00') })} + options={['daily', 'date'].map(v => ({ value: v, label: t(`${k}.countdown.modes.${v}`) }))} /> + + + set({ countdown_to: e.target.value ? e.target.value.slice(0, isDate(to) ? 16 : 5) : null })} /> + + ) + } + if (w.kind === 'hours') { + return (<> + + set({ hours_style })} data-testid="signage-widget-hours-style" + options={['week', 'today'].map(v => ({ value: v, label: t(`${k}.hours.styles.${v}`) }))} /> + + + set({ text: e.target.value || null })} /> + + ) + } + if (w.kind === 'wifi') { + return ( + +
+ set({ wifi_qr: on })} label={t(`${k}.wifi.qr`)} data-testid="signage-widget-wifi-qr" /> + set({ wifi_password: on })} label={t(`${k}.wifi.password`)} /> +
+
+ ) + } + if (w.kind === 'contact') { + return ( + + set({ contact_fields })} data-testid="signage-widget-contact-fields" + allLabel={t(`${k}.contact.none`)} options={CONTACT_KEYS.map(x => ({ value: x, label: t(`identity.contact.${x}`) }))} /> + + ) + } + return null +} + +/** Under the row: what needs more room, and what the venue still has to set. */ +export function MoreBelowFields({ w, set }) { + const { t } = useTranslation('manager') + const { data: identity } = useIdentity() + const { data: hours } = useHours() + const k = 'signage.widgets' + if (w.kind === 'shape') { + return ( +
+ {w.shape === 'custom' && ( + + set({ shape_points: e.target.value || null })} data-testid="signage-widget-shape-points" /> + + )} + set({ fill })} testId="signage-widget-fill" /> + set({ fill_to })} testId="signage-widget-fill-to" + auto={{ label: t(`${k}.shape.oneColour`), on: !w.fill_to, pick: () => set({ fill_to: null }) }} /> + {w.fill_to && set({ fill_angle })} />} + set({ stroke, stroke_width: w.stroke_width || 4 })} testId="signage-widget-stroke" + auto={{ label: t(`${k}.shape.noStroke`), on: !w.stroke || !w.stroke_width, pick: () => set({ stroke: null, stroke_width: 0 }) }} /> + {w.stroke && w.stroke_width > 0 && set({ stroke_width })} />} + {w.shape === 'star' && set({ shape_inner })} />} + {(w.shape || 'rectangle') === 'rectangle' && set({ radius })} />} +
+ ) + } + if (w.kind === 'ticker') { + return set({ ticker_speed })} testId="signage-widget-ticker-speed" /> + } + if (w.kind === 'countdown') { + const start = w.countdown_start || 'now' + return ( +
+ + set({ countdown_start, ...(countdown_start === 'at' && !w.countdown_at ? { countdown_at: (w.countdown_to || '15:00').slice(-5) } : {}) })} + data-testid="signage-widget-countdown-start" options={['now', 'before', 'at'].map(v => ({ value: v, label: t(`${k}.countdown.startModes.${v}`) }))} /> + + {start === 'before' && ( + + set({ countdown_before: v ?? 1 })} data-testid="signage-widget-countdown-before" /> + + )} + {start === 'at' && ( + + set({ countdown_at: e.target.value || null })} /> + + )} + {start !== 'now' && ( + + set({ countdown_waiting })} + options={['full', 'hide'].map(v => ({ value: v, label: t(`${k}.countdown.waitingModes.${v}`) }))} /> + + )} + + set({ countdown_done: e.target.value || null, countdown_done_hide: !e.target.value })} /> + +
+ ) + } + if (w.kind === 'hours') { + return ( +
+ set({ hours_group })} label={t(`${k}.hours.group`)} description={t(`${k}.hours.groupHint`)} /> + {hours && !hours.set && ( + + {t(`${k}.hours.setThem`)} + + )} +
+ ) + } + if (w.kind === 'wifi' || w.kind === 'contact') { + const missing = w.kind === 'wifi' ? identity && !identity.wifi?.ssid : identity && !(w.contact_fields || ['phone', 'website', 'instagram']).some(x => identity.contact?.[x]) + return missing + ? ( + + {t(`${k}.fromIdentity`)} + + ) + :

{t(`${k}.${w.kind}.hint`)} {t(`${k}.fromIdentity`)}

+ } + return null +} diff --git a/manager_dashboard/src/pages/signage/WidgetsEditor.jsx b/manager_dashboard/src/pages/signage/WidgetsEditor.jsx index 97bb730..194cc26 100644 --- a/manager_dashboard/src/pages/signage/WidgetsEditor.jsx +++ b/manager_dashboard/src/pages/signage/WidgetsEditor.jsx @@ -18,11 +18,14 @@ // has every setting a slide's widget has, aligned both ways in its place or moved and sized there on // the preview (Custom); the message of the day changed from its widget. The picked widget is a path // ("2", "2.1.0": see WidgetCanvas). +// 6R.15 (owner 2026-11-22): a shape, a scrolling text, a countdown, the opening hours, Wi-Fi and contact +// details (MoreWidgetFields). // Up to the venue's limit (10 recommended; Signage → Message & settings → Performance). import { Fragment, useEffect, useRef, useState } from 'react' import { AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart, ArrowDown, ArrowUp, Bold, Italic, Palette, RotateCcw, Underline, BookImage, CalendarDays, ChevronDown, Clock, CloudSun, Columns3, GripVertical, ImageIcon, LayoutList, MessageSquare, Plus, QrCode, Rows3, Store, Trash2, Type, UtensilsCrossed, + CalendarClock, Contact, MoveHorizontal, Shapes, Timer, Wifi, } from 'lucide-react' import { cellWidgets, evenShares, setShare } from '@xenia/signage' import { useTranslation } from '@xenia/i18n' @@ -31,12 +34,14 @@ import MessageOfTheDay from './MessageOfTheDay' import { usePerformance } from './usePerformance' import * as api from './signageApi' import MenuEditor from './MenuEditor' +import { MoreBelowFields as MoreBelow, MoreInlineFields as MoreInline } from './MoreWidgetFields' import { MediaPick, Section } from './SignageFields' import { CELL_KINDS, cellWidget, fillPlace, FONT_KEYS, WIDGET_COLOURS, moved, newWidget, pickedAfterMove, presetWidget, WEATHER_CHOICES, weatherChoice, WIDGET_KINDS, WIDGET_POSITIONS, } from './signageLogic' -const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, text: Type, qr: QrCode, weather: CloudSun, menu: UtensilsCrossed, hstack: Columns3, vstack: Rows3 } +const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, text: Type, qr: QrCode, weather: CloudSun, menu: UtensilsCrossed, hstack: Columns3, vstack: Rows3, + shape: Shapes, ticker: MoveHorizontal, countdown: Timer, hours: CalendarClock, wifi: Wifi, contact: Contact } const iconOf = w => (w.kind === 'stack' ? (w.direction === 'column' ? Rows3 : Columns3) : ICON[w.kind] || LayoutList) const kindLabel = (t, w) => t(`signage.widgets.kinds.${w.kind === 'stack' ? (w.direction === 'column' ? 'vstack' : 'hstack') : w.kind}`) const ROW = 'grid gap-4 items-end grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]' @@ -177,7 +182,7 @@ function VerticalField({ w, set }) { } // which widgets have text (their colour, font, style and size), a QR code's own colours, a plate -const TEXT_KINDS = ['name', 'date', 'clock', 'message', 'text', 'qr', 'weather'] +const TEXT_KINDS = ['name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'ticker', 'countdown', 'hours', 'wifi', 'contact'] /** * A widget's own look (owner review 5), folded under "Text and colours": its colour (text and @@ -187,7 +192,7 @@ const TEXT_KINDS = ['name', 'date', 'clock', 'message', 'text', 'qr', 'weather'] function LookFields({ w, set }) { const { t } = useTranslation('manager') const [open, setOpen] = useState(false) - if (w.kind === 'menu' || w.kind === 'stack') return null + if (w.kind === 'menu' || w.kind === 'stack' || w.kind === 'shape') return null const text = TEXT_KINDS.includes(w.kind) const changed = !!(w.colour || w.background_colour || w.font || w.bold != null || w.italic || w.underline || (w.text_size && w.text_size !== 100) || w.qr_colour || w.qr_background) const styles = [w.bold !== false && 'bold', w.italic && 'italic', w.underline && 'underline'].filter(Boolean) @@ -218,7 +223,7 @@ function LookFields({ w, set }) { set({ text_size })} testId="signage-widget-text-size" /> } - {w.kind === 'qr' && <> + {(w.kind === 'qr' || w.kind === 'wifi') && <> set({ qr_colour })} testId="signage-widget-qr-colour" opacity={false} /> set({ qr_background })} testId="signage-widget-qr-background" /> } @@ -249,6 +254,7 @@ function MessageHint() { /** The options only some widgets have, on the same row as where / size / alignment. */ function InlineFields({ w, set }) { const { t } = useTranslation('manager') + if (['shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact'].includes(w.kind)) return if (w.kind === 'message') { return ( @@ -305,6 +311,7 @@ function InlineFields({ w, set }) { /** What needs more room, under the row: the picture, hints, the QR's own link, a menu's list, a stack's parts. */ function BelowFields({ w, set, media, onMedia, extras, path, depth, selected, onSelect }) { const { t } = useTranslation('manager') + if (['shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact'].includes(w.kind)) return if (w.kind === 'logo') { return { onMedia(item); set({ media_id: item.id }) }} /> diff --git a/manager_dashboard/src/pages/signage/signageLogic.js b/manager_dashboard/src/pages/signage/signageLogic.js index a89aaee..f6f9f76 100644 --- a/manager_dashboard/src/pages/signage/signageLogic.js +++ b/manager_dashboard/src/pages/signage/signageLogic.js @@ -137,9 +137,9 @@ export function mediaLookup(map) { // ── menu boards and widgets (5.6b) ─────────────────────────────────────────── -export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu'] +export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact'] /** What a stack's part can show (2026-11-21): a widget, a stack one level deep, a library slide. */ -export const CELL_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu'] +export const CELL_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact'] /** A new widget of a kind ('hstack' / 'vstack': a stack side by side / one over the other), where it * usually goes: a menu or a stack in a box of its own (they fill a box). */ @@ -151,16 +151,24 @@ export function newWidget(kind) { if (kind === 'menu') { return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 55, y: 10, w: 40, h: 80 }, board: { select: 'all', columns: 1, sales_point: 'in_store' } } } - return { kind, position: kind === 'message' || kind === 'text' ? 'bottom-bar' : 'top-right', size: 'medium', align: 'auto', - ...(kind === 'text' ? { text: '' } : {}) } + if (kind === 'shape') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 40, y: 30, w: 20, h: 35 }, shape: 'rectangle', radius: 10 } + return { kind, position: NEW_PLACE[kind] || 'top-right', size: 'medium', align: 'auto', + ...(kind === 'text' || kind === 'ticker' ? { text: '' } : {}), ...(kind === 'countdown' ? { countdown_to: '17:00' } : {}) } } +/** The contact details a contact widget can show (routers/identity.py Contact, signage ContactKey). */ +export const CONTACT_KEYS = ['phone', 'phone2', 'email', 'address', 'website', 'google', 'facebook', 'instagram', 'tiktok', 'tripadvisor', 'whatsapp', 'viber'] + +// where a new widget goes (6R.15 kinds; the others top right, texts in the bottom bar) +const NEW_PLACE = { message: 'bottom-bar', text: 'bottom-bar', ticker: 'bottom-bar', countdown: 'top-center', hours: 'top-left', wifi: 'bottom-right', contact: 'bottom-left' } + /** A widget put in a stack's part: only what it shows (a part has no corner, size or box). */ export function cellWidget(kind) { if (kind === 'hstack' || kind === 'vstack') { return { kind: 'stack', direction: kind === 'hstack' ? 'row' : 'column', align: 'auto', cells: [{ share: 50 }, { share: 50 }] } } - return { kind, align: 'auto', ...(kind === 'menu' ? { board: { select: 'all', columns: 1, sales_point: 'in_store' } } : {}), ...(kind === 'text' ? { text: '' } : {}) } + return { kind, align: 'auto', ...(kind === 'menu' ? { board: { select: 'all', columns: 1, sales_point: 'in_store' } } : {}), ...(kind === 'text' || kind === 'ticker' ? { text: '' } : {}), + ...(kind === 'countdown' ? { countdown_to: '17:00' } : {}) } } /** The weather's days, as one choice: from (0 today, 1 tomorrow, 2 the day after) and how many. */ @@ -388,7 +396,7 @@ export function toggleMonthDay(line, key) { /** A menu's colours until the venue picks its own (the TV's data, as the player draws them). */ export const MENU_COLOURS = { accent: '#f59e0b', text: '#ffffff', newBadge: '#38bdf8' } /** A widget's colours before the venue picks its own (owner review 5). */ -export const WIDGET_COLOURS = { text: '#ffffff', plate: '#00000080', qr: '#000000', qrBackground: '#ffffff' } +export const WIDGET_COLOURS = { text: '#ffffff', plate: '#00000080', qr: '#000000', qrBackground: '#ffffff', shape: '#f59e0b' } /** A menu's look as new ("Reset the look", owner review 4): every part back to the board's. */ export const MENU_LOOK_DEFAULTS = { diff --git a/manager_dashboard/src/shell/useIdentity.js b/manager_dashboard/src/shell/useIdentity.js index 45a99cc..99ce840 100644 --- a/manager_dashboard/src/shell/useIdentity.js +++ b/manager_dashboard/src/shell/useIdentity.js @@ -5,6 +5,13 @@ import client from '../api/client' export const IDENTITY_KEY = ['identity'] +/** The venue's opening hours (6R.15): { days: [[{from, to}]…7], note, set }; edited on the Schedule page. */ +export const HOURS_KEY = ['opening-hours'] +export function useHours() { + const can = useCan('core.dashboard.access') + return useQuery({ queryKey: HOURS_KEY, queryFn: () => client.get('/api/identity/hours').then(r => r.data), enabled: !!can, staleTime: 60_000 }) +} + /** The venue's identity ({ name, slogan, colours, logos, wifi, contact }); data undefined while it loads. */ export function useIdentity() { const can = useCan('core.dashboard.access') diff --git a/manager_dashboard/tests/staff.test.mjs b/manager_dashboard/tests/staff.test.mjs index 422ff0f..b4f4abb 100644 --- a/manager_dashboard/tests/staff.test.mjs +++ b/manager_dashboard/tests/staff.test.mjs @@ -5,7 +5,7 @@ import { customKeys, filterStaff, groupCounts, groupOf, staffBody, staffForm, staffProblems, validPin, zonesBody, zonesOf, zonesSummary, } from '../src/pages/staff/staffLogic.js' import { - addDays, clashWith, gridOf, hourMarks, hoursOf, inOpening, loadView, overlaps, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals, + addDays, clashWith, gridOf, hourMarks, hoursOf, hoursValid, inOpening, inSpans, loadView, overlaps, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals, } from '../src/pages/schedule/scheduleLogic.js' const staff = [ @@ -79,6 +79,12 @@ test('shifts: hours past midnight, clashes, the grid, states, totals, the timeli assert.equal(hourMarks(22)[2], 0) assert.equal(inOpening(23, '18:00', '02:00'), true) assert.equal(inOpening(3, '18:00', '02:00'), false) + // the venue's hours, several spans a day (6R.15) + assert.equal(inSpans(13, [{ from: '12:00', to: '15:00' }, { from: '18:00', to: '23:00' }]), true) + assert.equal(inSpans(16, [{ from: '12:00', to: '15:00' }, { from: '18:00', to: '23:00' }]), false) + assert.equal(inSpans(10, undefined), false) + assert.equal(hoursValid([[{ from: '12:00', to: '15:00' }], []]), true) + assert.equal(hoursValid([[{ from: '12:00', to: '' }]]), false) }) test('the view settings stay in this browser and survive a broken store', () => { diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index ea28bc0..54c7dd6 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -1480,7 +1480,13 @@ "text": "Κείμενο", "menu": "Μενού", "hstack": "Οριζόντια στοίβα", - "vstack": "Κάθετη στοίβα" + "vstack": "Κάθετη στοίβα", + "shape": "Σχήμα", + "ticker": "Κυλιόμενο κείμενο", + "countdown": "Αντίστροφη μέτρηση", + "hours": "Ωράριο", + "wifi": "Wi-Fi", + "contact": "Στοιχεία επικοινωνίας" }, "position": "Πού", "size": "Μέγεθος", @@ -1569,7 +1575,94 @@ "qrBackground": "Φόντο κωδικού QR", "changeMessage": "Αλλαγή μηνύματος", "full_one": "Αυτή η διαφάνεια έχει τα περισσότερα widgets που επιτρέπονται ({{count}}). Προβολή → Μήνυμα & ρυθμίσεις → Απόδοση.", - "full_other": "Αυτή η διαφάνεια έχει τα περισσότερα widgets που επιτρέπονται ({{count}}). Προβολή → Μήνυμα & ρυθμίσεις → Απόδοση." + "full_other": "Αυτή η διαφάνεια έχει τα περισσότερα widgets που επιτρέπονται ({{count}}). Προβολή → Μήνυμα & ρυθμίσεις → Απόδοση.", + "shape": { + "kind": "Σχήμα", + "kinds": { + "rectangle": "Ορθογώνιο", + "circle": "Κύκλος / έλλειψη", + "triangle": "Τρίγωνο", + "polygon": "Πολύγωνο", + "star": "Αστέρι", + "custom": "Δικές σας γωνίες" + }, + "sides": "Πλευρές", + "points": "Ακτίνες", + "custom": "Γωνίες", + "customHint": "Κάθε γωνία ως x,y σε % του πλαισίου του σχήματος, χωρισμένες με κενά.", + "fill": "Γέμισμα", + "fillTo": "Διαβάθμιση προς", + "oneColour": "Ένα χρώμα", + "angle": "Κατεύθυνση διαβάθμισης", + "stroke": "Περίγραμμα", + "noStroke": "Χωρίς περίγραμμα", + "strokeWidth": "Πάχος περιγράμματος", + "inner": "Βάθος αστεριού", + "radius": "Στρογγυλεμένες γωνίες" + }, + "ticker": { + "text": "Το κείμενο", + "direction": "Κινείται", + "directions": { + "left": "Προς τα αριστερά", + "right": "Προς τα δεξιά" + }, + "speed": "Ταχύτητα" + }, + "countdown": { + "title": "Τίτλος", + "titlePlaceholder": "π.χ. Το happy hour τελειώνει σε", + "ends": "Τελειώνει", + "modes": { + "daily": "Κάθε μέρα", + "date": "Σε ημερομηνία" + }, + "everyDayAt": "Κάθε μέρα στις", + "at": "Στις", + "starts": "Αρχίζει να μετρά", + "startModes": { + "now": "Πάντα (από οποιαδήποτε ώρα)", + "before": "Λίγη ώρα πριν το τέλος", + "at": "Σε ορισμένη ώρα" + }, + "minutesBefore": "Λεπτά πριν το τέλος", + "min": "λεπ.", + "startsAt": "Αρχίζει στις", + "waiting": "Πριν αρχίσει", + "waitingModes": { + "full": "Δείχνει όλο τον χρόνο, σταματημένο", + "hide": "Κρύβεται" + }, + "done": "Όταν τελειώσει, δείχνει", + "doneHint": "Κενό: η μέτρηση κρύβεται.", + "donePlaceholder": "π.χ. Ώρα για happy hour!" + }, + "hours": { + "style": "Δείχνει", + "styles": { + "week": "Την εβδομάδα", + "today": "Σήμερα" + }, + "titlePlaceholder": "π.χ. Ωράριο λειτουργίας", + "group": "Μέρες με το ίδιο ωράριο σε μία γραμμή", + "groupHint": "Π.χ. Δευ–Παρ 12:00–23:00.", + "missing": "Το ωράριο του καταστήματος δεν έχει οριστεί ακόμη: το widget μένει κρυφό.", + "setThem": "Ορίστε το στη σελίδα Πρόγραμμα" + }, + "wifi": { + "shows": "Δείχνει", + "qr": "Κωδικό σύνδεσης (QR)", + "password": "Τον κωδικό", + "missing": "Το Wi-Fi πελατών δεν έχει οριστεί ακόμη: το widget μένει κρυφό.", + "hint": "Το δίκτυο και ο κωδικός έρχονται από την ταυτότητα του καταστήματος." + }, + "contact": { + "shows": "Δείχνει", + "none": "Τίποτα", + "missing": "Κανένα από αυτά τα στοιχεία δεν έχει οριστεί ακόμη: το widget μένει κρυφό.", + "hint": "Τα στοιχεία έρχονται από την ταυτότητα του καταστήματος· τα κενά δεν εμφανίζονται." + }, + "fromIdentity": "Ρυθμίσεις → Ταυτότητα" }, "tabs": { "playlists": "Λίστες", @@ -3507,7 +3600,19 @@ "firstHourHint": "Για την προβολή «Ανά ώρα».", "opens": "Ανοίγει", "closes": "Κλείνει", - "openingHint": "Σκιασμένα στον άξονα." + "openingHint": "Σκιασμένα στον άξονα.", + "openingButton": "Ωράριο", + "openingTitle": "Ωράριο λειτουργίας", + "openingIntro": "Πότε είναι ανοιχτό το κατάστημα, μέρα με τη μέρα (έως τρία διαστήματα τη μέρα· ένα διάστημα μπορεί να περνά τα μεσάνυχτα). Σκιάζεται στη χρονογραμμή και εμφανίζεται από το widget ωραρίου της ψηφιακής σήμανσης.", + "openingSaved": "Το ωράριο αποθηκεύτηκε", + "closedDay": "Κλειστά", + "removeSpan": "Αφαίρεση ωρών", + "addSpan": "Προσθήκη ωρών", + "openThisDay": "Ανοιχτά αυτή τη μέρα", + "copyToAll": "Ίδιο για κάθε μέρα", + "openingNote": "Σημείωση", + "openingNoteHint": "Π.χ. «Κλειστά τις αργίες» (προαιρετικό).", + "openingInvalid": "Κάθε διάστημα χρειάζεται δύο διαφορετικές ώρες." }, "reports": { "failed": "Η αναφορά δεν φορτώθηκε.", diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index 2d67b91..725ea3d 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -491,7 +491,8 @@ "calibrate": { "title": "Βαθμονόμηση εικόνας: {{name}}", "hint": "Στον διαχειριστή (Ψηφιακή σήμανση → Οθόνες) μετακινήστε κάθε άκρη μέχρι τα βέλη να ακουμπούν τις άκρες της οθόνης." - } + }, + "closed": "Κλειστά" }, "menuTablet": { "title": "Μενού", diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 7596238..481b130 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -1480,7 +1480,13 @@ "text": "Text", "menu": "Menu", "hstack": "Horizontal stack", - "vstack": "Vertical stack" + "vstack": "Vertical stack", + "shape": "Shape", + "ticker": "Scrolling text", + "countdown": "Countdown", + "hours": "Opening hours", + "wifi": "Wi-Fi", + "contact": "Contact details" }, "position": "Where", "size": "Size", @@ -1569,7 +1575,94 @@ "qrBackground": "QR code background", "changeMessage": "Change the message", "full_one": "This slide holds the most widgets allowed ({{count}}). Signage → Message & settings → Performance.", - "full_other": "This slide holds the most widgets allowed ({{count}}). Signage → Message & settings → Performance." + "full_other": "This slide holds the most widgets allowed ({{count}}). Signage → Message & settings → Performance.", + "shape": { + "kind": "Shape", + "kinds": { + "rectangle": "Rectangle", + "circle": "Circle / ellipse", + "triangle": "Triangle", + "polygon": "Polygon", + "star": "Star", + "custom": "Your own corners" + }, + "sides": "Sides", + "points": "Points", + "custom": "Corners", + "customHint": "Each corner as x,y in % of the shape's box, separated by spaces.", + "fill": "Fill", + "fillTo": "Gradient to", + "oneColour": "One colour", + "angle": "Gradient direction", + "stroke": "Border", + "noStroke": "No border", + "strokeWidth": "Border width", + "inner": "Star depth", + "radius": "Rounded corners" + }, + "ticker": { + "text": "The text", + "direction": "Moves", + "directions": { + "left": "To the left", + "right": "To the right" + }, + "speed": "Speed" + }, + "countdown": { + "title": "Title", + "titlePlaceholder": "e.g. Happy hour ends in", + "ends": "Ends", + "modes": { + "daily": "Every day", + "date": "On a date" + }, + "everyDayAt": "Every day at", + "at": "At", + "starts": "Starts counting", + "startModes": { + "now": "Always (from any time)", + "before": "A time before the end", + "at": "At a set time" + }, + "minutesBefore": "Minutes before the end", + "min": "min", + "startsAt": "Starts at", + "waiting": "Before it starts", + "waitingModes": { + "full": "Show the whole time, standing", + "hide": "Hide it" + }, + "done": "When it ends, show", + "doneHint": "Empty: the countdown hides.", + "donePlaceholder": "e.g. It's happy hour!" + }, + "hours": { + "style": "Shows", + "styles": { + "week": "The week", + "today": "Today" + }, + "titlePlaceholder": "e.g. Opening hours", + "group": "Days with the same hours on one line", + "groupHint": "E.g. Mon–Fri 12:00–23:00.", + "missing": "The venue's opening hours aren't set yet: the widget stays hidden.", + "setThem": "Set them on the Schedule page" + }, + "wifi": { + "shows": "Shows", + "qr": "A code to join", + "password": "The password", + "missing": "The guests' Wi-Fi isn't set yet: the widget stays hidden.", + "hint": "The network and password come from the venue's identity." + }, + "contact": { + "shows": "Shows", + "none": "Nothing chosen", + "missing": "None of these contact details is set yet: the widget stays hidden.", + "hint": "The details come from the venue's identity; empty ones don't show." + }, + "fromIdentity": "Settings → Identity" }, "tabs": { "playlists": "Playlists", @@ -3507,7 +3600,19 @@ "firstHourHint": "For the \"By hour\" view.", "opens": "Opens", "closes": "Closes", - "openingHint": "Shaded on the timeline." + "openingHint": "Shaded on the timeline.", + "openingButton": "Opening hours", + "openingTitle": "Opening hours", + "openingIntro": "When the venue is open, day by day (up to three spans a day; a span may pass midnight). Shaded on the timeline and shown by signage's opening hours widget.", + "openingSaved": "Opening hours saved", + "closedDay": "Closed", + "removeSpan": "Remove these hours", + "addSpan": "Add hours", + "openThisDay": "Open this day", + "copyToAll": "Same for every day", + "openingNote": "A note", + "openingNoteHint": "E.g. \"Closed on holidays\" (optional).", + "openingInvalid": "Each span needs two different times." }, "reports": { "failed": "This report couldn't be loaded.", diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index 4517eb9..d60a60e 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -491,7 +491,8 @@ "calibrate": { "title": "Calibrating the picture of {{name}}", "hint": "In the manager (Signage → Screens), move each edge until the arrows touch the edges of the screen." - } + }, + "closed": "Closed" }, "menuTablet": { "title": "Menu", diff --git a/packages/signage/src/Slides.jsx b/packages/signage/src/Slides.jsx index 619bd9b..bb8223a 100644 --- a/packages/signage/src/Slides.jsx +++ b/packages/signage/src/Slides.jsx @@ -2,12 +2,13 @@ // fonts and sizes here are the venue's own choices for its TV (slide content = data, CS-16), so // they are inline styles, not tokens. Sizes scale with the screen (cqmin), so a slide looks the // same on any TV. -import { Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Moon, Sun } from 'lucide-react' +import { useEffect, useRef, useState } from 'react' +import { Camera, Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Globe, Lock, Mail, MapPin, MessageCircle, Moon, Music, Phone, Star, Sun, ThumbsUp, Wifi } from 'lucide-react' import { QRCodeSVG } from 'qrcode.react' import { BADGE_ICONS } from './badges' import { cq, CQ_BOX } from './cq' import { useFormat, useTranslation } from '@xenia/i18n' -import { badgeColours, badgeName, cellWidgets, TIGHT, fitUnit, FONTS, itemBadges, menuLook, menuPages, pageAt, priceChars, textWidth, visibleGroups, weatherIcon, widgetAlign } from './logic' +import { badgeColours, badgeName, cellWidgets, countdownState, countdownText, TIGHT, fitUnit, FONTS, hoursRows, itemBadges, localNow, menuLook, menuPages, pageAt, priceChars, shapePoints, textWidth, visibleGroups, weatherIcon, widgetAlign, wifiQr } from './logic' /** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */ export function Background({ bg, media }) { @@ -173,8 +174,8 @@ const plate = (w, pad) => ({ ...(w.colour ? { color: w.colour } : {}), ...(w.background_colour ? { background: w.background_colour, borderRadius: cq(1.2), ...(pad ? { padding: `${cq(0.8)} ${cq(1.6)}` } : {}) } : {}), }) -// a menu or a stack in a corner or a bar has no box of its own: it gets one of this size (cqmin) -const BOXED = { menu: [48, 56], stack: [60, 36] } +// a menu, a stack, a shape or a scrolling text in a corner or a bar has no box of its own: it gets one of this size (cqmin) +const BOXED = { menu: [48, 56], stack: [60, 36], shape: [18, 18], ticker: [80, 7] } /** * The widgets of a slide: in their corners and bars, or (moved and sized by hand: position @@ -186,8 +187,9 @@ const BOXED = { menu: [48, 56], stack: [60, 36] } */ export function Widgets({ widgets, media, venue, now, colour, extras, embed }) { const fmt = useFormat() + const { t } = useTranslation('terminal') if (!widgets?.length) return null - const ctx = { media, venue, now, fmt, extras: extras || {}, embed } + const ctx = { media, venue, now, fmt, extras: extras || {}, embed, t } const shown = widgets.map((w, i) => [w, i, widgetBody(w, ctx, placedBy(w), String(i))]).filter(([, , body]) => body) const bar = where => shown.filter(([w]) => w.position === where) const bars = [['top-bar', { top: 0 }], ['bottom-bar', { bottom: 0 }]] @@ -198,7 +200,8 @@ export function Widgets({ widgets, media, venue, now, colour, extras, embed }) { style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: cq(3), padding: `${cq(2)} ${cq(4)}`, background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: cq(9) }}> {bar(where).map(([w, i, body]) => ( -
{body}
+
{body}
))} ))} @@ -307,9 +310,171 @@ function widgetBody(w, ctx, fit, path) { if (w.kind === 'weather') return weatherBody(w, venue?.weather, unit, text, formatDate) if (w.kind === 'menu') return boxed(, 'menu') if (w.kind === 'stack') return boxed(, 'stack') + // 6R.15 + if (w.kind === 'shape') return boxed(, 'shape') + if (w.kind === 'ticker') { + if (!w.text) return null + const inBar = (w.position || '').endsWith('-bar') + const u = fit ? fitUnit(3.4 * 1.3, 0.1) : n => cq(+(n * s).toFixed(3)) + const body = + return inBar ? body : boxed(body, 'ticker') + } + if (w.kind === 'countdown') { + const st = countdownState(w, localNow(venue?.timezone, now), now.getSeconds()) + if (st.state === 'none' || (st.state === 'waiting' && w.countdown_waiting === 'hide')) return null + if (st.state === 'done') return w.countdown_done_hide || !w.countdown_done ? null : line(w.countdown_done, 'signage-w-countdown-done', 700) + const digits = countdownText(st.left) + const label = w.text || '' + const u = unit((label ? 2.4 * 1.15 + 0.4 : 0) + 6 * 1.1, Math.max(textWidth(digits.length, 6) * 0.9, label ? textWidth(label.length, 2.4) : 0)) + return ( +
+ {label && {label}} + {digits} +
+ ) + } + if (w.kind === 'hours') return hoursBody(w, ctx, unit, text) + if (w.kind === 'wifi') return wifiBody(w, venue?.identity?.wifi, unit, text) + if (w.kind === 'contact') return contactBody(w, venue?.identity?.contact, unit, text) return null } +/** A shape (6R.15) filling its box: a rectangle (rounded corners) or circle as a box, the others as SVG corners; a fill or a gradient, a border. */ +function ShapeBody({ w, id }) { + const fill = w.fill || '#f59e0b' + const angle = w.fill_angle ?? 180 + const border = w.stroke && w.stroke_width ? cq(+(w.stroke_width / 2).toFixed(2)) : null // ½ % of its shorter side a step + const pts = shapePoints(w) + if (!pts) { + return ( +
+ ) + } + const rad = (angle * Math.PI) / 180 + const dx = Math.sin(rad) / 2 + const dy = -Math.cos(rad) / 2 + return ( + + ) +} + +/** A scrolling text (6R.15): one line moving across its place, round and round; its speed follows its height. */ +function Ticker({ w, style }) { + const box = useRef(null) + const run = useRef(null) + const [size, setSize] = useState(null) + useEffect(() => { + const el = box.current + if (!el || typeof ResizeObserver === 'undefined') return undefined + const ro = new ResizeObserver(() => setSize(s => (s && s.w === el.clientWidth && s.h === el.clientHeight ? s : { w: el.clientWidth, h: el.clientHeight }))) + ro.observe(el) + return () => ro.disconnect() + }, []) + useEffect(() => { + const r = run.current + if (!size || !r?.animate) return undefined + const T = r.scrollWidth + const left = (w.ticker_direction || 'left') === 'left' + const pxPerS = (w.ticker_speed || 4) * Math.max(8, r.offsetHeight) * 0.9 + const a = r.animate([{ transform: `translateX(${left ? size.w : -T}px)` }, { transform: `translateX(${left ? -T : size.w}px)` }], + { duration: ((size.w + T) / pxPerS) * 1000, iterations: Infinity }) + return () => a.cancel() + }, [size, w.text, w.ticker_speed, w.ticker_direction, style.fontSize]) + return ( +
+ {w.text} +
+ ) +} + +const MONDAY = '2026-11-16' // a Monday: day names from the venue's language +const dayShort = (fmt, i) => fmt.formatDate(`2026-11-${16 + i}T12:00:00Z`, 'weekday').slice(0, 3) + +/** The opening hours (6R.15): the week (days with the same hours on one line) or today; today stands out. */ +function hoursBody(w, ctx, unit, text) { + const { venue, now, fmt, t } = ctx + const hours = venue?.hours + if (!hours?.set) return null + const today = localNow(venue?.timezone, now).weekday + const rows = hoursRows(hours, { group: w.hours_group !== false, today, only: w.hours_style === 'today' ? today : null }) + const daysText = r => (r.days.length > 1 ? `${dayShort(fmt, r.days[0])}–${dayShort(fmt, r.days[r.days.length - 1])}` : dayShort(fmt, r.days[0])) + const spansText = r => (r.spans.length ? r.spans.map(x => `${x.from}–${x.to}`).join(', ') : t('signage.closed')) + const widest = Math.max(...rows.map(r => daysText(r).length + 2 + spansText(r).length), w.text ? w.text.length : 0) + const u = unit((rows.length + (w.text ? 1.3 : 0)) * 3 * 1.35, textWidth(widest, 3)) + return ( +
+ {w.text && {w.text}} + {rows.map(r => ( + + {daysText(r)} + {spansText(r)} + + ))} +
+ ) +} + +/** The guests' Wi-Fi (6R.15, from the identity): its code to join, the network and the password. */ +function wifiBody(w, wifi, unit, text) { + if (!wifi?.ssid) return null + const qr = w.wifi_qr !== false ? wifiQr(wifi) : '' + const pw = w.wifi_password !== false && wifi.security !== 'nopass' && wifi.password ? wifi.password : '' + const lines = [wifi.ssid, pw, wifi.note].filter(Boolean) + const chars = Math.max(...lines.map(l => l.length)) + 2 + const u = unit(Math.max(qr ? 13 : 0, lines.length * 3.4 * 1.35), (qr ? 14.5 : 0) + textWidth(chars, 3.4)) + const icon = { width: u(3), height: u(3), flexShrink: 0 } + return ( +
+ {qr && ( +
+ +
+ )} +
+ + {pw && } + {wifi.note && {wifi.note}} +
+
+ ) +} + +const CONTACT_ICONS = { phone: Phone, phone2: Phone, email: Mail, address: MapPin, website: Globe, google: MapPin, facebook: ThumbsUp, + instagram: Camera, tiktok: Music, tripadvisor: Star, whatsapp: MessageCircle, viber: MessageCircle } + +/** The venue's contact details (6R.15, from the identity): the chosen ones that are set, one a line with an icon. */ +function contactBody(w, contact, unit, text) { + const rows = (w.contact_fields || ['phone', 'website', 'instagram']).filter(k => contact?.[k]).map(k => [k, contact[k]]) + if (!rows.length) return null + const u = unit(rows.length * 3.2 * 1.4, textWidth(Math.max(...rows.map(([, v]) => v.length)) + 2, 3.2)) + return ( +
+ {rows.map(([k, v]) => { + const Icon = CONTACT_ICONS[k] || Globe + return ( + + + ) + })} +
+ ) +} + /** The weather: now or a day of the forecast (today, tomorrow, the day after), and the next days; * its picture and degrees, only the picture or only the degrees (2026-11-21). */ function weatherBody(w, wx, unit, text, formatDate) { diff --git a/packages/signage/src/logic.js b/packages/signage/src/logic.js index a1ec710..552c2ca 100644 --- a/packages/signage/src/logic.js +++ b/packages/signage/src/logic.js @@ -275,7 +275,7 @@ export function visibleGroups(groups) { /** Widgets whose box, placed by hand, is exactly their content (owner review 6): its height (× the * widget's text size) sets the size, its width follows. A menu or a stack fills its box. */ -export const TIGHT = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather'] +export const TIGHT = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'countdown', 'hours', 'wifi', 'contact'] /** The slide kinds that carry widgets. */ export const WIDGET_HOSTS = ['text', 'menu', 'blank'] @@ -519,3 +519,89 @@ export function wifiQr(wifi) { const pw = sec !== 'nopass' && wifi.password ? `P:${esc(wifi.password)};` : '' return `WIFI:T:${sec};S:${esc(wifi.ssid)};${pw}${wifi.hidden ? 'H:true;' : ''};` } + +// ── widgets of 6R.15: countdown, opening hours, shapes ─────────────────────── + +const minOf = hhmm => { const [h, m] = hhmm.split(':').map(Number); return h * 60 + m } +const dayNo = date => Date.UTC(+date.slice(0, 4), +date.slice(5, 7) - 1, +date.slice(8, 10)) / 86_400_000 + +/** A countdown's moment ("HH:MM" = that time today; "YYYY-MM-DDTHH:MM") in minutes from the venue's local midnight today. */ +function momentMin(when, local) { + if (!when) return null + if (when.length === 5) return minOf(when) + return (dayNo(when.slice(0, 10)) - dayNo(local.date)) * 1440 + minOf(when.slice(11)) +} + +/** + * Where a countdown stands (6R.15) at venue time `local` ({ date, minutes }) and `seconds` past the + * minute: 'none' (no end set), 'waiting' (before it starts: `left` = its whole span), 'running' + * (`left` = seconds to the end), 'done' (the end has passed, today or for good). + */ +export function countdownState(w, local, seconds = 0) { + const end = momentMin(w?.countdown_to, local) + if (end == null) return { state: 'none', left: 0 } + const nowS = local.minutes * 60 + seconds + const endS = end * 60 + let startS = null + if (w.countdown_start === 'before') startS = endS - (w.countdown_before || 120) * 60 + else if (w.countdown_start === 'at') { + const at = momentMin(w.countdown_at, local) + if (at != null) startS = at * 60 + } + if (nowS >= endS) return { state: 'done', left: 0 } + if (startS != null && nowS < startS) return { state: 'waiting', left: endS - startS } + return { state: 'running', left: endS - nowS } +} + +/** Seconds as "1:30:00", "05:09" under an hour, "3d 04:10:00" over a day. */ +export function countdownText(left) { + const s = Math.max(0, Math.floor(left)) + const d = Math.floor(s / 86400) + const h = Math.floor((s % 86400) / 3600) + const m = Math.floor((s % 3600) / 60) + const two = n => String(n).padStart(2, '0') + if (d) return `${d}d ${two(h)}:${two(m)}:${two(s % 60)}` + return h ? `${h}:${two(m)}:${two(s % 60)}` : `${two(m)}:${two(s % 60)}` +} + +/** + * The opening hours as lines (6R.15): [{ days: [0…6] (Monday 0), spans: [{from, to}] ([] closed), + * today }]; with `group`, days next to each other with the same hours share a line ("Mon–Fri"). + * `only`: one weekday (the "today" style). + */ +export function hoursRows(hours, { group = true, today = -1, only = null } = {}) { + const days = hours?.days || [] + if (days.length !== 7) return [] + const key = i => JSON.stringify(days[i] || []) + const rows = [] + for (let i = 0; i < 7; i++) { + if (only != null && i !== only) continue + const last = rows[rows.length - 1] + if (group && only == null && last && key(last.days[last.days.length - 1]) === key(i) && last.days[last.days.length - 1] === i - 1) last.days.push(i) + else rows.push({ days: [i], spans: days[i] || [] }) + } + return rows.map(r => ({ ...r, today: r.days.includes(today) })) +} + +/** A shape's corners as SVG points in a 100 × 100 box (polygon, star, triangle, custom "x,y x,y"); null for rectangle / circle. */ +export function shapePoints(w) { + const kind = w?.shape || 'rectangle' + const ring = (n, r, turn = 0) => Array.from({ length: n }, (_, i) => { + const a = -Math.PI / 2 + turn + (i * 2 * Math.PI) / n + return [50 + r * Math.cos(a), 50 + r * Math.sin(a)] + }) + let pts = null + if (kind === 'triangle') pts = [[50, 0], [100, 100], [0, 100]] + else if (kind === 'polygon') pts = ring(w.shape_sides || 6, 50) + else if (kind === 'star') { + const n = w.shape_sides || 5 + const outer = ring(n, 50) + const inner = ring(n, 50 * (w.shape_inner || 45) / 100, Math.PI / n) + pts = outer.flatMap((p, i) => [p, inner[i]]) + } else if (kind === 'custom') { + pts = String(w.shape_points || '').trim().split(/\s+/).map(p => p.split(',').map(Number)) + .filter(p => p.length === 2 && p.every(Number.isFinite)).map(([x, y]) => [Math.min(100, Math.max(0, x)), Math.min(100, Math.max(0, y))]) + if (pts.length < 3) pts = null + } + return pts ? pts.map(([x, y]) => `${+x.toFixed(2)},${+y.toFixed(2)}`).join(' ') : null +} diff --git a/packages/signage/tests/logic.test.mjs b/packages/signage/tests/logic.test.mjs index 7a790f6..eea3c2a 100644 --- a/packages/signage/tests/logic.test.mjs +++ b/packages/signage/tests/logic.test.mjs @@ -277,3 +277,41 @@ test('a Wi-Fi QR code: escaped, open networks without a password, hidden ones (6 assert.equal(wifiQr({ ssid: 'Open', password: 'x', security: 'nopass', hidden: true }), 'WIFI:T:nopass;S:Open;H:true;;') assert.equal(wifiQr({ password: 'x' }), '') }) + +test('a countdown: from a span before, waiting, running, done; a date; the text (6R.15)', async () => { + const { countdownState, countdownText } = await import('../src/logic.js') + const w = { countdown_to: '17:00', countdown_start: 'before', countdown_before: 120 } + const at = (hhmm, date = '2026-11-22') => ({ date, minutes: Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3)) }) + // the owner's case: ends at 5, starts 2 h before, the slide shows at 3:30 → 1:30:00 left + assert.deepEqual(countdownState(w, at('15:30')), { state: 'running', left: 5400 }) + assert.equal(countdownText(5400), '1:30:00') + assert.deepEqual(countdownState(w, at('14:00')), { state: 'waiting', left: 7200 }) + assert.equal(countdownState(w, at('17:00')).state, 'done') + assert.equal(countdownState({ countdown_to: '17:00' }, at('09:00')).left, 8 * 3600) + assert.equal(countdownState({ countdown_to: '17:00', countdown_start: 'at', countdown_at: '16:00' }, at('15:00')).state, 'waiting') + const ny = countdownState({ countdown_to: '2026-12-31T23:59' }, at('23:59', '2026-12-30'), 30) + assert.equal(ny.left, 86400 - 30) + assert.equal(countdownText(ny.left), '23:59:30') + assert.equal(countdownText(2 * 86400 + 61), '2d 00:01:01') + assert.equal(countdownText(309), '05:09') + assert.equal(countdownState({}, at('10:00')).state, 'none') +}) + +test('opening hours in lines: same hours grouped, today marked; shapes as points (6R.15)', async () => { + const { hoursRows, shapePoints } = await import('../src/logic.js') + const lunch = [{ from: '12:00', to: '23:00' }] + const hours = { days: [lunch, lunch, lunch, lunch, [{ from: '12:00', to: '01:00' }], [], lunch] } + const rows = hoursRows(hours, { today: 1 }) + assert.deepEqual(rows.map(r => r.days), [[0, 1, 2, 3], [4], [5], [6]]) + assert.equal(rows[0].today, true) + assert.deepEqual(rows[2].spans, []) + assert.equal(hoursRows(hours, { group: false }).length, 7) + assert.deepEqual(hoursRows(hours, { only: 5 }).map(r => r.days), [[5]]) + assert.deepEqual(hoursRows({ days: [] }), []) + assert.equal(shapePoints({ shape: 'triangle' }), '50,0 100,100 0,100') + assert.equal(shapePoints({ shape: 'star', shape_sides: 5 }).split(' ').length, 10) + assert.equal(shapePoints({ shape: 'polygon', shape_sides: 6 }).split(' ').length, 6) + assert.equal(shapePoints({ shape: 'custom', shape_points: '0,0 100,0 50,120' }), '0,0 100,0 50,100') + assert.equal(shapePoints({ shape: 'custom', shape_points: '1,1' }), null) + assert.equal(shapePoints({ shape: 'rectangle' }), null) +}) diff --git a/tests/e2e/signage.mjs b/tests/e2e/signage.mjs index 8a82a13..02a390e 100644 --- a/tests/e2e/signage.mjs +++ b/tests/e2e/signage.mjs @@ -577,6 +577,26 @@ try { await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { area_left: 0, area_top: 0, area_right: 0, area_bottom: 0 } }) await tv.setViewportSize({ width: 1280, height: 720 }) + // ── 6R.14 / 6R.15: the identity and opening hours feed the new widgets on the TV ── + const ident = await api('GET', '/api/identity', { token: boss }) + await api('PUT', '/api/identity', { token: boss, body: { name: ident.name || 'Taverna', wifi: { ssid: 'Xenia Guests', password: 'kalimera', security: 'WPA' }, + contact: { phone: '2310 123456', instagram: '@xenia' } } }) + await api('PUT', '/api/identity/hours', { token: boss, body: { days: [[{ from: '12:00', to: '23:00' }], [], [], [], [], [], []] } }) + const wl = await api('POST', '/api/signage/playlists', { token: boss, body: { name: 'New widgets', orientation: 'landscape' } }) + await api('POST', `/api/signage/playlists/${wl.id}/slides`, { token: boss, body: { kind: 'blank', duration_s: 60, content: { widgets: [ + { kind: 'shape', position: 'custom', box: { x: 2, y: 2, w: 10, h: 15 }, shape: 'star' }, + { kind: 'countdown', position: 'top-center', countdown_to: '2099-01-01T00:00', text: 'Opening in' }, + { kind: 'hours', position: 'top-left' }, { kind: 'wifi', position: 'bottom-right' }, { kind: 'contact', position: 'bottom-left' }, + { kind: 'ticker', position: 'top-bar', text: 'Fresh fish today' }] } } }) + await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: wl.id } }) + const widgetsOn = async () => (await Promise.all(['shape', 'countdown', 'hours', 'wifi', 'contact', 'ticker'].map(k => tv.getByTestId(`signage-w-${k}`).count()))).every(n => n === 1) + r.check('6R.15: a shape, a countdown, the opening hours, Wi-Fi (from the identity), contact details and a scrolling text on the TV', + await waitFor(async () => (await widgetsOn()) || null, 15_000, 300) === true) + r.check('6R.15: the Wi-Fi widget carries the code that joins the network', (await tv.getByTestId('signage-w-wifi').textContent()).includes('Xenia Guests') + && await tv.getByTestId('signage-w-wifi').locator('svg').count() > 0) + r.check('6R.15: the countdown runs (days left to 2099)', /^\d+d \d\d:\d\d:\d\d$/.test((await tv.getByTestId('signage-w-countdown').textContent()).replace('Opening in', '').trim())) + await tv.screenshot({ path: path.join(OUT, 'signage-new-widgets.png') }) + await mgr.context().close() await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } }) await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300)