diff --git a/docs/README.md b/docs/README.md index 0b04b74..614324d 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); 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/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); 6R.19 reviews (typed in by hand: setting `signage.reviews`, `GET/PUT /api/signage/reviews`, Message & settings → Reviews; `venue.reviews` on the screens; one at a time, a minimum of stars). The editor's widgets list is in layers (owner 2026-11-22): the top card is the last widget of the slide's list (drawn over the others), "Add a widget" (`AddWidgetMenu`) adds on top; 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/signage/manifest.py b/local_backend/modules/signage/manifest.py index cfc927b..748a31a 100644 --- a/local_backend/modules/signage/manifest.py +++ b/local_backend/modules/signage/manifest.py @@ -17,6 +17,7 @@ MODULE = Module( ), settings=( SettingDef('signage.message', '', 'The message of the day on every signage screen with a message widget (Signage > Message of the day).'), + SettingDef('signage.reviews', '[]', 'The reviews the venue typed in for the reviews widget (6R.19; JSON list; Signage > Message & settings).', type='json'), SettingDef('signage.weather.place', '', 'The place whose weather the screens show (picked from a town search in Signage).'), SettingDef('signage.weather.latitude', '', 'Latitude of the weather place.'), SettingDef('signage.weather.longitude', '', 'Longitude of the weather place.'), diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py index faa4f89..ad4d9cf 100644 --- a/local_backend/routers/signage.py +++ b/local_backend/routers/signage.py @@ -18,6 +18,7 @@ Manager side (signage.manage): PUT /api/signage/library/{id} change it (a screen showing it is told) DELETE /api/signage/library/{id} screens that had it as their default show nothing POST /api/signage/library/{id}/duplicate a copy + GET /api/signage/reviews the venue's reviews (6R.19); PUT: all of them at once GET /api/signage/screens the paired screens: playlist or slide, orientation, rotation, picture area (insets), fit, the window size it reported PUT /api/signage/screens/{id} {playlist_id | slide_id, orientation, rotation, area_*, fit} @@ -52,6 +53,7 @@ from services.ws_bus import broadcast_sync router = APIRouter() KEY = "signage.manage" MESSAGE = "signage.message" +REVIEWS = "signage.reviews" # the venue's reviews, typed in by hand (6R.19) MAX_WIDGETS = "signage.max_widgets" # widgets a slide may hold (owner review 6: Performance; 10 recommended) MAX_WIDGETS_CAP = 50 # never more, whatever the setting AREA_MAX = 4000 # px a screen's picture area may cut off one edge (6R.13) @@ -83,7 +85,8 @@ class Background(_Strict): WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack", - "shape", "ticker", "countdown", "hours", "wifi", "contact"] # 6R.15 + "shape", "ticker", "countdown", "hours", "wifi", "contact", # 6R.15 + "reviews"] # 6R.19 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"] @@ -308,6 +311,11 @@ class Widget(_Strict): 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) + # reviews (6R.19): the venue's, typed in under Message & settings; one at a time, turning + reviews_seconds: int = Field(default=8, ge=3, le=120) + reviews_min: int = Field(default=4, ge=1, le=5) # only reviews with at least these stars + reviews_stars: bool = True + reviews_name: bool = True @model_validator(mode="after") def _place(self): @@ -1434,6 +1442,46 @@ def put_performance(body: PerformanceBody, db: Session = Depends(get_db), user=D return {"max_widgets": body.max_widgets, "recommended": 10, "cap": MAX_WIDGETS_CAP} +class Review(_Strict): + """A review the venue typed in (6R.19): who, how many stars, what they wrote, when, where it was posted.""" + name: str = Field(min_length=1, max_length=60) + stars: int = Field(ge=1, le=5) + text: str = Field(min_length=1, max_length=400) + date: Optional[str] = Field(default=None, pattern=DATE) + source: Optional[str] = Field(default=None, max_length=40) # "Google", "Tripadvisor"… + + @field_validator("name", "text", "source") + @classmethod + def _trim(cls, v): + v = " ".join(str(v).split()) if v is not None else None + return v or None + + +class ReviewsBody(BaseModel): + reviews: List[Review] = Field(default_factory=list, max_length=100) + + +def reviews(db) -> list: + """The venue's reviews as stored (a broken value reads as none).""" + try: + return ReviewsBody(reviews=json.loads(_setting(db, REVIEWS) or "[]")).model_dump()["reviews"] + except Exception: + return [] + + +@router.get("/reviews") +def get_reviews(db: Session = Depends(get_db), user=Depends(require(KEY))): + return {"reviews": reviews(db)} + + +@router.put("/reviews") +def put_reviews(body: ReviewsBody, db: Session = Depends(get_db), user=Depends(require(KEY))): + _save_setting(db, REVIEWS, json.dumps(body.model_dump()["reviews"], ensure_ascii=False)) + db.commit() + tell_all_screens(db) + return {"reviews": reviews(db)} + + class BadgesBody(BaseModel): badges: list = Field(default_factory=list) @@ -1531,7 +1579,7 @@ def _venue(db) -> dict: 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, - "hours": hours_out(db)} + "hours": hours_out(db), "reviews": reviews(db)} class SlidePreviewBody(BaseModel): diff --git a/local_backend/tests/test_identity.py b/local_backend/tests/test_identity.py index ade6cb2..748a35b 100644 --- a/local_backend/tests/test_identity.py +++ b/local_backend/tests/test_identity.py @@ -84,3 +84,18 @@ def test_new_widgets_are_typed(client, owner_h): 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" + + +def test_reviews_typed_in_by_hand(client, owner_h, screens, sent): + body = {"reviews": [{"name": " Maria K. ", "stars": 5, "text": "Best octopus on the island", "date": "2026-11-01", "source": "Google"}, + {"name": "John", "stars": 3, "text": "OK"}]} + sent.clear() + r = client.put("/api/signage/reviews", headers=owner_h, json=body) + assert r.status_code == 200, r.text + got = r.json()["reviews"] + assert got[0]["name"] == "Maria K." and got[0]["text"] == "Best octopus on the island" and got[1]["date"] is None + assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent + assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]["reviews"][0]["stars"] == 5 + assert client.get("/api/signage/reviews", headers=owner_h).json()["reviews"][1]["name"] == "John" + assert client.put("/api/signage/reviews", headers=owner_h, json={"reviews": [{"name": "x", "stars": 6, "text": "y"}]}).status_code == 422 + assert client.put("/api/signage/reviews", headers=owner_h, json={"reviews": [{"name": "x", "stars": 5, "text": ""}]}).status_code == 422 diff --git a/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx b/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx index a4db2e2..c5a8ea1 100644 --- a/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx +++ b/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx @@ -1,11 +1,13 @@ // 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 +// countdown, the opening hours, the guests' Wi-Fi and the contact details; the reviews (6R.19). 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 { useEffect, useState } from 'react' 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 * as api from './signageApi' import { CONTACT_KEYS, WIDGET_COLOURS } from './signageLogic' const SHAPES = ['rectangle', 'circle', 'triangle', 'polygon', 'star', 'custom'] @@ -77,6 +79,17 @@ export function MoreInlineFields({ w, set }) { ) } + if (w.kind === 'reviews') { + return (<> + + set({ reviews_min })} data-testid="signage-widget-reviews-min" + options={[1, 2, 3, 4, 5].map(n => ({ value: n, label: `${n}+` }))} /> + + + set({ reviews_seconds: v ?? 3 })} /> + + ) + } if (w.kind === 'contact') { return ( @@ -159,6 +172,17 @@ export function MoreBelowFields({ w, set }) { ) } + if (w.kind === 'reviews') { + return ( +
+
+ set({ reviews_stars: on })} label={t(`${k}.reviews.stars`)} /> + set({ reviews_name: on })} label={t(`${k}.reviews.name`)} /> +
+ +
+ ) + } 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 @@ -171,3 +195,14 @@ export function MoreBelowFields({ w, set }) { } return null } + +/** Where the reviews come from, or a warning (with the way there) while there are none. */ +function ReviewsNote() { + const { t } = useTranslation('manager') + const [count, setCount] = useState(null) + useEffect(() => { api.getReviews().then(r => setCount(r.reviews.length)).catch(() => {}) }, []) + const link = {t('signage.widgets.reviews.where')} + return count === 0 + ? {link} + :

{t('signage.widgets.reviews.hint')} {link}

+} diff --git a/manager_dashboard/src/pages/signage/ReviewsSettings.jsx b/manager_dashboard/src/pages/signage/ReviewsSettings.jsx new file mode 100644 index 0000000..3b2a708 --- /dev/null +++ b/manager_dashboard/src/pages/signage/ReviewsSettings.jsx @@ -0,0 +1,79 @@ +// The venue's reviews (6R.19, owner 2026-11-22), under Signage → Message & settings: typed in by hand +// (who, stars, what they wrote, when, where it was posted) and shown one at a time by the reviews +// widget. Not pulled from Google (the owner's choice: no API key, no billing). Saved all at once. +import { useEffect, useMemo, useState } from 'react' +import toast from 'react-hot-toast' +import { ArrowDown, ArrowUp, Plus, Star, Trash2 } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Field, FieldRow, IconButton, Input, Segmented, Spinner, Textarea } from '@xenia/ui' +import * as api from './signageApi' +import { moved } from './signageLogic' + +const clean = list => list.map(r => ({ name: r.name.trim(), stars: r.stars, text: r.text.trim(), date: r.date || null, source: (r.source || '').trim() || null })) + +export default function ReviewsSettings() { + const { t } = useTranslation('manager') + const [saved, setSaved] = useState(null) + const [list, setList] = useState(null) + const [busy, setBusy] = useState(false) + useEffect(() => { + api.getReviews().then(r => { setSaved(r.reviews); setList(r.reviews) }).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((r, j) => (j === i ? { ...r, ...patch } : r))) + const bad = list.some(r => !r.name?.trim() || !r.text?.trim()) + const save = async () => { + setBusy(true) + try { const r = await api.putReviews(clean(list)); setSaved(r.reviews); setList(r.reviews); toast.success(t('settings.saved')) } + catch (err) { toast.error(errorMessage(err, t)) } + setBusy(false) + } + return ( +
+
+
+

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

+

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

+
+ + +
+ {list.length === 0 &&

{t('signage.reviews.none')}

} +
+ {list.map((r, i) => ( +
+
+ set(i, { stars })} aria-label={t('signage.reviews.stars')} data-testid="signage-review-stars" + options={[1, 2, 3, 4, 5].map(n => ({ value: n, label: String(n), icon:
+ +