From 1eb7e5e3a92710b275b2a766b7fff2b43575497c Mon Sep 17 00:00:00 2001 From: bonamin Date: Sun, 22 Nov 2026 14:41:17 +0200 Subject: [PATCH] feat(signage): gallery widget (pictures and videos one after another, from a list or a media folder); media folders on the Media page Folders are only a grouping in the database (media_folders, media.folder_id, Alembic 0046): made, renamed, deleted (files stay) on the Media page, a file filed from its details, uploads go into the folder shown, the picker filters by folder. The gallery widget: its own pictures/videos in order or a folder as it is now, seconds each, fade / slide / zoom, cover / contain. Plan 6R.16, F-114. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- local_backend/core/errors.py | 1 + .../migrations/versions/0046_media_folders.py | 41 +++++++ local_backend/models/media.py | 12 ++ local_backend/routers/identity.py | 2 +- local_backend/routers/media.py | 106 ++++++++++++++++-- local_backend/routers/signage.py | 21 +++- local_backend/tests/test_media_folders.py | 44 ++++++++ .../src/pages/media/MediaDetails.jsx | 15 ++- .../src/pages/media/MediaFolders.jsx | 57 ++++++++++ .../src/pages/media/MediaPage.jsx | 28 +++-- .../src/pages/media/MediaPicker.jsx | 15 ++- manager_dashboard/src/pages/media/mediaApi.js | 15 ++- .../src/pages/media/mediaHooks.js | 6 +- .../src/pages/signage/MoreWidgetFields.jsx | 82 +++++++++++++- .../src/pages/signage/WidgetsEditor.jsx | 8 +- .../src/pages/signage/signageLogic.js | 5 +- packages/i18n/locales/el/errors.json | 3 +- packages/i18n/locales/el/manager.json | 36 +++++- packages/i18n/locales/en/errors.json | 3 +- packages/i18n/locales/en/manager.json | 36 +++++- packages/signage/src/Slides.jsx | 36 +++++- tests/e2e/media.mjs | 17 +++ tests/e2e/signage.mjs | 9 +- 24 files changed, 549 insertions(+), 51 deletions(-) create mode 100644 local_backend/migrations/versions/0046_media_folders.py create mode 100644 local_backend/tests/test_media_folders.py create mode 100644 manager_dashboard/src/pages/media/MediaFolders.jsx diff --git a/docs/README.md b/docs/README.md index 614324d..c6af785 100644 --- a/docs/README.md +++ b/docs/README.md @@ -49,7 +49,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` | | `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/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. **Folders (6R.16):** `media_folders` + `media.folder_id` (Alembic 0046), only a grouping (files stay where they are): `GET/POST/PATCH/DELETE /api/media/folders`, `POST /api/media/move`, `?folder=|none`, uploads take `folder_id`; deleting a folder leaves its files in no folder. Signage's gallery widget shows its own `media_ids` or a folder (resolved in `extras` → `gallery`, so its files reach the TV's kept copies). 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); 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`) | diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index f0701dd..46d55db 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -126,6 +126,7 @@ CODES: dict[str, tuple[int, str]] = { "menu_tablet.order_not_found": (404, "This order was not found."), "menu_tablet.order_answered": (409, "This order was already answered."), "media.builtin": (409, "Built-in pictures can't be deleted or renamed."), + "media.folder_unknown": (404, "That folder isn't in the media library any more."), "reservation.not_found": (404, "Booking {reservation_id} not found."), "reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."), "reservation.table_unknown": (404, "Table {table_id} not found."), diff --git a/local_backend/migrations/versions/0046_media_folders.py b/local_backend/migrations/versions/0046_media_folders.py new file mode 100644 index 0000000..c839fbe --- /dev/null +++ b/local_backend/migrations/versions/0046_media_folders.py @@ -0,0 +1,41 @@ +"""Media folders (6R.16, owner 2026-11-22): the Media page groups files in folders. Only a grouping in +the database (media.folder_id); the files stay where they are on disk. A gallery widget can show a folder. + +Revision ID: 0046_media_folders +Revises: 0045_signage_shapes +Create Date: 2026-11-22 16:00:00 +""" +from alembic import op +import sqlalchemy as sa + +from core.timeutil import UTCDateTime + +revision = '0046_media_folders' +down_revision = '0045_signage_shapes' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + 'media_folders', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('position', sa.Integer(), nullable=False, server_default='0'), + sa.Column('created_at', UTCDateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_media_folders_id', 'media_folders', ['id']) + with op.batch_alter_table('media') as b: + b.add_column(sa.Column('folder_id', sa.Integer(), nullable=True)) + b.create_index('ix_media_folder_id', ['folder_id']) + b.create_foreign_key('fk_media_folder', 'media_folders', ['folder_id'], ['id'], ondelete='SET NULL') + + +def downgrade() -> None: + with op.batch_alter_table('media') as b: + b.drop_constraint('fk_media_folder', type_='foreignkey') + b.drop_index('ix_media_folder_id') + b.drop_column('folder_id') + op.drop_index('ix_media_folders_id', 'media_folders') + op.drop_table('media_folders') diff --git a/local_backend/models/media.py b/local_backend/models/media.py index 841eb62..0ccefc7 100644 --- a/local_backend/models/media.py +++ b/local_backend/models/media.py @@ -39,9 +39,21 @@ class Media(Base): # or no video tool on this server). `progress` 0-100 while working. processing = Column(String, nullable=True) progress = Column(Integer, nullable=True) + # its folder on the Media page (6R.16): only a grouping, the file stays where it is + folder_id = Column(Integer, ForeignKey("media_folders.id", ondelete="SET NULL"), nullable=True, index=True) uploader = relationship("User", lazy="joined") @property def uploaded_by_name(self): return self.uploader.full_name or self.uploader.username if self.uploader is not None else None + + +class MediaFolder(Base): + """A folder of the media library (6R.16): a name and a place in the list; its files point at it.""" + __tablename__ = "media_folders" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String, nullable=False) + position = Column(Integer, nullable=False, default=0, server_default='0') + created_at = Column(UTCDateTime, default=utcnow, nullable=False) diff --git a/local_backend/routers/identity.py b/local_backend/routers/identity.py index 11f9101..49d186c 100644 --- a/local_backend/routers/identity.py +++ b/local_backend/routers/identity.py @@ -157,7 +157,7 @@ def identity_out(db) -> dict: def _uses(db, media_id: int) -> list: logos = stored(db).logos - return [{"id": 0, "name": f"identity.{k}"} for k in LOGOS if getattr(logos, k) == media_id] + return [{"id": 0, "name": k} for k in LOGOS if getattr(logos, k) == media_id] def _register(): diff --git a/local_backend/routers/media.py b/local_backend/routers/media.py index 9b07dd1..abc8849 100644 --- a/local_backend/routers/media.py +++ b/local_backend/routers/media.py @@ -29,7 +29,7 @@ from core.access.deps import public, require_any from core.errors import XeniaError from database import get_db from datetime import datetime -from models.media import Media +from models.media import Media, MediaFolder from services import media as store from services import video @@ -57,6 +57,7 @@ class MediaOut(BaseModel): builtin: bool = False processing: Optional[str] = None # videos: waiting | working | done | failed (5.4e) progress: Optional[int] = None + folder_id: Optional[int] = None # 6R.16 urls: dict = Field(default_factory=dict) @@ -75,17 +76,53 @@ class MediaPage(BaseModel): class RenameBody(BaseModel): - name: str = Field(min_length=1, max_length=120) + name: Optional[str] = Field(default=None, min_length=1, max_length=120) + folder_id: Optional[int] = None # 6R.16: its folder (None: none) @field_validator("name") @classmethod def _strip(cls, v): + if v is None: + return v v = v.strip() if not v: raise ValueError("empty") return v +class FolderBody(BaseModel): + name: str = Field(min_length=1, max_length=60) + + @field_validator("name") + @classmethod + def _strip(cls, v): + v = " ".join(v.split()) + if not v: + raise ValueError("empty") + return v + + +class MoveBody(BaseModel): + ids: List[int] = Field(min_length=1, max_length=500) + folder_id: Optional[int] = None + + +def _folder(db: Session, folder_id: Optional[int]) -> Optional[MediaFolder]: + if folder_id is None: + return None + f = db.get(MediaFolder, folder_id) + if f is None: + raise XeniaError("media.folder_unknown", folder_id=folder_id) + return f + + +def _folders_out(db: Session) -> list: + from sqlalchemy import func + counts = dict(db.query(Media.folder_id, func.count(Media.id)).group_by(Media.folder_id).all()) + rows = db.query(MediaFolder).order_by(MediaFolder.position, MediaFolder.name).all() + return [{"id": f.id, "name": f.name, "count": counts.get(f.id, 0)} for f in rows] + + def _out(item: Media, cls=MediaOut, **extra): return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra}) @@ -105,9 +142,14 @@ def _name_from(filename: str | None) -> str: @router.get("", response_model=MediaPage) def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None, - collection: Optional[Literal["builtin", "own"]] = None, limit: int = 100, offset: int = 0, + collection: Optional[Literal["builtin", "own"]] = None, folder: Optional[str] = None, limit: int = 100, offset: int = 0, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): + """`folder`: a folder's id, or "none" for the files in no folder (6R.16).""" query = db.query(Media) + if folder == "none": + query = query.filter(Media.folder_id.is_(None)) + elif folder and folder.isdigit(): + query = query.filter(Media.folder_id == int(folder)) if kind: query = query.filter(Media.kind == kind) if q and q.strip(): @@ -122,11 +164,13 @@ def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str @router.post("", response_model=UploadOut, status_code=201) def upload_media(response: Response, file: UploadFile = File(...), name: Optional[str] = Form(None), + folder_id: Optional[int] = Form(None), db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): # The type comes from the bytes; the browser's content type only picks the size limit. declared = (file.content_type or "").lower() limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES tmp, sha, size = store.receive(file.file, limit) + folder = _folder(db, folder_id) existing = db.query(Media).filter(Media.sha256 == sha).first() if existing is not None: store._remove(tmp) @@ -134,7 +178,8 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona return _out(existing, UploadOut, existing=True) info = store.ingest(tmp, sha, size) item = Media(name=(name or "").strip()[:120] or _name_from(file.filename), - original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id, **info) + original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id, + folder_id=folder.id if folder else None, **info) if item.kind == "video": video.queued(item) # its still frame and playable version, in the background try: @@ -195,6 +240,50 @@ def _ranged(path: str, ctype: str, rng: str, headers: dict): **headers, "Content-Range": f"bytes {start}-{end}/{size}", "Content-Length": str(end - start + 1)}) +# ── folders (6R.16): only a grouping; files keep their place on disk ───────────── + +@router.get("/folders") +def list_folders(db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): + return {"folders": _folders_out(db), "none": db.query(Media).filter(Media.folder_id.is_(None)).count()} + + +@router.post("/folders", status_code=201) +def create_folder(body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): + last = db.query(MediaFolder).count() + f = MediaFolder(name=body.name, position=last) + db.add(f) + db.commit() + db.refresh(f) + return {"id": f.id, "name": f.name, "count": 0} + + +@router.patch("/folders/{folder_id}") +def rename_folder(folder_id: int, body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): + f = _folder(db, folder_id) + f.name = body.name + db.commit() + return next(x for x in _folders_out(db) if x["id"] == f.id) + + +@router.delete("/folders/{folder_id}", status_code=204) +def delete_folder(folder_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): + """The folder goes; its files stay in the library, in no folder.""" + f = _folder(db, folder_id) + db.query(Media).filter(Media.folder_id == f.id).update({Media.folder_id: None}) + db.delete(f) + db.commit() + return Response(status_code=204) + + +@router.post("/move") +def move_media(body: MoveBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): + """Several files into a folder (or out of any: folder_id null).""" + folder = _folder(db, body.folder_id) + n = db.query(Media).filter(Media.id.in_(body.ids)).update({Media.folder_id: folder.id if folder else None}, synchronize_session=False) + db.commit() + return {"moved": n} + + @router.get("/{media_id}", response_model=MediaDetail) def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): item = _get(db, media_id) @@ -204,9 +293,12 @@ def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require @router.patch("/{media_id}", response_model=MediaOut) def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): item = _get(db, media_id) - if item.builtin: - raise XeniaError("media.builtin") - item.name = body.name + if "name" in body.model_fields_set and body.name is not None: + if item.builtin: + raise XeniaError("media.builtin") + item.name = body.name + if "folder_id" in body.model_fields_set: + item.folder_id = _folder(db, body.folder_id).id if body.folder_id is not None else None # built-in pictures may be filed too db.commit() db.refresh(item) return _out(item) diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py index ad4d9cf..b0cc1f9 100644 --- a/local_backend/routers/signage.py +++ b/local_backend/routers/signage.py @@ -86,7 +86,7 @@ class Background(_Strict): WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack", "shape", "ticker", "countdown", "hours", "wifi", "contact", # 6R.15 - "reviews"] # 6R.19 + "reviews", "gallery"] # 6R.19, 6R.16 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"] @@ -316,6 +316,13 @@ class Widget(_Strict): 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 + # a gallery (6R.16): pictures and videos one after another, from its own list or a media folder + gallery_source: Literal["pictures", "folder"] = "pictures" + media_ids: List[int] = Field(default_factory=list, max_length=100) + gallery_folder: Optional[int] = None + gallery_seconds: int = Field(default=5, ge=3, le=120) + gallery_transition: Literal["fade", "slide", "zoom", "none"] = "fade" + gallery_fit: Literal["cover", "contain"] = "cover" @model_validator(mode="after") def _place(self): @@ -661,6 +668,10 @@ def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0): out[path] = {"link": _qr_link(w)} elif w.get("kind") == "menu": out[path] = {"menu": resolve(db, w.get("board") or {}, keep_hidden=keep_hidden)} + elif w.get("kind") == "gallery" and w.get("gallery_source") == "folder": + ids = gallery_folder_ids(db, w.get("gallery_folder")) # 6R.16: the folder as it is now + out[path] = {"gallery": ids} + mids += ids elif depth == 0: s = db.get(SignageSavedSlide, sid) if s is None: @@ -675,6 +686,14 @@ def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0): return out, mids +def gallery_folder_ids(db, folder_id) -> list[int]: + """A media folder's files for a gallery (6R.16), newest last as uploaded; none for a folder that's gone.""" + from models.media import Media + if not folder_id: + return [] + return [m.id for m in db.query(Media).filter(Media.folder_id == folder_id).order_by(Media.created_at, Media.id).limit(200)] + + def _content(db, kind: str, raw: dict | None) -> dict: """The content as stored: typed for its kind, every media id an existing file of the right kind.""" from pydantic import ValidationError diff --git a/local_backend/tests/test_media_folders.py b/local_backend/tests/test_media_folders.py new file mode 100644 index 0000000..6144b0a --- /dev/null +++ b/local_backend/tests/test_media_folders.py @@ -0,0 +1,44 @@ +"""Media folders (6R.16): made, renamed, deleted (files stay), files moved and uploaded into one, +the list filtered; a gallery widget showing a folder gets its files (and the screen their addresses).""" +from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures) +from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers) +from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers) + + +def test_folders(client, owner_h, media_dir): + f = client.post("/api/media/folders", headers=owner_h, json={"name": " Summer menu "}).json() + assert f["name"] == "Summer menu" and f["count"] == 0 + a = up(client, owner_h, jpeg(300, 200)).json() + b = up(client, owner_h, jpeg(300, 200, (9, 9, 9))).json() + assert client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"], b["id"]], "folder_id": f["id"]}).json()["moved"] == 2 + got = client.get("/api/media/folders", headers=owner_h).json() + assert got["folders"] == [{"id": f["id"], "name": "Summer menu", "count": 2}] + listed = client.get(f"/api/media?folder={f['id']}", headers=owner_h).json() + assert {i["id"] for i in listed["items"]} == {a["id"], b["id"]} and listed["items"][0]["folder_id"] == f["id"] + assert all(i["folder_id"] is None for i in client.get("/api/media?folder=none", headers=owner_h).json()["items"]) + r = client.patch(f"/api/media/{a['id']}", headers=owner_h, json={"folder_id": None}) + assert r.status_code == 200 and r.json()["folder_id"] is None and r.json()["name"] == a["name"] + assert client.patch(f"/api/media/folders/{f['id']}", headers=owner_h, json={"name": "Winter"}).json()["name"] == "Winter" + # an upload straight into a folder + c = client.post("/api/media", headers=owner_h, files={"file": ("x.jpg", jpeg(100, 100, (1, 2, 3)), "image/jpeg")}, data={"folder_id": str(f["id"])}).json() + assert c["folder_id"] == f["id"] + assert err(client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"]], "folder_id": 9999})) == "media.folder_unknown" + assert client.delete(f"/api/media/folders/{f['id']}", headers=owner_h).status_code == 204 + assert client.get(f"/api/media/{b['id']}", headers=owner_h).json()["folder_id"] is None # the file stays + + +def test_a_gallery_of_a_folder(client, owner_h, screens, media_dir): + f = client.post("/api/media/folders", headers=owner_h, json={"name": "Dishes"}).json() + pics = [up(client, owner_h, jpeg(400, 300, (i * 40, 10, 10))).json() for i in range(3)] + client.post("/api/media/move", headers=owner_h, json={"ids": [p["id"] for p in pics], "folder_id": f["id"]}) + p = playlist(client, owner_h) + slide(client, owner_h, p["id"], "blank", content={"widgets": [ + {"kind": "gallery", "position": "custom", "box": {"x": 0, "y": 0, "w": 50, "h": 50}, "gallery_source": "folder", "gallery_folder": f["id"], "gallery_seconds": 4}, + {"kind": "gallery", "position": "top-left", "media_ids": [pics[0]["id"]], "gallery_transition": "slide"}]}) + client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": p["id"]}) + pl = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["playlist"] + s = pl["slides"][0] + assert s["extras"]["0"]["gallery"] == [x["id"] for x in pics] + assert all(str(x["id"]) in pl["media"] for x in pics) + # the pictures in a gallery's own list are protected + assert err(client.delete(f"/api/media/{pics[0]['id']}", headers=owner_h)) == "media.in_use" diff --git a/manager_dashboard/src/pages/media/MediaDetails.jsx b/manager_dashboard/src/pages/media/MediaDetails.jsx index 0e6147e..ce73fb5 100644 --- a/manager_dashboard/src/pages/media/MediaDetails.jsx +++ b/manager_dashboard/src/pages/media/MediaDetails.jsx @@ -6,11 +6,11 @@ import toast from 'react-hot-toast' import { Trash2 } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useFormat, useTranslation } from '@xenia/i18n' -import { Button, Dialog, Field, Input, Spinner, cx } from '@xenia/ui' -import { deleteMedia, getMedia, renameMedia } from './mediaApi' +import { Button, Dialog, Dropdown, Field, Input, Spinner, cx } from '@xenia/ui' +import { deleteMedia, getMedia, renameMedia, setFolder } from './mediaApi' import { duration, fileSize, preparing, resolution, VARIANT_ORDER, videoState } from './mediaLogic' -export default function MediaDetails({ id, onClose, onChanged, onDeleted }) { +export default function MediaDetails({ id, onClose, onChanged, onDeleted, folders = [] }) { const { t } = useTranslation('manager') const { formatDateTime, formatNumber } = useFormat() const [item, setItem] = useState(null) @@ -43,6 +43,10 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) { catch (err) { toast.error(errorMessage(err, t)) } setBusy(false) } + const fileIn = async folderId => { + try { const m = await setFolder(id, folderId); setItem(it => ({ ...it, ...m })); onChanged?.(m); toast.success(t('media.folders.moved')) } + catch (err) { toast.error(errorMessage(err, t)) } + } const remove = async () => { setBusy(true) try { await deleteMedia(id); toast.success(t('media.deleted')); onDeleted?.(id); onClose() } @@ -93,6 +97,11 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {

{t(item.builtin ? 'media.builtinHint' : 'media.displayNameHint')}

+ + fileIn(v === '' ? null : Number(v))} data-testid="media-folder-pick" + options={[{ value: '', label: t('media.folders.none') }, ...folders.map(f => ({ value: f.id, label: f.name }))]} /> + +
{rows.map(([k, v]) =>
{k}
{v}
)}
diff --git a/manager_dashboard/src/pages/media/MediaFolders.jsx b/manager_dashboard/src/pages/media/MediaFolders.jsx new file mode 100644 index 0000000..08192ba --- /dev/null +++ b/manager_dashboard/src/pages/media/MediaFolders.jsx @@ -0,0 +1,57 @@ +// The media library's folders (6R.16, owner 2026-11-22): only a grouping in the database, the files +// stay where they are. The bar picks what the page shows (everything, the files in no folder, a +// folder) and where uploads go; a folder is made, renamed or deleted here (its files stay, in no folder). +import { useState } from 'react' +import toast from 'react-hot-toast' +import { FolderPlus, Pencil, Trash2 } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Dialog, Field, FilterChip, IconButton, Input, useConfirm } from '@xenia/ui' +import { createFolder, deleteFolder, renameFolder } from './mediaApi' + +/** value: '' (all) | 'none' | a folder id as a string. */ +export default function MediaFolders({ folders, none, total, value, onChange, onChanged }) { + const { t } = useTranslation('manager') + const [naming, setNaming] = useState(null) // { id?, name } + const [confirm, confirmDialog] = useConfirm() + const current = folders?.find(f => String(f.id) === value) + const save = async () => { + try { + const f = naming.id ? await renameFolder(naming.id, naming.name.trim()) : await createFolder(naming.name.trim()) + setNaming(null) + await onChanged?.() + onChange(String(f.id)) + } catch (err) { toast.error(errorMessage(err, t)) } + } + const remove = async () => { + if (!await confirm({ title: t('media.folders.deleteTitle', { name: current.name }), body: t('media.folders.deleteBody'), confirmLabel: t('media.delete'), tone: 'danger', testId: 'media-folder-delete-confirm' })) return + try { await deleteFolder(current.id); onChange(''); await onChanged?.() } catch (err) { toast.error(errorMessage(err, t)) } + } + return ( +
+ onChange('')} data-testid="media-folder-all">{t('media.folders.all')} + onChange('none')} data-testid="media-folder-none">{t('media.folders.none')} + {(folders || []).map(f => ( + onChange(String(f.id))} data-testid="media-folder" data-name={f.name}>{f.name} + ))} + + {current && <> + setNaming({ id: current.id, name: current.name })} data-testid="media-folder-rename"> + + } + {naming && ( + setNaming(null)} + footer={<> + + + }> + + setNaming(n => ({ ...n, name: e.target.value }))} + onKeyDown={e => { if (e.key === 'Enter' && naming.name.trim()) save() }} data-testid="media-folder-name" /> + + + )} + {confirmDialog} +
+ ) +} diff --git a/manager_dashboard/src/pages/media/MediaPage.jsx b/manager_dashboard/src/pages/media/MediaPage.jsx index f7c538d..576d0f0 100644 --- a/manager_dashboard/src/pages/media/MediaPage.jsx +++ b/manager_dashboard/src/pages/media/MediaPage.jsx @@ -2,13 +2,15 @@ // library. Batch upload (pick many files or drop them on the page) to use later anywhere that // takes media (products, categories; the customer display and signage next). The backend names // and stores the files; here people see a display name, the details and the sizes made. -// Backend: /api/media (routers/media.py). +// Folders (6R.16): the bar under the toolbar picks a folder (uploads go into it); a file's folder is +// changed in its details. Backend: /api/media (routers/media.py). import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Upload } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useTranslation } from '@xenia/i18n' import { Button, EmptyState, Input, Page, Select, Spinner, cx } from '@xenia/ui' -import { listMedia } from './mediaApi' +import { listFolders, listMedia } from './mediaApi' +import MediaFolders from './MediaFolders' import { ACCEPT, preparing } from './mediaLogic' import MediaDetails from './MediaDetails' import { MediaGrid, UploadQueue } from './MediaParts' @@ -24,13 +26,17 @@ export default function MediaPage() { const [error, setError] = useState(null) const [open, setOpen] = useState(null) const [dragging, setDragging] = useState(false) + const [folder, setFolder] = useState('') // '' all | 'none' | a folder id + const [folders, setFolders] = useState(null) // { folders, none } + const loadFolders = useCallback(async () => { try { setFolders(await listFolders()) } catch { /* the bar waits */ } }, []) + useEffect(() => { loadFolders() }, [loadFolders]) const input = useRef(null) useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q]) const load = useCallback(async () => { - try { setPage(await listMedia({ kind, q: search, collection })); setError(null) } catch (err) { setError(errorMessage(err, t)) } - }, [kind, search, collection, t]) + try { setPage(await listMedia({ kind, q: search, collection, folder })); setError(null) } catch (err) { setError(errorMessage(err, t)) } + }, [kind, search, collection, folder, t]) useEffect(() => { load() }, [load]) // Videos are prepared for screens in the background (5.4e): read the list again while any is. const busy = preparing(page?.items) @@ -45,16 +51,18 @@ export default function MediaPage() { setPage(p => (p && !p.items.some(x => x.id === item.id) ? { ...p, items: [item, ...p.items], total: p.total + 1 } : p)) }, [])) const wasBusy = useRef(false) - useEffect(() => { if (wasBusy.current && !summary.busy) load(); wasBusy.current = summary.busy }, [summary.busy, load]) + useEffect(() => { if (wasBusy.current && !summary.busy) { load(); loadFolders() } wasBusy.current = summary.busy }, [summary.busy, load, loadFolders]) const onDrop = e => { e.preventDefault(); setDragging(false) - if (e.dataTransfer.files?.length) add(e.dataTransfer.files) + if (e.dataTransfer.files?.length) add(e.dataTransfer.files, upTo) } const kinds = useMemo(() => [ { value: '', label: t('media.kinds.all') }, { value: 'image', label: t('media.kinds.images') }, { value: 'video', label: t('media.kinds.videos') }, ], [t]) const closeDetails = useCallback(() => setOpen(null), []) + const upTo = /^\d+$/.test(folder) ? Number(folder) : null // uploads go into the folder shown + const allCount = folders ? folders.none + folders.folders.reduce((n, f) => n + f.count, 0) : undefined return ( { if (e.target.files?.length) add(e.target.files); e.target.value = '' }} /> + onChange={e => { if (e.target.files?.length) add(e.target.files, upTo); e.target.value = '' }} /> {t('media.dropHint')}
setQ(e.target.value)} placeholder={t('media.search')} aria-label={t('media.search')} @@ -81,6 +89,8 @@ export default function MediaPage() {
+ + {error ? @@ -92,8 +102,8 @@ export default function MediaPage() { {page.total > page.items.length &&

{t('media.more', { shown: page.items.length, total: page.total })}

} } - {open && setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) })} + {open && { setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) }); loadFolders() }} onDeleted={id => setPage(p => p && { ...p, items: p.items.filter(x => x.id !== id), total: p.total - 1 })} />}
) diff --git a/manager_dashboard/src/pages/media/MediaPicker.jsx b/manager_dashboard/src/pages/media/MediaPicker.jsx index 455440a..799a4f7 100644 --- a/manager_dashboard/src/pages/media/MediaPicker.jsx +++ b/manager_dashboard/src/pages/media/MediaPicker.jsx @@ -6,7 +6,7 @@ import { Upload } from 'lucide-react' import { errorMessage } from '@xenia/api' import { useTranslation } from '@xenia/i18n' import { Button, Dialog, EmptyState, Input, Select, Spinner } from '@xenia/ui' -import { listMedia } from './mediaApi' +import { listFolders, listMedia } from './mediaApi' import { ACCEPT } from './mediaLogic' import { MediaGrid, UploadQueue } from './MediaParts' import { useUploadQueue } from './mediaHooks' @@ -22,13 +22,16 @@ export default function MediaPicker({ open, onClose, onPick, onPickMany, multipl const [chosen, setChosen] = useState([]) // multiple: the items picked so far, in order const toggle = item => setChosen(c => (c.some(x => x.id === item.id) ? c.filter(x => x.id !== item.id) : [...c, item])) + const [folder, setFolder] = useState('') // 6R.16: '' all | 'none' | a folder id + const [folders, setFolders] = useState([]) + useEffect(() => { if (open) listFolders().then(r => setFolders(r.folders)).catch(() => {}) }, [open]) useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q]) useEffect(() => { if (!open) return let live = true - listMedia({ kind, q: search, collection }).then(p => { if (live) { setPage(p); setError(null) } }).catch(err => live && setError(errorMessage(err, t))) + listMedia({ kind, q: search, collection, folder }).then(p => { if (live) { setPage(p); setError(null) } }).catch(err => live && setError(errorMessage(err, t))) return () => { live = false } - }, [open, kind, search, collection, t]) + }, [open, kind, search, collection, folder, t]) const { queue, add, clear, summary } = useUploadQueue(useCallback(item => { setPage(p => (p && !p.items.some(x => x.id === item.id) ? { ...p, items: [item, ...p.items], total: p.total + 1 } : p)) @@ -49,9 +52,13 @@ export default function MediaPicker({ open, onClose, onPick, onPickMany, multipl className="flex-1 min-w-[10rem]" data-testid="media-picker-search" /> setFolder(e.target.value)} aria-label={t('media.folders.folder')} data-testid="media-picker-folder" + options={[{ value: '', label: t('media.folders.all') }, { value: 'none', label: t('media.folders.none') }, ...folders.map(f => ({ value: String(f.id), label: f.name }))]} /> + )} a.startsWith('image/')).join(',') : ACCEPT} - className="sr-only" data-testid="media-picker-file" multiple={multiple} onChange={e => { if (e.target.files?.length) add(multiple ? e.target.files : [e.target.files[0]]); e.target.value = '' }} /> + className="sr-only" data-testid="media-picker-file" multiple={multiple} onChange={e => { if (e.target.files?.length) add(multiple ? e.target.files : [e.target.files[0]], /^\d+$/.test(folder) ? Number(folder) : null); e.target.value = '' }} /> {error ? diff --git a/manager_dashboard/src/pages/media/mediaApi.js b/manager_dashboard/src/pages/media/mediaApi.js index 9e15a57..3e3b027 100644 --- a/manager_dashboard/src/pages/media/mediaApi.js +++ b/manager_dashboard/src/pages/media/mediaApi.js @@ -1,16 +1,17 @@ // The media library's API (backend: local_backend/routers/media.py, plan steps 5.1 / 5.2). import client from '../../api/client' -export const listMedia = ({ kind, q, collection, limit = 500 } = {}) => - client.get('/api/media', { params: { kind: kind || undefined, q: q || undefined, collection: collection || undefined, limit } }).then(r => r.data) +export const listMedia = ({ kind, q, collection, folder, limit = 500 } = {}) => + client.get('/api/media', { params: { kind: kind || undefined, q: q || undefined, collection: collection || undefined, folder: folder || undefined, limit } }).then(r => r.data) export const getMedia = id => client.get(`/api/media/${id}`).then(r => r.data) /** Upload one file → the library item (`existing: true` when the same file was already there). */ -export function uploadMedia(file, { name, onProgress } = {}) { +export function uploadMedia(file, { name, folderId, onProgress } = {}) { const fd = new FormData() fd.append('file', file) if (name) fd.append('name', name) + if (folderId) fd.append('folder_id', String(folderId)) return client.post('/api/media', fd, { onUploadProgress: e => { if (onProgress && e.total) onProgress(Math.round((e.loaded / e.total) * 100)) }, }).then(r => r.data) @@ -19,3 +20,11 @@ export function uploadMedia(file, { name, onProgress } = {}) { export const renameMedia = (id, name) => client.patch(`/api/media/${id}`, { name }).then(r => r.data) export const deleteMedia = id => client.delete(`/api/media/${id}`) + +// folders (6R.16): only a grouping in the database; the files stay where they are +export const listFolders = () => client.get('/api/media/folders').then(r => r.data) +export const createFolder = name => client.post('/api/media/folders', { name }).then(r => r.data) +export const renameFolder = (id, name) => client.patch(`/api/media/folders/${id}`, { name }).then(r => r.data) +export const deleteFolder = id => client.delete(`/api/media/folders/${id}`) +export const moveMedia = (ids, folderId) => client.post('/api/media/move', { ids, folder_id: folderId ?? null }).then(r => r.data) +export const setFolder = (id, folderId) => client.patch(`/api/media/${id}`, { folder_id: folderId ?? null }).then(r => r.data) diff --git a/manager_dashboard/src/pages/media/mediaHooks.js b/manager_dashboard/src/pages/media/mediaHooks.js index 3456ea6..3fd066b 100644 --- a/manager_dashboard/src/pages/media/mediaHooks.js +++ b/manager_dashboard/src/pages/media/mediaHooks.js @@ -27,8 +27,8 @@ export function useUploadQueue(onDone) { useEffect(() => { done.current = onDone }) const counter = useRef(0) - const add = useCallback(files => { - const list = queueFrom(files, counter.current) + const add = useCallback((files, folderId = null) => { + const list = queueFrom(files, counter.current).map(x => ({ ...x, folderId })) counter.current += list.length setQueue(q => [...q, ...list]) }, []) @@ -41,7 +41,7 @@ export function useUploadQueue(onDone) { running.current = true const set = patch => setQueue(q => q.map(x => (x.key === next.key ? { ...x, ...patch } : x))) set({ status: 'uploading' }) - uploadMedia(next.file, { onProgress: progress => set({ progress }) }) + uploadMedia(next.file, { folderId: next.folderId, onProgress: progress => set({ progress }) }) .then(item => { set({ status: item.existing ? 'existing' : 'added', progress: 100, item }); done.current?.(item, !!item.existing) }) .catch(err => set({ status: 'failed', error: errorMessage(err, t) })) .finally(() => { running.current = false; setQueue(q => [...q]) }) diff --git a/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx b/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx index c5a8ea1..c2da31b 100644 --- a/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx +++ b/manager_dashboard/src/pages/signage/MoreWidgetFields.jsx @@ -1,14 +1,17 @@ // 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 reviews (6R.19). The last three read the +// countdown, the opening hours, the guests' Wi-Fi and the contact details; the reviews (6R.19); a gallery (6R.16). 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 { ArrowLeft, ArrowRight, Film, Plus, X } from 'lucide-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 { Button, ColourField, Dropdown, Field, IconButton, Input, Notice, NumberInput, Segmented, Slider, Switch } from '@xenia/ui' +import { listFolders } from '../media/mediaApi' +import MediaPicker from '../media/MediaPicker' import { useHours, useIdentity } from '../../shell/useIdentity' import * as api from './signageApi' -import { CONTACT_KEYS, WIDGET_COLOURS } from './signageLogic' +import { CONTACT_KEYS, moved, WIDGET_COLOURS } from './signageLogic' const SHAPES = ['rectangle', 'circle', 'triangle', 'polygon', 'star', 'custom'] const isDate = v => !!v && v.length > 5 @@ -79,6 +82,25 @@ export function MoreInlineFields({ w, set }) { ) } + if (w.kind === 'gallery') { + return (<> + + set({ gallery_source })} data-testid="signage-widget-gallery-source" + options={['pictures', 'folder'].map(v => ({ value: v, label: t(`${k}.gallery.sources.${v}`) }))} /> + + + set({ gallery_seconds: v ?? 3 })} /> + + + set({ gallery_transition })} + options={['fade', 'slide', 'zoom', 'none'].map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))} /> + + + set({ gallery_fit })} + options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} /> + + ) + } if (w.kind === 'reviews') { return (<> @@ -102,7 +124,7 @@ export function MoreInlineFields({ w, set }) { } /** Under the row: what needs more room, and what the venue still has to set. */ -export function MoreBelowFields({ w, set }) { +export function MoreBelowFields({ w, set, media = {}, onMedia }) { const { t } = useTranslation('manager') const { data: identity } = useIdentity() const { data: hours } = useHours() @@ -172,6 +194,7 @@ export function MoreBelowFields({ w, set }) { ) } + if (w.kind === 'gallery') return if (w.kind === 'reviews') { return (
@@ -206,3 +229,54 @@ function ReviewsNote() { ? {link} :

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

} + +/** A gallery's pictures and videos (its own list, in order) or the media folder it shows (6R.16). */ +function GalleryItems({ w, set, media, onMedia }) { + const { t } = useTranslation('manager') + const [picking, setPicking] = useState(false) + const [folders, setFolders] = useState(null) + const folder = w.gallery_source === 'folder' + useEffect(() => { if (folder) listFolders().then(r => setFolders(r.folders)).catch(() => setFolders([])) }, [folder]) + const k = 'signage.widgets.gallery' + if (folder) { + return ( +
+ + set({ gallery_folder: v === '' ? null : Number(v) })} data-testid="signage-widget-gallery-folder" + options={[{ value: '', label: t(`${k}.noFolder`) }, ...(folders || []).map(f => ({ value: f.id, label: f.name, hint: String(f.count) }))]} /> + + {folders && folders.length === 0 && ( + {t(`${k}.toMedia`)} + )} +
+ ) + } + const ids = w.media_ids || [] + return ( +
+
+ {ids.map((id, i) => { + const m = media[String(id)] + return ( +
+ {m?.thumb ? {m.name :
+ ) + })} + {ids.length < 100 && ( + + )} +
+ {ids.length === 0 &&

{t(`${k}.empty`)}

} + {picking && ( + setPicking(false)} + onPickMany={items => { items.forEach(it => onMedia?.(it)); set({ media_ids: [...ids, ...items.map(it => it.id)].slice(0, 100) }); setPicking(false) }} /> + )} +
+ ) +} diff --git a/manager_dashboard/src/pages/signage/WidgetsEditor.jsx b/manager_dashboard/src/pages/signage/WidgetsEditor.jsx index bbb32fa..c444aea 100644 --- a/manager_dashboard/src/pages/signage/WidgetsEditor.jsx +++ b/manager_dashboard/src/pages/signage/WidgetsEditor.jsx @@ -28,7 +28,7 @@ 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, MessageSquareQuote, MoveHorizontal, Shapes, Timer, Wifi, + CalendarClock, Contact, GalleryHorizontal, MessageSquareQuote, MoveHorizontal, Shapes, Timer, Wifi, } from 'lucide-react' import { cellWidgets, evenShares, setShare } from '@xenia/signage' import { useTranslation } from '@xenia/i18n' @@ -44,8 +44,8 @@ import { } 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, - shape: Shapes, ticker: MoveHorizontal, countdown: Timer, hours: CalendarClock, wifi: Wifi, contact: Contact, reviews: MessageSquareQuote } -const MORE_KINDS = ['shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews'] // MoreWidgetFields + shape: Shapes, ticker: MoveHorizontal, countdown: Timer, hours: CalendarClock, wifi: Wifi, contact: Contact, reviews: MessageSquareQuote, gallery: GalleryHorizontal } +const MORE_KINDS = ['shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews', 'gallery'] // MoreWidgetFields 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))]' @@ -307,7 +307,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 (MORE_KINDS.includes(w.kind)) return + if (MORE_KINDS.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 9ad9c74..437d932 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', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews'] +export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews', 'gallery'] /** 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', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews'] +export const CELL_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact', 'reviews', 'gallery'] /** 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). */ @@ -152,6 +152,7 @@ export function newWidget(kind) { 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' } } } if (kind === 'shape') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 40, y: 30, w: 20, h: 35 }, shape: 'rectangle', radius: 10 } + if (kind === 'gallery') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 55, y: 15, w: 40, h: 50 }, media_ids: [] } if (kind === 'reviews') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 25, y: 55, w: 50, h: 32 } } return { kind, position: NEW_PLACE[kind] || 'top-right', size: 'medium', align: 'auto', ...(kind === 'text' || kind === 'ticker' ? { text: '' } : {}), ...(kind === 'countdown' ? { countdown_to: '17:00' } : {}) } diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index caf66c2..77e8864 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -174,7 +174,8 @@ "unreadable": "Αυτή η εικόνα δεν διαβάζεται. Αποθηκεύστε τη ξανά ως JPG ή PNG και ανεβάστε τη.", "in_use": "Αυτό το αρχείο χρησιμοποιείται από: {{uses}}. Αφαιρέστε το πρώτα από εκεί.", "not_a_picture": "Εδώ διαλέξτε εικόνα, όχι βίντεο.", - "builtin": "Οι ενσωματωμένες εικόνες δεν διαγράφονται ούτε μετονομάζονται." + "builtin": "Οι ενσωματωμένες εικόνες δεν διαγράφονται ούτε μετονομάζονται.", + "folder_unknown": "Αυτός ο φάκελος δεν υπάρχει πια στη βιβλιοθήκη πολυμέσων." }, "caller_id": { "key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος." diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index fccdb3b..b2d6902 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -1215,7 +1215,10 @@ "usedCantDelete": "Ένα αρχείο σε χρήση δεν διαγράφεται. Αφαιρέστε το πρώτα από εκεί.", "uses": { "product": "Προϊόν", - "category": "Κατηγορία" + "category": "Κατηγορία", + "identity": "Το λογότυπο του καταστήματος", + "signage_slide": "Διαφάνεια σήμανσης", + "signage_saved_slide": "Αποθηκευμένη διαφάνεια" }, "pickTitle": "Επιλογή εικόνας", "photo": "Φωτογραφία", @@ -1246,6 +1249,19 @@ "waiting": "Σε αναμονή…", "working": "Ετοιμάζεται {{progress}}%", "failed": "Δεν ετοιμάστηκε" + }, + "folders": { + "title": "Φάκελοι", + "all": "Όλα", + "none": "Χωρίς φάκελο", + "new": "Νέος φάκελος", + "rename": "Μετονομασία φακέλου", + "delete": "Διαγραφή φακέλου", + "deleteTitle": "Διαγραφή του φακέλου «{{name}}»;", + "deleteBody": "Τα αρχεία του μένουν στη βιβλιοθήκη, χωρίς φάκελο. Μια συλλογή που δείχνει αυτόν τον φάκελο δεν θα δείχνει τίποτα.", + "name": "Όνομα φακέλου", + "folder": "Φάκελος", + "moved": "Μετακινήθηκε" } }, "signage": { @@ -1487,7 +1503,8 @@ "hours": "Ωράριο", "wifi": "Wi-Fi", "contact": "Στοιχεία επικοινωνίας", - "reviews": "Κριτικές" + "reviews": "Κριτικές", + "gallery": "Συλλογή" }, "position": "Πού", "size": "Μέγεθος", @@ -1675,6 +1692,21 @@ "missing": "Δεν υπάρχουν κριτικές ακόμη: το widget μένει κρυφό.", "hint": "Οι κριτικές που καταχωρίσατε, μία κάθε φορά.", "where": "Προσθέστε τις στο Ψηφιακή σήμανση → Μήνυμα & ρυθμίσεις" + }, + "gallery": { + "source": "Δείχνει", + "sources": { + "pictures": "Επιλεγμένες εικόνες", + "folder": "Έναν φάκελο" + }, + "seconds": "Καθεμία για", + "folder": "Φάκελος", + "folderHint": "Ό,τι υπάρχει τώρα στον φάκελο, και ό,τι προσθέσετε αργότερα.", + "noFolder": "Διαλέξτε φάκελο", + "noFolders": "Δεν υπάρχουν φάκελοι πολυμέσων ακόμη.", + "toMedia": "Φτιάξτε έναν στη σελίδα Πολυμέσα", + "add": "Προσθήκη εικόνων ή βίντεο", + "empty": "Η συλλογή είναι άδεια ακόμη: μένει κρυφή." } }, "tabs": { diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index dfef242..ee1aea3 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -174,7 +174,8 @@ "unreadable": "This picture can't be read. Save it again as JPG or PNG and upload it.", "in_use": "This file is used by {{uses}}. Remove it there first.", "not_a_picture": "Pick a picture here, not a video.", - "builtin": "Built-in pictures can't be deleted or renamed." + "builtin": "Built-in pictures can't be deleted or renamed.", + "folder_unknown": "That folder isn't in the media library any more." }, "caller_id": { "key_invalid": "The phone system's key is missing or wrong." diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index a8c4167..b114bdc 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -1215,7 +1215,10 @@ "usedCantDelete": "A file in use can't be deleted. Remove it there first.", "uses": { "product": "Product", - "category": "Category" + "category": "Category", + "identity": "The venue's logo", + "signage_slide": "Signage slide", + "signage_saved_slide": "Saved slide" }, "pickTitle": "Pick a picture", "photo": "Photo", @@ -1246,6 +1249,19 @@ "waiting": "Waiting…", "working": "Preparing {{progress}}%", "failed": "Not prepared" + }, + "folders": { + "title": "Folders", + "all": "All", + "none": "In no folder", + "new": "New folder", + "rename": "Rename the folder", + "delete": "Delete the folder", + "deleteTitle": "Delete the folder \"{{name}}\"?", + "deleteBody": "Its files stay in the library, in no folder. A gallery that shows this folder will show nothing.", + "name": "Folder name", + "folder": "Folder", + "moved": "Moved" } }, "signage": { @@ -1487,7 +1503,8 @@ "hours": "Opening hours", "wifi": "Wi-Fi", "contact": "Contact details", - "reviews": "Reviews" + "reviews": "Reviews", + "gallery": "Gallery" }, "position": "Where", "size": "Size", @@ -1675,6 +1692,21 @@ "missing": "No reviews yet: the widget stays hidden.", "hint": "The reviews you typed in, one at a time.", "where": "Add them under Signage → Message & settings" + }, + "gallery": { + "source": "Shows", + "sources": { + "pictures": "Chosen pictures", + "folder": "A folder" + }, + "seconds": "Each for", + "folder": "Folder", + "folderHint": "Whatever is in the folder now, also what you add to it later.", + "noFolder": "Choose a folder", + "noFolders": "No media folders yet.", + "toMedia": "Make one on the Media page", + "add": "Add pictures or videos", + "empty": "Nothing in the gallery yet: it stays hidden." } }, "tabs": { diff --git a/packages/signage/src/Slides.jsx b/packages/signage/src/Slides.jsx index b0bdf9d..0c15181 100644 --- a/packages/signage/src/Slides.jsx +++ b/packages/signage/src/Slides.jsx @@ -175,7 +175,7 @@ const plate = (w, pad) => ({ ...(w.background_colour ? { background: w.background_colour, borderRadius: cq(1.2), ...(pad ? { padding: `${cq(0.8)} ${cq(1.6)}` } : {}) } : {}), }) // 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], reviews: [56, 24] } +const BOXED = { menu: [48, 56], stack: [60, 36], shape: [18, 18], ticker: [80, 7], reviews: [56, 24], gallery: [40, 30] } /** * The widgets of a slide: in their corners and bars, or (moved and sized by hand: position @@ -336,6 +336,12 @@ function widgetBody(w, ctx, fit, path) { 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) + if (w.kind === 'gallery') { + const ids = w.gallery_source === 'folder' ? (x.gallery || []) : (w.media_ids || []) + const items = ids.map(id => media(id)).filter(Boolean) + if (!items.length) return null + return boxed(, 'gallery') + } if (w.kind === 'reviews') { const list = (venue?.reviews || []).filter(r => r.stars >= (w.reviews_min || 4)) if (!list.length) return null @@ -346,6 +352,34 @@ function widgetBody(w, ctx, fit, path) { } const STAR = '#fbbf24' +const GALLERY_IN = { + fade: [{ opacity: 0 }, { opacity: 1 }], + slide: [{ transform: 'translateX(100%)' }, { transform: 'translateX(0)' }], + zoom: [{ opacity: 0, transform: 'scale(1.12)' }, { opacity: 1, transform: 'scale(1)' }], +} + +/** A gallery (6R.16): its pictures and videos one after another, each for its seconds, coming in with its transition. */ +function Gallery({ w, items, now }) { + const i = pageAt(items.length, w.gallery_seconds || 5, now.getTime()) + const m = items[i] + const el = useRef(null) + const frames = GALLERY_IN[w.gallery_transition || 'fade'] + useEffect(() => { + if (!frames || !el.current?.animate) return undefined + const a = el.current.animate(frames, { duration: 700, easing: 'ease-out' }) + return () => a.cancel() + }, [i, frames]) + const fit = { width: '100%', height: '100%', objectFit: w.gallery_fit || 'cover', display: 'block' } + return ( +
+
+ {m.kind === 'video' + ?
+
+ ) +} /** * One of the venue's reviews (6R.19), the next one every few seconds: its stars, what they wrote, diff --git a/tests/e2e/media.mjs b/tests/e2e/media.mjs index dff566e..d883df8 100644 --- a/tests/e2e/media.mjs +++ b/tests/e2e/media.mjs @@ -179,6 +179,23 @@ try { (await page.getByTestId('media-used-by').innerText().catch(() => '')).includes(p1.name) && await page.getByTestId('media-delete').isDisabled()) await page.keyboard.press('Escape') + // ── 6R.16: folders: one made on the page, a file filed from its details, the folder shows only it ── + await page.getByTestId('media-folder-new').click() + await page.getByTestId('media-folder-name').fill('Dishes') + await page.getByTestId('media-folder-save').click() + const made = await waitFor(async () => (await page.locator('[data-testid="media-folder"][data-name="Dishes"]').getAttribute('aria-pressed').catch(() => null)) === 'true' || null, 8000, 200) + r.check('6R.16: a folder made on the Media page (and opened: empty)', made === true && (await page.getByTestId('media-item').count()) === 0) + await page.getByTestId('media-folder-all').click() + await page.locator(`[data-testid="media-item"][data-id="${after1.image.id}"]`).click() + await page.getByTestId('media-folder-pick').click() + await page.getByRole('option', { name: 'Dishes' }).click() + await sleep(600) + await page.keyboard.press('Escape') + await page.locator('[data-testid="media-folder"][data-name="Dishes"]').click() + r.check('6R.16: a file filed in it from its details; the folder shows just that file', + await waitFor(async () => (await page.getByTestId('media-item').count()) === 1 || null, 8000, 200) === true + && (await page.locator('[data-testid="media-folder"][data-name="Dishes"]').textContent()).includes('1')) + // ── 5.3: the customer display's looks pick their pictures from the library ── await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {}) await page.goto(`${MANAGER}/settings`) diff --git a/tests/e2e/signage.mjs b/tests/e2e/signage.mjs index 35b214b..2f5f067 100644 --- a/tests/e2e/signage.mjs +++ b/tests/e2e/signage.mjs @@ -589,19 +589,24 @@ try { contact: { phone: '2310 123456', instagram: '@xenia' } } }) await api('PUT', '/api/signage/reviews', { token: boss, body: { reviews: [{ name: 'Maria', stars: 5, text: 'Best octopus on the island' }, { name: 'Bob', stars: 2, text: 'Meh' }] } }) await api('PUT', '/api/identity/hours', { token: boss, body: { days: [[{ from: '12:00', to: '23:00' }], [], [], [], [], [], []] } }) + const dishes = await api('POST', '/api/media/folders', { token: boss, body: { name: 'Dishes' } }) + await api('POST', '/api/media/move', { token: boss, body: { ids: [photo.id], folder_id: dishes.id } }) 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' }, - { kind: 'reviews', position: 'custom', box: { x: 30, y: 40, w: 40, h: 25 } }] } } }) + { kind: 'reviews', position: 'custom', box: { x: 30, y: 40, w: 40, h: 25 } }, + { kind: 'gallery', position: 'custom', box: { x: 75, y: 30, w: 20, h: 20 }, gallery_source: 'folder', gallery_folder: dishes.id }] } } }) 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', 'reviews'].map(k => tv.getByTestId(`signage-w-${k}`).count()))).every(n => n === 1) + const widgetsOn = async () => (await Promise.all(['shape', 'countdown', 'hours', 'wifi', 'contact', 'ticker', 'reviews', 'gallery'].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.16: a gallery of a media folder shows its picture (kept on the TV)', await tv.getByTestId('signage-w-gallery').getAttribute('data-count') === '1' + && (await tv.getByTestId('signage-w-gallery').locator('img').getAttribute('src')).startsWith('blob:')) r.check('6R.19: a review typed in by hand shows (the 2-star one is left out)', await tv.getByTestId('signage-w-reviews').getAttribute('data-count') === '1' && (await tv.getByTestId('signage-w-reviews').textContent()).includes('Best octopus')) 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()))