feat(signage,scenes): schedule lines with screens and smart days, screens' defaults, horizontal timeline, scenes

- Scenes (Alembic 0043, models/scene.py, /api/scenes, core.scenes.manage): named
  modes on or off (optionally until a time); price rules / deals get the
  condition "a scene is on"; signage lines can play only during a scene;
  turning one on tells every screen and pushes the online menu.
- Signage schedules are lines (signage_schedule_items): playlist, screens
  ([] = every screen), priority, days, smart days (1st / last day, first / last
  week, Greek public holidays or not: core/calendar_days.py, mirrored in
  @xenia/signage), hours, dates, scene. No line → the screen's default
  playlist. 0043 turns the old named schedules into lines for their screens.
- Screens: default playlist, TV shape, turn; what plays now and why.
- Manager: tabs Screens · Playlists · Schedules · Slides (placeholder) ·
  Message and weather; schedule lines with playlist / screens / priority /
  delete on one line; the playlist editor's horizontal timeline of fixed
  cards, the slide's basics beside its preview (one height), then its content;
  Management → Scenes; the scene condition in pricing.
- Tests: backend (lines, smart days, scenes, prices), player logic, e2e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 19:22:47 +02:00
co-authored by Claude Opus 5.5
parent abab158b7c
commit 60e6a16217
44 changed files with 1429 additions and 533 deletions
+53
View File
@@ -0,0 +1,53 @@
"""Smart day filters (owner 2026-11-21): the 1st / last day of the month, its first / last week, and
Greek public holidays (fixed dates and those that follow the Orthodox Easter).
The same rules in JavaScript: packages/signage/src/logic.js (a screen applies its schedule while
the server is down); both sides are tested with the same dates.
"""
from __future__ import annotations
import calendar
from datetime import date, timedelta
# the filters a schedule line can have: any one that holds is enough, except "not_holiday",
# which keeps the line off on public holidays
MONTH_DAYS = ("first", "last", "first_week", "last_week", "holiday", "not_holiday")
_FIXED = ((1, 1), (1, 6), (3, 25), (5, 1), (8, 15), (10, 28), (12, 25), (12, 26))
# days from the Orthodox Easter Sunday: Clean Monday, Good Friday, Easter Sunday, Easter Monday, Whit Monday
_FROM_EASTER = (-48, -2, 0, 1, 50)
def orthodox_easter(year: int) -> date:
"""The Orthodox Easter Sunday (Meeus' Julian algorithm, + 13 days to the Gregorian calendar, 1900-2099)."""
a, b, c = year % 4, year % 7, year % 19
d = (19 * c + 15) % 30
e = (2 * a + 4 * b - d + 34) % 7
month = (d + e + 114) // 31
day = (d + e + 114) % 31 + 1
return date(year, month, day) + timedelta(days=13)
def is_holiday(day: date) -> bool:
"""A Greek public holiday (nationwide)."""
if (day.month, day.day) in _FIXED:
return True
easter = orthodox_easter(day.year)
return any(day == easter + timedelta(days=n) for n in _FROM_EASTER)
def month_days_ok(tokens, day: date) -> bool:
"""Does a day pass a line's smart filters (empty = every day)?"""
tokens = [t for t in (tokens or []) if t in MONTH_DAYS]
if not tokens:
return True
hol = is_holiday(day)
if "not_holiday" in tokens and hol:
return False
wanted = [t for t in tokens if t != "not_holiday"]
if not wanted:
return True
last = calendar.monthrange(day.year, day.month)[1]
return any((t == "first" and day.day == 1) or (t == "last" and day.day == last)
or (t == "first_week" and day.day <= 7) or (t == "last_week" and day.day > last - 7)
or (t == "holiday" and hol) for t in wanted)
+4
View File
@@ -201,6 +201,10 @@ CODES: dict[str, tuple[int, str]] = {
"expense.document_not_found": (404, "Document not found."),
"channel_price.not_found": (404, "Channel price not found."),
"channel_price.set_one_product": (400, "A set price is for one product: pick one product (and no categories), or change the price by an amount or a percentage."),
"scene.not_found": (404, "Scene {scene_id} not found."),
"scene.until_past": (400, "That time has already passed: pick a later one."),
"signage.scene_unknown": (404, "Scene {scene_id} not found."),
"signage.screen_unknown": (404, "Screen {device_id} not found."),
"expense.document_type": (422, "Upload a PDF or a photo (JPG, PNG, WebP or HEIC)."),
"expense.document_too_big": (413, "The file is too big (at most {max_mb} MB)."),
"flag.not_found": (404, "Mark not found."),
@@ -59,9 +59,6 @@ def _ref_exists(source: str, value: int, db) -> bool:
from models.table import Table
t = db.get(Table, value)
return t is not None and bool(t.is_active)
if source == "signage_schedules":
from models.signage import SignageSchedule
return db.get(SignageSchedule, value) is not None
if source == "display_looks":
from models.display_look import DisplayLook
return db.get(DisplayLook, value) is not None
@@ -0,0 +1,119 @@
"""Scenes, and signage schedule lines that name their screens (owner 2026-11-21).
- `scenes`: named modes of the venue (party mode…) that are on or off (models/scene.py).
- `signage_schedule_items` replaces the named schedules of 5.4d: each line has its playlist, its
screens ([] = every screen), its priority, days, hours, dates, smart days and an optional scene.
A schedule's lines become lines for the screens that had that schedule (a schedule no screen
used: its lines are kept, turned off). A screen's own playlist is its default; a screen on a
schedule without its own playlist gets the schedule's "otherwise" playlist as its default.
The device config key `schedule` is gone.
- The key `core.scenes.manage` for owners and store managers.
Revision ID: 0043_scenes_and_schedule_items
Revises: 0042_menu_texts_per_language
Create Date: 2026-11-21 16:00:00
"""
import json
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0043_scenes_and_schedule_items'
down_revision = '0042_menu_texts_per_language'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'scenes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('color', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('activated_at', UTCDateTime(), nullable=True),
sa.Column('until', UTCDateTime(), nullable=True),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_scenes_id', 'scenes', ['id'])
op.create_table(
'signage_schedule_items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('playlist_id', sa.Integer(), sa.ForeignKey('signage_playlists.id', ondelete='CASCADE'), nullable=False),
sa.Column('screen_ids', sa.JSON(), nullable=False),
sa.Column('priority', sa.Integer(), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False),
sa.Column('days', sa.JSON(), nullable=False),
sa.Column('month_days', sa.JSON(), nullable=False),
sa.Column('time_from', sa.String(), nullable=True),
sa.Column('time_to', sa.String(), nullable=True),
sa.Column('date_from', sa.String(), nullable=True),
sa.Column('date_to', sa.String(), nullable=True),
sa.Column('scene_id', sa.Integer(), sa.ForeignKey('scenes.id', ondelete='SET NULL'), nullable=True),
sa.Column('position', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_signage_schedule_items_id', 'signage_schedule_items', ['id'])
op.create_index('ix_signage_schedule_items_playlist_id', 'signage_schedule_items', ['playlist_id'])
op.create_index('ix_signage_schedule_items_scene_id', 'signage_schedule_items', ['scene_id'])
bind = op.get_bind()
playlists = {r[0] for r in bind.execute(sa.text("SELECT id FROM signage_playlists")).fetchall()}
screens = []
for did, cfg in bind.execute(sa.text("SELECT id, config FROM devices WHERE app_key = 'signage'")).fetchall():
c = json.loads(cfg) if isinstance(cfg, str) and cfg else (cfg or {})
screens.append((did, c if isinstance(c, dict) else {}))
from datetime import datetime, timezone
stamp = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')
pos = 0
for sid, name, fallback, entries in bind.execute(sa.text("SELECT id, name, fallback_playlist_id, entries FROM signage_schedules ORDER BY id")).fetchall():
entries = json.loads(entries) if isinstance(entries, str) and entries else (entries or [])
on = [did for did, c in screens if c.get('schedule') == sid]
for e in entries:
if e.get('playlist_id') not in playlists:
continue
bind.execute(sa.text(
"INSERT INTO signage_schedule_items (name, playlist_id, screen_ids, priority, enabled, days, month_days, time_from, time_to, "
"date_from, date_to, scene_id, position, created_at, updated_at) VALUES (:name, :pl, :scr, :pri, :en, :days, '[]', :tf, :tt, :df, :dt, "
"NULL, :pos, :now, :now)"),
{'name': name, 'pl': e['playlist_id'], 'scr': json.dumps(on), 'pri': int(e.get('priority') or 0), 'en': bool(on),
'days': json.dumps(e.get('days') or []), 'tf': e.get('time_from'), 'tt': e.get('time_to'),
'df': e.get('date_from'), 'dt': e.get('date_to'), 'pos': pos, 'now': stamp})
pos += 1
for did, c in screens:
if c.get('schedule') == sid and not c.get('playlist') and fallback in playlists:
c['playlist'] = fallback
for did, c in screens:
if 'schedule' in c:
c.pop('schedule')
bind.execute(sa.text("UPDATE devices SET config = :c WHERE id = :id"), {'c': json.dumps(c) if c else None, 'id': did})
elif c.get('playlist'):
bind.execute(sa.text("UPDATE devices SET config = :c WHERE id = :id"), {'c': json.dumps(c), 'id': did})
op.drop_table('signage_schedules')
# the new key core.scenes.manage for owners and store managers (their role's template)
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'core.scenes.manage' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.create_table(
'signage_schedules',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('fallback_playlist_id', sa.Integer(), sa.ForeignKey('signage_playlists.id', ondelete='SET NULL'), nullable=True),
sa.Column('entries', sa.JSON(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.drop_table('signage_schedule_items')
op.drop_table('scenes')
op.get_bind().execute(sa.text("delete from user_permissions where key = 'core.scenes.manage'"))
+1
View File
@@ -41,5 +41,6 @@ import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
import models.media # noqa: F401 Media (media library, step 5.1)
import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3)
import models.signage # noqa: F401 SignagePlaylist, SignageSlide (signage, step 5.4a)
import models.scene # noqa: F401 Scene (2026-11-21)
import models.tablet_order # noqa: F401 TabletOrder (ordering from a menu tablet, step 6.6)
import models.floor_plan # noqa: F401 FloorPlan, FloorItem (the table map, step 6.8)
+1
View File
@@ -91,6 +91,7 @@ class PriceModifierCondition(Base):
min_order_value {"min": 0.00} (cart total before modifiers)
order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S)
price_group_active {"price_group_id": N}
scene_active {"scene_id": N} (a scene is on: services/scenes.py, 2026-11-21)
user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts)
low_stock {"threshold": N} (placeholder, needs inventory)
"""
+23
View File
@@ -0,0 +1,23 @@
"""Scenes (owner 2026-11-21): a named mode of the venue ("Party mode", "Match night") that is on or
off. What follows a scene: signage schedule lines that play only while it is on (and win by their
priority), and price rules / deals with the condition "a scene is on". Several can be on at once;
one may turn itself off at a time (`until`). services/scenes.py.
"""
from sqlalchemy import Boolean, Column, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class Scene(Base):
__tablename__ = "scenes"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
color = Column(String, nullable=True) # "#rrggbb", the venue's choice
description = Column(String, nullable=True)
is_active = Column(Boolean, nullable=False, default=False)
activated_at = Column(UTCDateTime, nullable=True)
until = Column(UTCDateTime, nullable=True) # on until then (None: until turned off)
sort_order = Column(Integer, nullable=False, default=0)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
+23 -10
View File
@@ -6,8 +6,9 @@ a text, with its time on screen, its transition and when it may show (days, hour
What the slide shows is `content`, typed per kind in routers/signage.py (pictures and videos
as media library ids, which the library protects while used).
A paired signage screen plays the playlist in its device config (`playlist`), in its own
orientation and rotation (modules/signage/manifest.py).
A paired signage screen plays its default playlist (device config `playlist`) in its own
orientation and rotation (modules/signage/manifest.py), unless a schedule line for it matches
(SignageScheduleItem, 2026-11-21).
"""
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
@@ -53,15 +54,27 @@ class SignageSlide(Base):
playlist = relationship("SignagePlaylist", back_populates="slides")
class SignageSchedule(Base):
"""Which playlist plays when (5.4d): entries matched in venue time (services/signage_schedule.py),
the fallback when none matches. A screen with a schedule plays it instead of a single playlist."""
__tablename__ = "signage_schedules"
class SignageScheduleItem(Base):
"""A schedule line (owner 2026-11-21, was named schedules of 5.4d): a playlist on some screens
(none picked = every screen), on some days / hours / dates / smart days (core/calendar_days.py),
optionally only while a scene is on, with a priority. At a moment, a screen plays the line
that matches with the highest priority (then the most specific, then the later one); none →
its own default playlist (Screens). services/signage_schedule.py."""
__tablename__ = "signage_schedule_items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
fallback_playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="SET NULL"), nullable=True)
# [{playlist_id, days, time_from, time_to, date_from, date_to, priority}]
entries = Column(JSON, nullable=False, default=list)
name = Column(String, nullable=True)
playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="CASCADE"), nullable=False, index=True)
screen_ids = Column(JSON, nullable=False, default=list) # [] = every screen
priority = Column(Integer, nullable=False, default=0)
enabled = Column(Boolean, nullable=False, default=True)
days = Column(JSON, nullable=False, default=list) # [0..6], Monday = 0; [] = every day
month_days = Column(JSON, nullable=False, default=list) # smart days: first, last, first_week, last_week, holiday, not_holiday
time_from = Column(String, nullable=True)
time_to = Column(String, nullable=True)
date_from = Column(String, nullable=True)
date_to = Column(String, nullable=True)
scene_id = Column(Integer, ForeignKey("scenes.id", ondelete="SET NULL"), nullable=True, index=True)
position = Column(Integer, nullable=False, default=0)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
+2
View File
@@ -12,6 +12,7 @@ MODULE = Module(
Perm('core.settings.manage', 'Change venue settings', roles=('owner',)),
Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)),
Perm('core.devices.manage', 'Pair, rename, reassign and remove devices', roles=('owner', 'store_manager')),
Perm('core.scenes.manage', 'Make scenes and turn them on or off', roles=('owner', 'store_manager')),
Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()),
),
settings=(
@@ -48,6 +49,7 @@ MODULE = Module(
Mount('routers.media', '/api/media'),
Mount('routers.access', '/api/access'),
Mount('routers.notifications', '/api/platform/notifications'),
Mount('routers.scenes', '/api/scenes'),
Mount('core.modules.api', '/api/platform'),
),
)
@@ -27,8 +27,6 @@ MODULE = Module(
device_app=DeviceApp(login_modes=('none',), scope=(), config=(
# What it plays and how the TV hangs (5.4a); the editor builds for the screen's shape
ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'),
# or a schedule: which playlist plays when (5.4d); it wins over the single playlist
ConfigField('schedule', 'ref', default=None, choices_from='signage_schedules'),
ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')),
ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)),
)),
+4
View File
@@ -630,6 +630,8 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
# Build pricing context once for the whole batch
now = utcnow()
active_pg_ids = build_active_price_group_ids(db, now)
from services.pricing import build_active_scene_ids
active_scenes = build_active_scene_ids(db, now)
# The order's sales point (phase 3S): what the pricing engine's channel condition sees
from core.sales_points import is_sold_at, of_order
order_channel = of_order(order)
@@ -670,6 +672,7 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
}
],
active_price_group_ids=active_pg_ids,
active_scene_ids=active_scenes,
)
# Resolve final unit_price through pricing engine
@@ -804,6 +807,7 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
now=now,
cart_items=final_cart,
active_price_group_ids=active_pg_ids,
active_scene_ids=active_scenes,
)
deal_offers = evaluate_deals(order_id, deal_ctx, already_fired, db)
+2
View File
@@ -718,6 +718,8 @@ def _condition_ok(ctype: str, p: dict) -> bool:
return bool(p.get("channels"))
if ctype == "price_group_active":
return isinstance(p.get("price_group_id"), int)
if ctype == "scene_active":
return isinstance(p.get("scene_id"), int) and not isinstance(p.get("scene_id"), bool)
return ctype in ("user_tier", "low_stock") # old placeholders: kept, never added
+90
View File
@@ -0,0 +1,90 @@
"""Scenes (owner 2026-11-21): list them (everyone in the dashboard), make, change, delete and turn
them on or off (`core.scenes.manage`). services/scenes.py says what follows a scene."""
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, Response
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from core.access.deps import require
from core.errors import XeniaError
from core.timeutil import utcnow
from database import get_db
from models.scene import Scene
from services import scenes as svc
router = APIRouter()
VIEW = "core.dashboard.access"
KEY = "core.scenes.manage"
COLOUR = r"^#[0-9a-fA-F]{6}$"
class SceneBody(BaseModel):
name: str = Field(min_length=1, max_length=60)
color: Optional[str] = Field(default=None, pattern=COLOUR)
description: Optional[str] = Field(default=None, max_length=200)
class ActiveBody(BaseModel):
active: bool
until: Optional[datetime] = None # on until then (UTC); None: until turned off
def _scene(db, sid: int) -> Scene:
s = db.get(Scene, sid)
if s is None:
raise XeniaError("scene.not_found", scene_id=sid)
return s
@router.get("")
def list_scenes(db: Session = Depends(get_db), user=Depends(require(VIEW))):
return [svc.out(s) for s in db.query(Scene).order_by(Scene.sort_order, Scene.id)]
@router.post("", status_code=201)
def create_scene(body: SceneBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = Scene(name=body.name.strip(), color=body.color, description=(body.description or "").strip() or None,
sort_order=db.query(Scene).count())
db.add(s)
db.commit()
db.refresh(s)
svc.changed(db)
return svc.out(s)
@router.put("/{scene_id}")
def update_scene(scene_id: int, body: SceneBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _scene(db, scene_id)
s.name, s.color, s.description = body.name.strip(), body.color, (body.description or "").strip() or None
db.commit()
svc.changed(db)
return svc.out(s)
@router.put("/{scene_id}/active")
def set_active(scene_id: int, body: ActiveBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _scene(db, scene_id)
if body.active and body.until is not None and svc._aware(body.until) <= utcnow():
raise XeniaError("scene.until_past")
s.is_active = body.active
s.activated_at = utcnow() if body.active else None
s.until = body.until if body.active else None
db.commit()
svc.changed(db)
return svc.out(s)
@router.delete("/{scene_id}", status_code=204)
def delete_scene(scene_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""The signage lines that played only in it are turned off (they would otherwise play always)."""
s = _scene(db, scene_id)
from models.signage import SignageScheduleItem
for item in db.query(SignageScheduleItem).filter(SignageScheduleItem.scene_id == s.id):
item.scene_id = None
item.enabled = False
db.delete(s)
db.commit()
svc.changed(db)
return Response(status_code=204)
+112 -104
View File
@@ -35,7 +35,7 @@ from sqlalchemy.orm import Session
from core.access.deps import require, require_device
from core.errors import XeniaError
from database import get_db
from models.signage import SignagePlaylist, SignageSchedule, SignageSlide
from models.signage import SignagePlaylist, SignageScheduleItem, SignageSlide
from services import media as media_store
from services import video as video_store
from services.ws_bus import broadcast_sync
@@ -218,14 +218,21 @@ class OrderBody(BaseModel):
slide_ids: List[int]
class ScheduleEntry(BaseModel):
class ScheduleLine(BaseModel):
"""A schedule line (owner 2026-11-21): a playlist on some screens ([] = every screen), when, with a priority."""
id: Optional[int] = None
name: Optional[str] = Field(default=None, max_length=80)
playlist_id: int
screen_ids: List[int] = Field(default_factory=list)
priority: int = Field(default=0, ge=0, le=100)
enabled: bool = True
days: List[int] = Field(default_factory=list) # [0..6], Monday = 0; [] = every day
month_days: List[str] = Field(default_factory=list) # core/calendar_days.MONTH_DAYS
time_from: Optional[str] = Field(default=None, pattern=TIME)
time_to: Optional[str] = Field(default=None, pattern=TIME)
date_from: Optional[str] = Field(default=None, pattern=DATE)
date_to: Optional[str] = Field(default=None, pattern=DATE)
priority: int = Field(default=0, ge=0, le=100)
scene_id: Optional[int] = None
@field_validator("days")
@classmethod
@@ -234,16 +241,21 @@ class ScheduleEntry(BaseModel):
raise ValueError("days are 0 (Monday) to 6 (Sunday)")
return sorted(set(v))
@field_validator("month_days")
@classmethod
def _month_days(cls, v):
from core.calendar_days import MONTH_DAYS
if any(d not in MONTH_DAYS for d in v):
raise ValueError(f"smart days are {', '.join(MONTH_DAYS)}")
return [d for d in MONTH_DAYS if d in v]
class ScheduleBody(BaseModel):
name: str = Field(min_length=1, max_length=80)
fallback_playlist_id: Optional[int] = None
entries: List[ScheduleEntry] = Field(default_factory=list, max_length=100)
class SchedulesBody(BaseModel):
lines: List[ScheduleLine] = Field(default_factory=list, max_length=200)
class ScreenBody(BaseModel):
playlist_id: Optional[int] = None
schedule_id: Optional[int] = None
playlist_id: Optional[int] = None # its default playlist
orientation: Optional[Orientation] = None
rotation: Optional[Literal[0, 90, 180, 270]] = None
@@ -355,24 +367,18 @@ def _screen_config(dev) -> dict:
return effective(for_app("signage"), dev.config)
def _screen_playlists(db, d) -> set:
"""Every playlist a screen may play: its default and those of its schedule lines."""
from services.signage_schedule import lines_for
out = {i.playlist_id for i in lines_for(db, d.id)}
if _screen_config(d).get("playlist"):
out.add(_screen_config(d)["playlist"])
return out
def _screens_playing(db, playlist_id: int) -> list[int]:
"""The screens that play it: as their playlist, or anywhere in their schedule."""
in_schedules = {s.id for s in db.query(SignageSchedule) if playlist_id in _schedule_playlists(s)}
out = []
for d in _screens(db):
cfg = _screen_config(d)
if cfg.get("schedule") in in_schedules or (not cfg.get("schedule") and cfg.get("playlist") == playlist_id):
out.append(d.id)
return out
def _schedule_playlists(s) -> set:
if s is None:
return set()
out = {e.get("playlist_id") for e in (s.entries or []) if e.get("playlist_id")}
if s.fallback_playlist_id:
out.add(s.fallback_playlist_id)
return out
"""The screens that may play it: as their default, or in one of their schedule lines."""
return [d.id for d in _screens(db) if playlist_id in _screen_playlists(db, d)]
def _tell(ids: list[int]) -> None:
@@ -455,7 +461,7 @@ def menu_changed(db) -> None:
the screens with a menu board on their playlist read it again."""
playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")}
if playlists:
_tell([d.id for d in _screens(db) if _screen_config(d).get("playlist") in playlists])
_tell([d.id for d in _screens(db) if _screen_playlists(db, d) & playlists])
# ── playlists ──────────────────────────────────────────────────────────────────
@@ -500,12 +506,8 @@ def delete_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depend
for d in _screens(db):
if (d.config or {}).get("playlist") == p.id:
d.config = {**(d.config or {}), "playlist": None}
for sch in db.query(SignageSchedule):
kept = [e for e in (sch.entries or []) if e.get("playlist_id") != p.id]
if kept != (sch.entries or []):
sch.entries = kept
if sch.fallback_playlist_id == p.id:
sch.fallback_playlist_id = None
for item in db.query(SignageScheduleItem).filter(SignageScheduleItem.playlist_id == p.id):
db.delete(item) # its schedule lines go with it
db.delete(p)
db.commit()
_tell(stopped)
@@ -608,17 +610,17 @@ def duplicate_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(r
# ── screens ────────────────────────────────────────────────────────────────────
def _screen_out(db, d) -> dict:
"""A screen: its default playlist, shape and turn, and what plays on it now (a schedule line wins)."""
from services.signage_schedule import now_for
cfg = _screen_config(d)
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
sch = db.get(SignageSchedule, cfg["schedule"]) if cfg.get("schedule") else None
if sch is not None:
ids = _schedule_playlists(sch)
now_id, scheduled = now_for(db, d)
now_p = db.get(SignagePlaylist, now_id) if now_id else None
ids = _screen_playlists(db, d)
shapes = {x.orientation for x in db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids))} if ids else set()
else:
shapes = {p.orientation} if p else set()
return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None,
"schedule_id": sch.id if sch else None, "schedule_name": sch.name if sch else None,
"orientation": cfg["orientation"], "rotation": cfg["rotation"],
"now": {"id": now_p.id, "name": now_p.name, "scheduled": scheduled} if now_p else None,
"orientation_mismatch": any(o != cfg["orientation"] for o in shapes)}
@@ -636,7 +638,7 @@ def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db
raise XeniaError("signage.not_a_screen", device_id=device_id)
cfg = dict(d.config or {})
for key in body.model_fields_set:
cfg[{"playlist_id": "playlist", "schedule_id": "schedule"}.get(key, key)] = getattr(body, key)
cfg[{"playlist_id": "playlist"}.get(key, key)] = getattr(body, key)
d.config = validate(for_app("signage"), cfg, db)
db.commit()
broadcast_sync("device.updated", {}, device_ids=[d.id])
@@ -665,24 +667,29 @@ def _resolved(db, p: SignagePlaylist) -> dict:
def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))):
"""What this screen plays: its settings and its playlist with every slide and media address.
Slides that are off are left out; time windows are the player's (it keeps playing offline).
With a schedule (5.4d): the schedule and every playlist in it, so the screen switches by
itself; `playlist` is the one playing now. `version` changes whenever anything here does."""
With schedule lines for it (5.4d, 2026-11-21): the lines, the scenes on now and every playlist
they name, so the screen switches by itself; `playlist` is the one playing now and the
schedule's `fallback_playlist_id` is the screen's default. `version` changes whenever anything
here does."""
from core.timeutil import venue_now, venue_tz
from services import weather
from services.signage_schedule import pick
from services.scenes import active_ids
from services.signage_schedule import entry_of, lines_for, pick
cfg = _screen_config(dev)
sch = db.get(SignageSchedule, cfg["schedule"]) if cfg.get("schedule") else None
lines = lines_for(db, dev.id)
schedule, playlists, playlist = None, None, None
if sch is not None:
ids = _schedule_playlists(sch)
default = cfg.get("playlist")
if lines:
ids = _screen_playlists(db, dev)
playlists = {str(p.id): _resolved(db, p) for p in
(db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids)).all() if ids else [])}
now_id = pick(sch.entries or [], sch.fallback_playlist_id, venue_now())
scenes = sorted(active_ids(db))
entries = [entry_of(i) for i in lines]
now_id = pick(entries, default, venue_now(), scenes)
playlist = playlists.get(str(now_id)) if now_id else None
schedule = {"id": sch.id, "name": sch.name, "entries": sch.entries or [], "fallback_playlist_id": sch.fallback_playlist_id,
"timezone": venue_tz().key}
schedule = {"entries": entries, "fallback_playlist_id": default, "scenes": scenes, "timezone": venue_tz().key}
else:
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
p = db.get(SignagePlaylist, default) if default else None
playlist = _resolved(db, p) if p is not None else None
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
"playlist": playlist, "schedule": schedule, "playlists": playlists,
@@ -693,73 +700,74 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
return out
# ── schedules (5.4d) ───────────────────────────────────────────────────────────
# ── schedules (5.4d; lines with their screens and scenes, owner 2026-11-21) ─────
def _schedule(db, sid: int) -> SignageSchedule:
s = db.get(SignageSchedule, sid)
if s is None:
raise XeniaError("signage.schedule_unknown", schedule_id=sid)
return s
def _line_out(i: SignageScheduleItem, now_ids: dict) -> dict:
return {"id": i.id, "name": i.name, "playlist_id": i.playlist_id, "screen_ids": i.screen_ids or [], "priority": i.priority,
"enabled": bool(i.enabled), "days": i.days or [], "month_days": i.month_days or [], "time_from": i.time_from,
"time_to": i.time_to, "date_from": i.date_from, "date_to": i.date_to, "scene_id": i.scene_id, "position": i.position,
# the screens where this line wins now
"playing_on": now_ids.get(i.id, [])}
def _schedule_out(db, s: SignageSchedule) -> dict:
def _lines_out(db) -> list:
from core.timeutil import venue_now
from services.signage_schedule import pick
names = {p.id: p.name for p in db.query(SignagePlaylist)}
now_id = pick(s.entries or [], s.fallback_playlist_id, venue_now())
return {"id": s.id, "name": s.name, "fallback_playlist_id": s.fallback_playlist_id, "entries": s.entries or [],
"playing_now": {"id": now_id, "name": names.get(now_id)} if now_id else None,
"screens": [{"id": d.id, "name": d.name} for d in _screens(db) if _screen_config(d).get("schedule") == s.id]}
def _check_schedule(db, body: ScheduleBody) -> None:
for pid in [body.fallback_playlist_id, *[e.playlist_id for e in body.entries]]:
if pid is not None:
_playlist(db, pid)
from services.scenes import active_ids
from services.signage_schedule import entry_of, lines_for, matches
local, scenes = venue_now(), active_ids(db)
winners: dict = {}
for d in _screens(db):
best, key = None, None
for n, i in enumerate(lines_for(db, d.id)):
e = entry_of(i)
if not matches(e, local, scenes):
continue
from services.signage_schedule import _specific
k = (i.priority or 0, _specific(e), n)
if key is None or k > key:
best, key = i.id, k
if best is not None:
winners.setdefault(best, []).append({"id": d.id, "name": d.name})
items = db.query(SignageScheduleItem).order_by(SignageScheduleItem.position, SignageScheduleItem.id).all()
return [_line_out(i, winners) for i in items]
@router.get("/schedules")
def list_schedules(db: Session = Depends(get_db), user=Depends(require(KEY))):
return [_schedule_out(db, s) for s in db.query(SignageSchedule).order_by(SignageSchedule.name)]
return _lines_out(db)
@router.post("/schedules", status_code=201)
def create_schedule(body: ScheduleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
_check_schedule(db, body)
s = SignageSchedule(name=body.name.strip(), fallback_playlist_id=body.fallback_playlist_id,
entries=[e.model_dump() for e in body.entries])
db.add(s)
@router.put("/schedules")
def save_schedules(body: SchedulesBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Every schedule line at once (the tab saves them together); ids that aren't sent are deleted."""
from models.scene import Scene
screens = {d.id for d in _screens(db)}
for line in body.lines:
_playlist(db, line.playlist_id)
if line.scene_id is not None and db.get(Scene, line.scene_id) is None:
raise XeniaError("signage.scene_unknown", scene_id=line.scene_id)
for sid in line.screen_ids:
if sid not in screens:
raise XeniaError("signage.screen_unknown", device_id=sid)
keep = {line.id for line in body.lines if line.id}
for item in db.query(SignageScheduleItem):
if item.id not in keep:
db.delete(item)
db.flush()
for n, line in enumerate(body.lines):
item = db.get(SignageScheduleItem, line.id) if line.id else None
if item is None:
item = SignageScheduleItem()
db.add(item)
for k, v in line.model_dump(exclude={"id"}).items():
setattr(item, k, (v or "").strip() or None if k == "name" else v)
item.screen_ids = sorted(set(line.screen_ids))
item.position = n
db.commit()
db.refresh(s)
return _schedule_out(db, s)
_tell([d.id for d in _screens(db)]) # their lines may have changed
return _lines_out(db)
@router.put("/schedules/{schedule_id}")
def update_schedule(schedule_id: int, body: ScheduleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _schedule(db, schedule_id)
_check_schedule(db, body)
s.name = body.name.strip()
s.fallback_playlist_id = body.fallback_playlist_id
s.entries = [e.model_dump() for e in body.entries]
db.commit()
db.refresh(s)
_tell([d.id for d in _screens(db) if _screen_config(d).get("schedule") == s.id])
return _schedule_out(db, s)
@router.delete("/schedules/{schedule_id}", status_code=204)
def delete_schedule(schedule_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _schedule(db, schedule_id)
moved = []
for d in _screens(db):
if (d.config or {}).get("schedule") == s.id:
d.config = {**(d.config or {}), "schedule": None}
moved.append(d.id)
db.delete(s)
db.commit()
_tell(moved)
return Response(status_code=204)
# ── the message of the day and the weather (5.4c) ──────────────────────────────
class MessageBody(BaseModel):
+1 -1
View File
@@ -713,7 +713,7 @@ async def _wait_for_site_id(max_seconds: int = 30) -> None:
# not at the next 5-minute tick (phase 3S): request_menu_push() from any thread wakes the
# worker; edits in a row within MENU_SETTLE_SECONDS become one push.
MENU_SETTLE_SECONDS = 5
MENU_PATHS = ("/api/products", "/api/pricing", "/api/connect/fees", "/api/data-transfer/import",
MENU_PATHS = ("/api/products", "/api/pricing", "/api/scenes", "/api/connect/fees", "/api/data-transfer/import",
"/api/connect/qr", "/api/tables") # S.7: the tables' QR codes travel with the menu
_menu_wake: "asyncio.Event | None" = None
_menu_loop = None
+6 -2
View File
@@ -227,6 +227,8 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = utcnow()
active = build_active_price_group_ids(db, now)
from services.pricing import build_active_scene_ids
scenes = build_active_scene_ids(db, now)
channel = point or point_for(order_type)
cart = list(existing_cart or [])
out = []
@@ -236,7 +238,7 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No
raise _bad(n, "not_sold_here")
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids,
"quantity": line.quantity, "unit_price": p.base_price + line.extra}
ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active)
ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active, active_scene_ids=scenes)
unit, events = resolve_price(p, line.quantity, line.extra, ctx, db)
out.append((unit, events))
cart.append({**here, "unit_price": unit})
@@ -250,11 +252,13 @@ def unit_prices(db, products, point: str, now=None) -> list[float]:
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = now or utcnow()
active = build_active_price_group_ids(db, now)
from services.pricing import build_active_scene_ids
scenes = build_active_scene_ids(db, now)
out = []
for p in products:
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids,
"quantity": 1, "unit_price": p.base_price}
ctx = OrderContext(channel=point, now=now, cart_items=[here], active_price_group_ids=active)
ctx = OrderContext(channel=point, now=now, cart_items=[here], active_price_group_ids=active, active_scene_ids=scenes)
out.append(resolve_price(p, 1, 0.0, ctx, db)[0])
return out
+12
View File
@@ -38,6 +38,7 @@ class OrderContext:
cart_items: list # list of {product_id, category_id (primary), category_ids, quantity, unit_price}
active_price_group_ids: set # set of PriceGroup.id that are currently active
user_tier: Optional[str] = None # 'bronze'|'silver'|'gold' — placeholder
active_scene_ids: set = field(default_factory=set) # the scenes on now (services/scenes.py, 2026-11-21)
@dataclass
@@ -144,6 +145,11 @@ def _eval_condition(ctype: str, params: dict, ctx: OrderContext,
passed = pgid in ctx.active_price_group_ids
return passed, {"price_group_active": passed}
if ctype == "scene_active":
# a scene is on (owner 2026-11-21): party mode, match night…
passed = params.get("scene_id") in ctx.active_scene_ids
return passed, {"scene_active": passed}
if ctype == "user_tier":
passed = ctx.user_tier in params.get("tiers", [])
return passed, {"user_tier": ctx.user_tier}
@@ -236,6 +242,12 @@ def _price_group_is_active(pg, now: datetime) -> bool:
return bool(pg.is_active)
def build_active_scene_ids(db: Session, now: datetime) -> set:
"""The scenes on at `now` (services/scenes.py), for the condition "a scene is on"."""
from services.scenes import active_ids
return active_ids(db, now)
def build_active_price_group_ids(db: Session, now: datetime) -> set:
"""Fetch all price groups once per request and return active IDs."""
from models.pricing import PriceGroup
+42
View File
@@ -0,0 +1,42 @@
"""Scenes (owner 2026-11-21, models/scene.py): which are on now, and telling what follows them.
A scene is on when it was turned on and its `until` (if any) has not passed. When scenes change,
the signage screens are told (their schedules may pick another playlist) and the prices are
recomputed by whoever asks next (price rules read `active_ids` through the pricing context).
"""
from __future__ import annotations
from datetime import datetime
from core.timeutil import utcnow
def _aware(dt):
from datetime import timezone
return dt if dt is None or dt.tzinfo else dt.replace(tzinfo=timezone.utc)
def is_on(scene, now: datetime | None = None) -> bool:
now = now or utcnow()
return bool(scene.is_active) and (scene.until is None or _aware(scene.until) > _aware(now))
def active_ids(db, now: datetime | None = None) -> set[int]:
from models.scene import Scene
return {s.id for s in db.query(Scene).filter(Scene.is_active.is_(True)) if is_on(s, now)}
def out(scene, now: datetime | None = None) -> dict:
return {"id": scene.id, "name": scene.name, "color": scene.color, "description": scene.description,
"active": is_on(scene, now), "activated_at": scene.activated_at, "until": scene.until, "sort_order": scene.sort_order}
def changed(db) -> None:
"""Scenes changed: the signage screens look again; the dashboards refresh their scene lists."""
from services.ws_bus import broadcast_sync
broadcast_sync("scenes.changed", {})
try:
from routers.signage import tell_all_screens
tell_all_screens(db)
except Exception: # signage off or not loaded: nothing to tell
pass
+51 -21
View File
@@ -1,13 +1,17 @@
"""Signage schedules (plan step 5.4d): which playlist a screen plays when.
"""Signage schedules (plan step 5.4d; lines with their screens and scenes, owner 2026-11-21): which
playlist a screen plays when.
A schedule is a list of entries {playlist_id, days, time_from, time_to, date_from, date_to,
priority} and a fallback playlist. At a moment (venue time) the entries that match are:
A screen's lines are the schedule lines (models/signage.py SignageScheduleItem) that are on and
name it (or no screen = every screen). At a moment (venue time) a line matches when:
- its days include today (empty = every day),
- its smart days hold (core/calendar_days.py: 1st / last day, first / last week, public
holidays or not; empty = every day),
- the time is inside [time_from, time_to) (empty = all day; a window that passes midnight,
e.g. 22:00-02:00, counts the after-midnight part for the day it started),
- today is inside [date_from, date_to] (empty = no limit).
- today is inside [date_from, date_to] (empty = no limit),
- its scene (if any) is on.
The winner is the highest priority, then the most specific (dates > days > hours), then the
later entry in the list. No match → the fallback (None = a blank screen).
later line. No match → the screen's default playlist (None = a blank screen).
`pick()` is pure (unit-tested; the player in 5.5a does the same in JavaScript so a screen
switches by itself while the server is down). `schedule_worker` tells a screen when its pick
@@ -30,12 +34,15 @@ def _minutes(hhmm: str | None) -> int | None:
def _date_ok(e: dict, day) -> bool:
from core.calendar_days import month_days_ok
d = day.isoformat()
return (not e.get("date_from") or d >= e["date_from"]) and (not e.get("date_to") or d <= e["date_to"])
return (not e.get("date_from") or d >= e["date_from"]) and (not e.get("date_to") or d <= e["date_to"]) and month_days_ok(e.get("month_days"), day)
def matches(e: dict, local: datetime) -> bool:
"""Does entry `e` cover this venue-local moment?"""
def matches(e: dict, local: datetime, scenes=None) -> bool:
"""Does entry `e` cover this venue-local moment (with these scenes on)?"""
if e.get("scene_id") is not None and e["scene_id"] not in (scenes or ()):
return False
days = e.get("days") or []
start, end = _minutes(e.get("time_from")), _minutes(e.get("time_to"))
now = local.hour * 60 + local.minute
@@ -55,15 +62,15 @@ def matches(e: dict, local: datetime) -> bool:
def _specific(e: dict) -> int:
return (4 if (e.get("date_from") or e.get("date_to")) else 0) + (2 if e.get("days") else 0) + \
return (4 if (e.get("date_from") or e.get("date_to")) else 0) + (2 if (e.get("days") or e.get("month_days")) else 0) + \
(1 if (e.get("time_from") or e.get("time_to")) else 0)
def pick(entries: list[dict], fallback: int | None, local: datetime) -> int | None:
def pick(entries: list[dict], fallback: int | None, local: datetime, scenes=None) -> int | None:
"""The playlist id that plays at `local` (venue time)."""
best, best_key = None, None
for i, e in enumerate(entries or []):
if e.get("playlist_id") is None or not matches(e, local):
if e.get("playlist_id") is None or not matches(e, local, scenes):
continue
key = (e.get("priority") or 0, _specific(e), i)
if best_key is None or key > best_key:
@@ -76,20 +83,43 @@ def pick(entries: list[dict], fallback: int | None, local: datetime) -> int | No
_playing: dict[int, int | None] = {} # screen id → the playlist it was told about
def due_changes(db, local: datetime | None = None) -> list[int]:
"""The screens on a schedule whose pick is different from the last one seen (and remember it)."""
ENTRY_KEYS = ("playlist_id", "days", "month_days", "time_from", "time_to", "date_from", "date_to", "priority", "scene_id")
def entry_of(item) -> dict:
"""A schedule line as the screens and pick() read it."""
return {k: getattr(item, k) for k in ENTRY_KEYS}
def lines_for(db, screen_id: int) -> list:
"""The schedule lines that are on and name this screen (or no screen), in order."""
from models.signage import SignageScheduleItem
return [i for i in db.query(SignageScheduleItem).filter(SignageScheduleItem.enabled.is_(True))
.order_by(SignageScheduleItem.position, SignageScheduleItem.id) if not i.screen_ids or screen_id in i.screen_ids]
def now_for(db, dev, local: datetime | None = None, scenes=None) -> tuple[int | None, bool]:
"""(the playlist a screen plays now, whether a schedule line picked it)."""
from core.timeutil import venue_now
from models.signage import SignageSchedule
from routers.signage import _screen_config, _screens
from routers.signage import _screen_config
from services.scenes import active_ids
local = local or venue_now()
scenes = active_ids(db) if scenes is None else scenes
default = _screen_config(dev).get("playlist")
got = pick([entry_of(i) for i in lines_for(db, dev.id)], None, local, scenes)
return (got, True) if got is not None else (default, False)
def due_changes(db, local: datetime | None = None) -> list[int]:
"""The screens whose pick is different from the last one seen (and remember it)."""
from core.timeutil import venue_now
from routers.signage import _screens
from services.scenes import active_ids
local = local or venue_now()
scenes = active_ids(db)
changed = []
for d in _screens(db):
sid = _screen_config(d).get("schedule")
if not sid:
_playing.pop(d.id, None)
continue
s = db.get(SignageSchedule, sid)
now = pick(s.entries or [], s.fallback_playlist_id, local) if s else None
now = now_for(db, d, local, scenes)[0]
if d.id in _playing and _playing[d.id] != now:
changed.append(d.id)
_playing[d.id] = now
+51
View File
@@ -0,0 +1,51 @@
"""Scenes (owner 2026-11-21): named modes of the venue (party mode) that are on or off; price
rules follow them ("a scene is on"), signage lines too (tests/test_signage_schedule.py)."""
from datetime import timedelta
from core.timeutil import utcnow
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import menu, till # noqa: F401 (fixtures)
from tests.test_pricing_setup import happy_hour
def test_scenes_are_made_and_switched(client, owner_h, make_user, login):
r = client.post("/api/scenes", headers=owner_h, json={"name": " Party mode ", "color": "#ff6699"})
assert r.status_code == 201 and r.json()["name"] == "Party mode" and r.json()["active"] is False
sid = r.json()["id"]
assert client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": True}).json()["active"] is True
soon = (utcnow() + timedelta(hours=2)).isoformat()
on = client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": True, "until": soon}).json()
assert on["active"] is True and on["until"]
past = (utcnow() - timedelta(minutes=1)).isoformat()
assert err(client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": True, "until": past})) == "scene.until_past"
assert err(client.put("/api/scenes/99999/active", headers=owner_h, json={"active": True})) == "scene.not_found"
assert client.post("/api/scenes", headers=owner_h, json={"name": "x", "color": "pink"}).status_code == 422
# a waiter can't switch scenes
h = login(make_user(role="waiter"), client="waiter")
assert client.put(f"/api/scenes/{sid}/active", headers=h, json={"active": False}).status_code == 403
def test_a_scene_turns_itself_off(db, client, owner_h):
from models.scene import Scene
from services.scenes import active_ids
s = Scene(name="Brunch", is_active=True, until=utcnow() - timedelta(seconds=1), sort_order=0)
db.add(s)
db.commit()
assert s.id not in active_ids(db)
assert client.get("/api/scenes", headers=owner_h).json()[0]["active"] is False
def test_a_price_rule_follows_a_scene(client, owner_h, till, menu):
line = {"product_id": menu["coffee"].id, "quantity": 2}
sid = client.post("/api/scenes", headers=owner_h, json={"name": "Party mode"}).json()["id"]
rule = happy_hour(targets=[{"target_type": "item", "target_ids": [menu["coffee"].id]}])
rule["conditions"] = [{"condition_type": "scene_active", "params": {"scene_id": sid}}]
r = client.post("/api/pricing/modifiers", headers=owner_h, json=rule)
assert r.status_code == 201, r.text
assert client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()["total"] == 6.0
client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": True})
assert client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()["total"] == 4.8
client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": False})
assert client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()["total"] == 6.0
bad = dict(rule, conditions=[{"condition_type": "scene_active", "params": {}}])
assert err(client.post("/api/pricing/modifiers", headers=owner_h, json=bad)) == "pricing.bad_condition"
+92 -43
View File
@@ -1,10 +1,12 @@
"""Signage schedules (plan step 5.4d): which playlist plays when (days, hours that may pass
midnight, dates, priority, a fallback); a screen on a schedule gets every playlist in it so it
switches by itself, and the server tells it when the pick changes."""
from datetime import datetime
"""Signage schedules (plan step 5.4d; lines with their screens, smart days and scenes, owner
2026-11-21): which playlist plays when (days, hours that may pass midnight, dates, smart days,
priority, a scene); no line → the screen's default playlist. A screen with lines gets every
playlist they name so it switches by itself, and the server tells it when the pick changes."""
from datetime import date, datetime
import pytest
from core.calendar_days import is_holiday, month_days_ok, orthodox_easter
from services.signage_schedule import matches, pick
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_signage import playlist, slide
@@ -27,18 +29,37 @@ def test_which_entries_match():
assert matches(xmas, datetime(2026, 12, 24, 20, 0)) and not matches(xmas, datetime(2026, 12, 28, 9, 0))
assert matches({"playlist_id": 4}, MON_10) # always
assert matches({"playlist_id": 5, "time_from": "18:00"}, datetime(2026, 11, 16, 23, 59)) # until the end of the day
party = {"playlist_id": 6, "scene_id": 7}
assert not matches(party, MON_10) and matches(party, MON_10, {7}) # only while the scene is on
def test_smart_days():
"""The same dates as packages/signage/tests/logic.test.mjs."""
assert [orthodox_easter(y) for y in (2025, 2026, 2027)] == [date(2025, 4, 20), date(2026, 4, 12), date(2027, 5, 2)]
assert is_holiday(date(2026, 3, 25)) and is_holiday(date(2026, 2, 23)) # Independence Day; Clean Monday 2026
assert is_holiday(date(2026, 4, 10)) and is_holiday(date(2026, 4, 13)) # Good Friday, Easter Monday
assert is_holiday(date(2026, 6, 1)) and not is_holiday(date(2026, 6, 2)) # Whit Monday
assert month_days_ok(["first"], date(2026, 11, 1)) and not month_days_ok(["first"], date(2026, 11, 2))
assert month_days_ok(["last"], date(2026, 2, 28)) and not month_days_ok(["last"], date(2026, 2, 27))
assert month_days_ok(["first_week"], date(2026, 11, 7)) and not month_days_ok(["first_week"], date(2026, 11, 8))
assert month_days_ok(["last_week"], date(2026, 11, 24)) and not month_days_ok(["last_week"], date(2026, 11, 23))
assert month_days_ok(["first", "last"], date(2026, 11, 30)) # any one is enough
assert not month_days_ok(["not_holiday"], date(2026, 12, 25)) and month_days_ok(["not_holiday"], date(2026, 12, 24))
assert matches({"playlist_id": 1, "month_days": ["last"], "time_from": "18:00"}, datetime(2026, 11, 30, 19, 0))
def test_the_winner():
entries = [{"playlist_id": 10, "time_from": "12:00", "time_to": "15:00"},
{"playlist_id": 20, "days": [5, 6]},
{"playlist_id": 30, "days": [5, 6], "time_from": "12:00", "time_to": "15:00"},
{"playlist_id": 40, "date_from": "2026-11-21", "date_to": "2026-11-21", "priority": 5}]
assert pick(entries, 99, MON_10) == 99 # nothing → the fallback
{"playlist_id": 40, "date_from": "2026-11-21", "date_to": "2026-11-21", "priority": 5},
{"playlist_id": 50, "scene_id": 1, "priority": 9}]
assert pick(entries, 99, MON_10) == 99 # nothing → the default
assert pick(entries, 99, MON_13) == 10
assert pick(entries, 99, datetime(2026, 11, 22, 13, 0)) == 30 # Sunday lunch: days + hours beat hours alone
assert pick(entries, 99, SAT_13) == 40 # the higher priority wins
assert pick(entries, None, MON_10) is None # no fallback → blank
assert pick(entries, 99, SAT_13, {1}) == 50 # party mode on: its line, the highest priority
assert pick(entries, None, MON_10) is None # no default → blank
@pytest.fixture
@@ -64,31 +85,59 @@ def setup(client, owner_h, pair):
lunch, weekend, normal = (playlist(client, owner_h, n) for n in ("Lunch", "Weekend", "Normal"))
for p in (lunch, weekend, normal):
slide(client, owner_h, p["id"], "text", content={"title": p["name"]})
r = client.post("/api/signage/schedules", headers=owner_h, json={
"name": "The week", "fallback_playlist_id": normal["id"],
"entries": [{"playlist_id": lunch["id"], "time_from": "12:00", "time_to": "15:00"},
{"playlist_id": weekend["id"], "days": [5, 6], "priority": 1}]})
assert r.status_code == 201, r.text
token, dev = pair("signage", "TV")
client.put(f"/api/signage/screens/{dev.json()['id']}", headers=owner_h, json={"schedule_id": r.json()["id"]})
return {"h": {"X-Xenia-Device": token}, "id": dev.json()["id"], "schedule": r.json(),
_, other = pair("signage", "Bar TV")
tv, bar = dev.json()["id"], other.json()["id"]
client.put(f"/api/signage/screens/{tv}", headers=owner_h, json={"playlist_id": normal["id"]})
r = client.put("/api/signage/schedules", headers=owner_h, json={"lines": [
{"playlist_id": lunch["id"], "screen_ids": [tv], "time_from": "12:00", "time_to": "15:00"},
{"playlist_id": weekend["id"], "days": [5, 6], "priority": 1}]}) # no screens: every screen
assert r.status_code == 200, r.text
return {"h": {"X-Xenia-Device": token}, "id": tv, "bar": bar, "lines": r.json(),
"lunch": lunch["id"], "weekend": weekend["id"], "normal": normal["id"]}
def test_a_screen_gets_its_schedule_and_every_playlist(client, owner_h, setup, at):
def test_a_screen_gets_its_lines_and_every_playlist(client, owner_h, setup, at):
at(MON_10)
got = client.get("/api/signage/screen", headers=setup["h"]).json()
assert got["playlist"]["name"] == "Normal"
assert got["playlist"]["name"] == "Normal" # its default
assert sorted(got["playlists"]) == sorted(str(i) for i in (setup["lunch"], setup["weekend"], setup["normal"]))
assert got["schedule"]["timezone"] == "Europe/Athens" and len(got["schedule"]["entries"]) == 2
assert got["schedule"]["fallback_playlist_id"] == setup["normal"]
at(MON_13)
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Lunch"
at(SAT_13)
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Weekend"
s = client.get("/api/signage/schedules", headers=owner_h).json()[0]
assert s["playing_now"]["name"] == "Weekend" and [x["name"] for x in s["screens"]] == ["TV"]
screen = client.get("/api/signage/screens", headers=owner_h).json()[0]
assert screen["schedule_name"] == "The week" and screen["orientation_mismatch"] is False
lines = client.get("/api/signage/schedules", headers=owner_h).json()
assert sorted(x["name"] for x in lines[1]["playing_on"]) == ["Bar TV", "TV"] # the weekend line is for every screen
screens = {s["name"]: s for s in client.get("/api/signage/screens", headers=owner_h).json()}
assert screens["TV"]["playlist_name"] == "Normal" and screens["TV"]["now"] == {"id": setup["weekend"], "name": "Weekend", "scheduled": True}
assert screens["TV"]["orientation_mismatch"] is False
def test_scenes_switch_screens_and_prices(client, db, owner_h, setup, at, sent):
"""A scene (party mode): its schedule line plays while it is on; a price rule follows it too."""
at(MON_10)
party = playlist(client, owner_h, "Party")
slide(client, owner_h, party["id"], "text", content={"title": "Party"})
scene = client.post("/api/scenes", headers=owner_h, json={"name": "Party mode", "color": "#ff6699"}).json()
lines = client.get("/api/signage/schedules", headers=owner_h).json()
body = [{k: x[k] for k in ("id", "playlist_id", "screen_ids", "priority", "days", "time_from", "time_to")} for x in lines]
body.append({"playlist_id": party["id"], "scene_id": scene["id"], "priority": 50})
assert client.put("/api/signage/schedules", headers=owner_h, json={"lines": body}).status_code == 200
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Normal"
sent.clear()
r = client.put(f"/api/scenes/{scene['id']}/active", headers=owner_h, json={"active": True})
assert r.status_code == 200 and r.json()["active"] is True
assert ("signage.changed", sorted([setup["id"], setup["bar"]])) in sent
got = client.get("/api/signage/screen", headers=setup["h"]).json()
assert got["playlist"]["name"] == "Party" and got["schedule"]["scenes"] == [scene["id"]]
client.put(f"/api/scenes/{scene['id']}/active", headers=owner_h, json={"active": False})
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Normal"
# deleting the scene turns its line off (it would otherwise play always)
assert client.delete(f"/api/scenes/{scene['id']}", headers=owner_h).status_code == 204
left = [x for x in client.get("/api/signage/schedules", headers=owner_h).json() if x["playlist_id"] == party["id"]]
assert left[0]["enabled"] is False and left[0]["scene_id"] is None
def test_the_server_tells_a_screen_when_its_playlist_switches(client, db, setup, at):
@@ -100,7 +149,7 @@ def test_the_server_tells_a_screen_when_its_playlist_switches(client, db, setup,
at(datetime(2026, 11, 16, 11, 59, 40))
assert ss.due_changes(db) == []
at(datetime(2026, 11, 16, 12, 0))
assert ss.due_changes(db) == [setup["id"]] # lunch starts
assert ss.due_changes(db) == [setup["id"]] # lunch starts (only on the TV)
assert ss.due_changes(db) == []
at(datetime(2026, 11, 16, 15, 0))
assert ss.due_changes(db) == [setup["id"]] # and ends
@@ -108,31 +157,31 @@ def test_the_server_tells_a_screen_when_its_playlist_switches(client, db, setup,
def test_changes_and_deletes(client, owner_h, setup, sent, at):
at(MON_10)
sid = setup["schedule"]["id"]
at(MON_13)
lines = client.get("/api/signage/schedules", headers=owner_h).json()
sent.clear()
client.put(f"/api/signage/schedules/{sid}", headers=owner_h, json={"name": "The week", "fallback_playlist_id": setup["lunch"], "entries": []})
assert sent == [("signage.changed", [setup["id"]])]
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Lunch"
# a slide changed in a playlist of the schedule reaches the screen
lunch = client.get(f"/api/signage/playlists/{setup['lunch']}", headers=owner_h).json()
assert client.put("/api/signage/schedules", headers=owner_h, json={"lines": [{"id": lines[1]["id"], "playlist_id": setup["weekend"], "days": [5, 6]}]}).status_code == 200
assert sorted(sent[0][1]) == sorted([setup["id"], setup["bar"]])
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Normal" # the lunch line is gone
# a slide changed in a playlist of its lines reaches the screen
wk = client.get(f"/api/signage/playlists/{setup['weekend']}", headers=owner_h).json()
sent.clear()
client.put(f"/api/signage/slides/{lunch['slides'][0]['id']}", headers=owner_h, json={"duration_s": 20})
assert sent == [("signage.changed", [setup["id"]])]
# deleting a playlist takes it out of the schedule
client.delete(f"/api/signage/playlists/{setup['lunch']}", headers=owner_h)
assert client.get("/api/signage/schedules", headers=owner_h).json()[0]["fallback_playlist_id"] is None
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"] is None
# deleting the schedule: the screen goes back to its playlist (none here)
assert client.delete(f"/api/signage/schedules/{sid}", headers=owner_h).status_code == 204
client.put(f"/api/signage/slides/{wk['slides'][0]['id']}", headers=owner_h, json={"duration_s": 20})
assert sorted(sent[0][1]) == sorted([setup["id"], setup["bar"]])
# deleting a playlist takes its lines with it
client.delete(f"/api/signage/playlists/{setup['weekend']}", headers=owner_h)
assert client.get("/api/signage/schedules", headers=owner_h).json() == []
got = client.get("/api/signage/screen", headers=setup["h"]).json()
assert got["schedule"] is None and got["playlist"] is None
assert got["schedule"] is None and got["playlist"]["name"] == "Normal"
def test_schedules_are_checked(client, owner_h, setup):
body = {"name": "Bad", "entries": [{"playlist_id": 99999}]}
assert err(client.post("/api/signage/schedules", headers=owner_h, json=body)) == "signage.playlist_unknown"
assert client.post("/api/signage/schedules", headers=owner_h, json={"name": "x", "entries": [{"playlist_id": setup["lunch"], "days": [9]}]}).status_code == 422
assert client.post("/api/signage/schedules", headers=owner_h, json={"name": "x", "entries": [{"playlist_id": setup["lunch"], "time_to": "24:00"}]}).status_code == 422
assert err(client.put(f"/api/signage/screens/{setup['id']}", headers=owner_h, json={"schedule_id": 99999})) == "validation.device_config"
assert err(client.get("/api/signage/schedules/99999", headers=owner_h)) in ("http.404", "http.405")
put = lambda line: client.put("/api/signage/schedules", headers=owner_h, json={"lines": [line]}) # noqa: E731
assert err(put({"playlist_id": 99999})) == "signage.playlist_unknown"
assert err(put({"playlist_id": setup["lunch"], "screen_ids": [99999]})) == "signage.screen_unknown"
assert err(put({"playlist_id": setup["lunch"], "scene_id": 99999})) == "signage.scene_unknown"
assert put({"playlist_id": setup["lunch"], "days": [9]}).status_code == 422
assert put({"playlist_id": setup["lunch"], "month_days": ["fullmoon"]}).status_code == 422
assert put({"playlist_id": setup["lunch"], "time_to": "24:00"}).status_code == 422
assert put({"playlist_id": setup["lunch"], "month_days": ["last", "first"]}).json()[0]["month_days"] == ["first", "last"]
assert err(client.put(f"/api/signage/screens/{setup['id']}", headers=owner_h, json={"playlist_id": 99999})) == "validation.device_config"
+2
View File
@@ -42,6 +42,7 @@ import ApprovalsPage from './pages/staff/ApprovalsPage'
import ManagementSchedulePage from './pages/schedule/SchedulePage'
import PrepZonesConfigPage from './pages/printing/PrepZonesPage'
import PricingPage from './pages/pricing/PricingPage'
import ScenesPage from './pages/scenes/ScenesPage'
// Inventory
import ThrowawaysPage from './pages/inventory/ThrowawaysPage'
@@ -155,6 +156,7 @@ export default function App() {
<Route path="management/schedule" element={<ManagementSchedulePage />} />
<Route path="management/prep-zones" element={<PrepZonesConfigPage />} />
<Route path="management/pricing" element={<PricingPage />} />
<Route path="management/scenes" element={<ScenesPage />} />
{/* ── Inventory ── */}
<Route path="inventory/throwaways" element={<ThrowawaysPage />} />
@@ -4,7 +4,7 @@ import { useState } from 'react'
import { ArrowDown, ArrowUp, Check, Pencil, Plus, Power, Trash2, X } from 'lucide-react'
import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access'
import { latin, useFormat, useTranslation } from '@xenia/i18n'
import { Button, IconButton, Input, Select, cx } from '@xenia/ui'
import { Button, Dropdown, IconButton, Input, Select, cx } from '@xenia/ui'
import { COLOURS } from './useCatalog'
import { OLD_PLACEHOLDERS, WEEKDAYS, blankCondition, conditionComplete, toggleIn } from './pricingLogic'
@@ -220,6 +220,12 @@ function ConditionFields({ cond, onChange, catalog }) {
placeholder={catalog.groups.length ? t('pricing.choose') : t('pricing.condition.noGroups')}
options={catalog.groups.map(g => ({ value: g.id, label: g.name }))} />
)
case 'scene_active': return (
<Dropdown size="sm" value={p.scene_id ?? null} aria-label={t('pricing.condition.fields.scene_id')} data-testid="pricing-cond-scene"
onChange={v => set('scene_id', v == null || v === '' ? null : Number(v))}
placeholder={catalog.scenes.length ? t('pricing.choose') : t('pricing.condition.noScenes')}
options={catalog.scenes.map(s => ({ value: s.id, label: s.name, dot: s.color || undefined }))} />
)
default: return null
}
}
@@ -6,10 +6,10 @@
export const WEEKDAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0, as the server counts
// conditions a rule can have; the deals take fewer
export const MODIFIER_CONDITIONS = ['time_range', 'day_of_week', 'date_range', 'specific_date', 'price_group_active',
export const MODIFIER_CONDITIONS = ['time_range', 'day_of_week', 'date_range', 'specific_date', 'price_group_active', 'scene_active',
'order_channel', 'min_item_quantity', 'min_category_qty', 'min_order_value']
export const DEAL_CONDITIONS = ['min_item_quantity', 'min_order_value', 'time_range', 'day_of_week', 'date_range',
'order_channel', 'price_group_active']
'order_channel', 'price_group_active', 'scene_active']
export const OLD_PLACEHOLDERS = ['user_tier', 'low_stock'] // never did anything; shown, not offered
export const MODIFIER_TARGETS = ['all', 'item', 'category', 'prep_zone', 'tag']
@@ -31,6 +31,7 @@ export function blankCondition(type) {
case 'min_order_value': return { condition_type: type, params: { min: 20 } }
case 'order_channel': return { condition_type: type, params: { channels: [] } }
case 'price_group_active': return { condition_type: type, params: { price_group_id: null } }
case 'scene_active': return { condition_type: type, params: { scene_id: null } } // a scene is on (2026-11-21)
default: return { condition_type: type, params: {} }
}
}
@@ -51,6 +52,7 @@ export function conditionComplete({ condition_type: type, params: p = {} }) {
case 'min_order_value': return positive(p.min ?? 0, 0)
case 'order_channel': return (p.channels ?? []).length > 0
case 'price_group_active': return Number.isInteger(p.price_group_id)
case 'scene_active': return Number.isInteger(p.scene_id)
default: return OLD_PLACEHOLDERS.includes(type)
}
}
@@ -1,10 +1,11 @@
// What the pricing rules can point at (plan step 6.7), loaded once and kept current: products,
// categories (as a tree), prep zones, tags and price groups; and the colours a rule can have.
// categories (as a tree), prep zones, tags, price groups and scenes; and the colours a rule can have.
import { useMemo } from 'react'
import { useLiveQuery } from '../../live/useLiveQuery'
import { CATEGORY_COLOURS } from '../products/categoryColours'
import { categoryTree, treeLabel } from '../products/productsLogic'
import * as api from './pricingApi'
import { SCENE_EVENTS, listScenes } from '../scenes/scenesApi'
export const COLOURS = CATEGORY_COLOURS // the venue's colours (data, as the categories')
@@ -14,6 +15,7 @@ export function useCatalog() {
const zones = useLiveQuery({ queryKey: ['prep-zones'], queryFn: api.listPrepZones, staleTime: 60_000 })
const tags = useLiveQuery({ queryKey: ['product-tags'], queryFn: api.listTags, staleTime: 60_000 })
const groups = useLiveQuery({ queryKey: ['pricing', 'groups'], queryFn: api.listGroups, events: api.PRICING_EVENTS })
const scenes = useLiveQuery({ queryKey: ['scenes'], queryFn: listScenes, events: SCENE_EVENTS })
return useMemo(() => ({
products: (products.data ?? []).filter(p => p.lifecycle_status !== 'archived' && !p.is_service_item)
.sort((a, b) => a.name.localeCompare(b.name)).map(p => ({ id: p.id, name: p.name, price: p.base_price })),
@@ -21,6 +23,7 @@ export function useCatalog() {
zones: (zones.data ?? []).map(z => ({ id: z.id, name: z.name })),
tags: tags.data ?? [],
groups: groups.data ?? [],
}), [products.data, categories.data, zones.data, tags.data, groups.data])
scenes: scenes.data ?? [],
}), [products.data, categories.data, zones.data, tags.data, groups.data, scenes.data])
}
@@ -0,0 +1,110 @@
// Management → Scenes (owner 2026-11-21): the venue's modes ("Party mode", "Match night") that are
// on or off. Turning one on changes, at once, everything that follows it: the signage schedule
// lines that play only in it (Signage → Schedules) and the price rules or deals with the condition
// "a scene is on" (Offers & pricing). Several can be on together; one can be on for a while only.
// Backend: /api/scenes (routers/scenes.py, services/scenes.py).
import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { PartyPopper, Pencil, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Dropdown, EmptyState, Field, IconButton, Input, Page, PageHeader, Spinner, Switch, cx } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import { CATEGORY_COLOURS } from '../products/categoryColours'
import * as api from './scenesApi'
import { FOR, untilOf } from './scenesApi'
export default function ScenesPage() {
const { t } = useTranslation('manager')
const { formatDateTime } = useFormat()
const qc = useQueryClient()
const { data: scenes, isPending } = useLiveQuery({ queryKey: ['scenes'], queryFn: api.listScenes, events: api.SCENE_EVENTS })
const [editing, setEditing] = useState(null)
const [removing, setRemoving] = useState(null)
const [forOf, setForOf] = useState({})
const refresh = () => qc.invalidateQueries({ queryKey: ['scenes'] })
const act = async (fn, done) => {
try { await fn(); if (done) toast.success(done); refresh(); return true } catch (err) { toast.error(errorMessage(err, t)); return false }
}
return (
<Page testId="scenes-page">
<PageHeader title={t('scenes.title')} subtitle={t('scenes.intro')}
actions={<Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="scene-new">{t('scenes.new')}</Button>} />
{isPending ? <div className="flex justify-center p-6"><Spinner /></div>
: !scenes?.length ? <EmptyState icon={<PartyPopper size={28} />} title={t('scenes.none')} description={t('scenes.noneHint')} />
: (
<ul className="grid gap-3 md:grid-cols-2 xl:grid-cols-3" data-testid="scenes">
{scenes.map(s => (
<li key={s.id} data-testid="scene" data-name={s.name} data-active={s.active}
className={cx('rounded-card border bg-surface shadow-raised p-card grid gap-3', s.active ? 'border-accent ring-2 ring-accent' : 'border-line')}>
<div className="flex items-start gap-3">
{/* a scene's colour is the venue's choice (data) */}
<span className="mt-1 w-3 h-3 rounded-full shrink-0 bg-ink-3" style={s.color ? { background: s.color } : undefined} aria-hidden="true" />
<span className="flex-1 min-w-0 grid gap-0.5">
<span className="text-body-lg font-semibold text-ink truncate">{s.name}</span>
{s.description && <span className="text-label text-ink-2">{s.description}</span>}
</span>
<Switch checked={s.active} aria-label={t('scenes.on')} data-testid="scene-switch"
onChange={on => act(() => api.setSceneActive(s.id, on, on ? untilOf(forOf[s.id]) : null), t(on ? 'scenes.turnedOn' : 'scenes.turnedOff', { name: s.name }))} />
</div>
<div className="flex flex-wrap items-center gap-2">
{s.active
? <span className="text-label text-success-ink font-medium flex-1">{s.until ? t('scenes.onUntil', { time: formatDateTime(s.until, 'datetimeShort') }) : t('scenes.onNow')}</span>
: <Dropdown size="sm" className="flex-1 min-w-40" value={forOf[s.id] ?? ''} onChange={v => setForOf(f => ({ ...f, [s.id]: v }))} aria-label={t('scenes.for')}
options={FOR.map(k => ({ value: k, label: t(`scenes.forOptions.${k || 'off'}`) }))} />}
<IconButton size="sm" tone="accent" label={t('scenes.edit')} onClick={() => setEditing(s)}><Pencil size={16} /></IconButton>
<IconButton size="sm" tone="danger" label={t('scenes.delete')} onClick={() => setRemoving(s)}><Trash2 size={16} /></IconButton>
</div>
</li>
))}
</ul>
)}
{editing && <SceneDialog scene={editing} onClose={() => setEditing(null)}
onSave={body => act(() => (editing.id ? api.updateScene(editing.id, body) : api.createScene(body)), t('scenes.saved')).then(ok => ok && setEditing(null))} />}
{removing && (
<Dialog open size="sm" title={t('scenes.deleteTitle', { name: removing.name })} onClose={() => setRemoving(null)}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('fees.cancel')}</Button>
<Button variant="danger" data-testid="scene-delete-confirm"
onClick={() => act(() => api.deleteScene(removing.id), t('scenes.deleted')).then(() => setRemoving(null))}>{t('scenes.delete')}</Button>
</>}>
<p className="text-body text-ink-2">{t('scenes.deleteBody')}</p>
</Dialog>
)}
</Page>
)
}
function SceneDialog({ scene, onClose, onSave }) {
const { t } = useTranslation('manager')
const [name, setName] = useState(scene.name ?? '')
const [description, setDescription] = useState(scene.description ?? '')
const [color, setColor] = useState(scene.color ?? CATEGORY_COLOURS[0])
const [busy, setBusy] = useState(false)
return (
<Dialog open size="sm" title={scene.id ? t('scenes.edit') : t('scenes.new')} onClose={onClose}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>
<Button disabled={!name.trim()} loading={busy} data-testid="scene-save"
onClick={async () => { setBusy(true); await onSave({ name: name.trim(), description: description.trim() || null, color }); setBusy(false) }}>{t('fees.save')}</Button>
</>}>
<div className="grid gap-3">
<Field label={t('scenes.name')}><Input value={name} maxLength={60} autoFocus onChange={e => setName(e.target.value)} placeholder={t('scenes.namePh')} data-testid="scene-name" /></Field>
<Field label={t('scenes.description')}><Input value={description} maxLength={200} onChange={e => setDescription(e.target.value)} placeholder={t('scenes.descriptionPh')} /></Field>
<div className="grid gap-2">
<span className="text-label font-medium text-ink-2">{t('scenes.colour')}</span>
<div className="flex flex-wrap gap-2" role="radiogroup" aria-label={t('scenes.colour')}>
{CATEGORY_COLOURS.map(c => (
<button key={c} type="button" role="radio" aria-checked={color === c} aria-label={c} onClick={() => setColor(c)}
className={cx('w-8 h-8 rounded-full ring-offset-2 ring-offset-[var(--x-surface)]', color === c && 'ring-2 ring-[var(--x-ink)]')} style={{ background: c }} />
))}
</div>
</div>
</div>
</Dialog>
)
}
@@ -0,0 +1,21 @@
// Scenes (owner 2026-11-21): backend local_backend/routers/scenes.py.
import client from '../../api/client'
const data = r => r.data
export const SCENE_EVENTS = ['scenes.changed']
export const listScenes = () => client.get('/api/scenes').then(data)
export const createScene = body => client.post('/api/scenes', body).then(data)
export const updateScene = (id, body) => client.put(`/api/scenes/${id}`, body).then(data)
export const deleteScene = id => client.delete(`/api/scenes/${id}`)
export const setSceneActive = (id, active, until = null) => client.put(`/api/scenes/${id}/active`, { active, until }).then(data)
// how long a scene stays on when turned on: until turned off, or for a while
export const FOR = ['', '1', '2', '3', '4', '6', 'day']
/** The moment a scene turned on now goes off ("day": the end of today on this device's clock). */
export function untilOf(choice, now = new Date()) {
if (!choice) return null
if (choice === 'day') { const d = new Date(now); d.setHours(23, 59, 0, 0); return d.toISOString() }
return new Date(now.getTime() + Number(choice) * 3600_000).toISOString()
}
@@ -1,20 +1,43 @@
// One playlist (plan step 5.6a): its name, orientation and default transition; the timeline of
// slides (drag or arrows to reorder, duplicate, remove, on / off); a slide's settings with a live
// preview at the playlist's shape; new slides blank or from a template; a warning on slides whose
// picture or video doesn't fit the orientation.
import { useCallback, useEffect, useMemo, useState } from 'react'
// One playlist (plan step 5.6a; reworked 2026-11-21): its name, orientation and default transition
// (the toolbar); a horizontal timeline of slides, like a video editor's (cards of one size that
// scroll sideways: drag or ← → to reorder, duplicate, remove); under it the picked slide's basics
// (name, seconds, on / off, transition, when it shows) beside its live preview, the same height;
// then what the slide shows. New slides blank or from a template; a warning on slides whose
// picture or video doesn't fit the orientation. A slide's "when it shows" narrows its playlist's
// schedule: outside both, it doesn't play.
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import toast from 'react-hot-toast'
import { AlertTriangle, ArrowDown, ArrowUp, Copy, Film, GripVertical, ImageIcon, LayoutList, Plus, Trash2, Type } from 'lucide-react'
import { AlertTriangle, ArrowLeft, ArrowRight, Copy, Film, ImageIcon, LayoutList, Plus, Trash2, Type } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Select, Spinner } from '@xenia/ui'
import * as api from './signageApi'
import { mediaEntry, mediaLookup, misfits, moved, slideBody, slideFromTemplate, TEMPLATES, totalSeconds, TRANSITIONS, windowParts } from './signageLogic'
import SlideEditor from './SlideEditor'
import SlideEditor, { SlideBasics } from './SlideEditor'
import SlidePreview from './SlidePreview'
const KIND_ICON = { image: ImageIcon, video: Film, text: Type, menu: LayoutList }
/** The preview as big as its box allows (the box is as tall as the basics beside it). */
function FitPreview({ orientation, children }) {
const box = useRef(null)
const [size, setSize] = useState({ w: 0, h: 0 })
useLayoutEffect(() => {
const el = box.current
if (!el) return undefined
const ro = new ResizeObserver(([e]) => setSize({ w: e.contentRect.width, h: e.contentRect.height }))
ro.observe(el)
return () => ro.disconnect()
}, [])
const ratio = orientation === 'portrait' ? 9 / 16 : 16 / 9
const width = Math.max(0, Math.min(size.w, size.h * ratio))
return (
<div ref={box} className="h-full min-h-[16rem] grid place-items-center" data-testid="signage-preview-box">
{width > 0 && <div style={{ width }}>{children}</div>}
</div>
)
}
export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
const { t } = useTranslation('manager')
const [pl, setPl] = useState(null)
@@ -109,10 +132,9 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
{pl.screens.length > 0 && <> · {t('signage.playingOn', { names: pl.screens.map(s => s.name).join(', ') })}</>}
</p>
<div className="grid gap-4 lg:grid-cols-[minmax(16rem,22rem)_1fr]">
{/* the timeline */}
<section className="grid gap-2 content-start" aria-label={t('signage.timeline')}>
<ol className="grid gap-2" data-testid="signage-timeline">
{/* the timeline: cards of one size, scrolling sideways (2026-11-21) */}
<section className="rounded-card border border-line bg-surface-2 p-3" aria-label={t('signage.timeline')}>
<ol className="flex gap-3 overflow-x-auto pb-2 snap-x" data-testid="signage-timeline">
{pl.slides.map((s, i) => {
const Icon = KIND_ICON[s.kind] || ImageIcon
const parts = windowParts(s)
@@ -120,60 +142,66 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
<li key={s.id} draggable onDragStart={() => setDragFrom(i)} onDragOver={e => e.preventDefault()}
onDrop={() => { if (dragFrom != null) reorder(dragFrom, i); setDragFrom(null) }}
data-testid="signage-slide-card" data-id={s.id} data-kind={s.kind}
className={`rounded-card border bg-surface flex gap-2 p-2 items-center cursor-pointer transition-colors duration-fast
className={`w-52 shrink-0 snap-start rounded-card border bg-surface grid gap-2 p-2 cursor-pointer transition-colors duration-fast
${s.id === selected ? 'border-accent ring-2 ring-accent' : 'border-line hover:border-line-strong'} ${s.enabled ? '' : 'opacity-60'}`}
onClick={() => pick(s)}>
<GripVertical size={16} className="text-ink-3 shrink-0 cursor-grab" aria-hidden="true" />
<div className="w-24 shrink-0 pointer-events-none">
<div className="pointer-events-none h-28 grid place-items-center rounded-control bg-surface-2">
<div style={{ width: pl.orientation === 'portrait' ? 63 : '100%' }}>
<SlidePreview slide={s} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} testid="signage-card-preview" />
</div>
<div className="grid gap-0.5 min-w-0 flex-1">
</div>
<div className="grid gap-0.5 min-w-0">
<span className="text-label font-medium text-ink truncate flex items-center gap-1.5">
<Icon size={14} className="text-ink-2 shrink-0" aria-hidden="true" />{s.name || t(`signage.kinds.${s.kind}`)}
{bad[s.id] && <AlertTriangle size={14} className="text-warning-ink" aria-label={t('signage.misfit')} data-testid="signage-card-misfit" />}
<span className="text-caption text-ink-3 tabular-nums">{i + 1}</span>
<Icon size={14} className="text-ink-2 shrink-0" aria-hidden="true" />
<span className="truncate">{s.name || t(`signage.kinds.${s.kind}`)}</span>
{bad[s.id] && <AlertTriangle size={14} className="text-warning-ink shrink-0" aria-label={t('signage.misfit')} data-testid="signage-card-misfit" />}
</span>
<span className="text-caption text-ink-3">
<span className="text-caption text-ink-3 truncate">
{s.kind === 'video' && s.video_to_end ? t('signage.toTheEnd') : t('signage.seconds', { count: s.duration_s })}
{!s.enabled && <> · {t('signage.off')}</>}
{parts.map(p => <span key={p.key}> · {p.key === 'days' ? p.params.days.map(d => t(`signage.weekdays.${d}`)).join(' ') : t(`signage.window.${p.key}`, p.params)}</span>)}
</span>
</div>
<div className="flex flex-col" onClick={e => e.stopPropagation()}>
<IconButton size="sm" variant="ghost" label={t('display.earlier')} disabled={i === 0 || busy} onClick={() => reorder(i, i - 1)} data-testid="signage-up"><ArrowUp size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('display.later')} disabled={i === pl.slides.length - 1 || busy} onClick={() => reorder(i, i + 1)} data-testid="signage-down"><ArrowDown size={14} /></IconButton>
</div>
<div className="flex flex-col" onClick={e => e.stopPropagation()}>
<IconButton size="sm" variant="ghost" label={t('signage.duplicateSlide')} disabled={busy}
onClick={() => run(() => api.duplicateSlide(s.id), t('signage.duplicated'))}><Copy size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('fees.delete')} disabled={busy} data-testid="signage-slide-delete"
onClick={() => window.confirm(t('signage.deleteSlide')) && run(() => api.deleteSlide(s.id), t('signage.removed'), s.id === selected ? null : selected)}><Trash2 size={14} /></IconButton>
<div className="grid grid-cols-4 gap-1" onClick={e => e.stopPropagation()}>
<IconButton size="sm" tone="accent" className="!w-full" label={t('display.earlier')} disabled={i === 0 || busy} onClick={() => reorder(i, i - 1)} data-testid="signage-up"><ArrowLeft size={16} /></IconButton>
<IconButton size="sm" tone="accent" className="!w-full" label={t('display.later')} disabled={i === pl.slides.length - 1 || busy} onClick={() => reorder(i, i + 1)} data-testid="signage-down"><ArrowRight size={16} /></IconButton>
<IconButton size="sm" tone="info" className="!w-full" label={t('signage.duplicateSlide')} disabled={busy}
onClick={() => run(() => api.duplicateSlide(s.id), t('signage.duplicated'))}><Copy size={16} /></IconButton>
<IconButton size="sm" tone="danger" className="!w-full" label={t('fees.delete')} disabled={busy} data-testid="signage-slide-delete"
onClick={() => window.confirm(t('signage.deleteSlide')) && run(() => api.deleteSlide(s.id), t('signage.removed'), s.id === selected ? null : selected)}><Trash2 size={16} /></IconButton>
</div>
</li>
)
})}
<li className="w-52 shrink-0 snap-start">
<button type="button" onClick={() => setAdding(true)} data-testid="signage-add-slide"
className="w-full h-full min-h-[12rem] rounded-card border-2 border-dashed border-line-strong text-ink-2 hover:text-accent-ink hover:border-accent grid place-items-center gap-1 text-label font-medium transition-colors duration-fast">
<span className="grid justify-items-center gap-1"><Plus size={20} aria-hidden="true" />{t('signage.addSlide')}</span>
</button>
</li>
</ol>
<Button variant="secondary" icon={<Plus size={16} />} onClick={() => setAdding(true)} data-testid="signage-add-slide">{t('signage.addSlide')}</Button>
</section>
{/* the slide being edited */}
<section className="grid gap-4 content-start">
{/* the picked slide: its basics beside its preview (one height), then what it shows */}
{draft ? <>
{/* the preview stays in view while the settings below scroll */}
<div className="sticky top-0 z-10 bg-canvas pb-2">
<SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} playing
className={pl.orientation === 'portrait' ? 'max-w-[13rem] mx-auto w-full' : 'w-full max-w-2xl mx-auto'} />
</div>
<section className="grid gap-4 lg:grid-cols-2 items-stretch rounded-card border border-line bg-surface shadow-raised p-card" data-testid="signage-slide-top">
<SlideBasics slide={draft} onChange={setDraft} />
<FitPreview orientation={pl.orientation}>
<SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} playing />
</FitPreview>
</section>
<section className="rounded-card border border-line bg-surface shadow-raised p-card">
<SlideEditor slide={draft} onChange={setDraft} media={media} onMedia={item => setMedia(m => ({ ...m, [String(item.id)]: mediaEntry(item) }))}
misfit={draftBad} />
<div className="flex gap-2 items-center sticky bottom-0 bg-canvas py-2">
</section>
<div className="flex gap-2 items-center sticky bottom-0 bg-canvas py-2 z-10">
<Button loading={busy} disabled={!dirty} onClick={() => run(() => api.updateSlide(draft.id, slideBody(draft)), t('settings.saved'))}
data-testid="signage-slide-save">{t('fees.save')}</Button>
<Button variant="secondary" disabled={!dirty || busy} onClick={() => setDraft(structuredClone(saved))}>{t('signage.undo')}</Button>
{dirty && <span className="text-label text-ink-3">{t('display.looks.unsaved')}</span>}
</div>
</> : <p className="text-body text-ink-3 p-6 text-center">{t(pl.slides.length ? 'signage.pickSlide' : 'signage.noSlides')}</p>}
</section>
</div>
{adding && (
<Dialog open size="lg" title={t('signage.addSlide')} onClose={() => setAdding(false)}
@@ -1,136 +1,137 @@
// Signage → Schedules (plan step 5.6c): which playlist plays when. A schedule is lines (a playlist
// on some days, between some hours, between some dates, with a priority) and a playlist for the rest
// of the time. When two lines match, the higher priority wins, then the more specific (dates, then
// days, then hours). A TV with a schedule switches by itself, also while the server is down.
// Signage → Schedules (plan step 5.6c; lines with their screens, owner 2026-11-21): which playlist
// plays when, on which screens. Each line: a playlist, its screens (none picked = every screen), a
// priority; its days (with shortcuts), smart days (1st / last of the month, first / last week,
// public holidays or not), hours that may pass midnight, dates, and optionally a scene it plays in
// (party mode). When two lines match on a screen, the higher priority wins, then the more specific
// one; no line → the screen's default playlist (Screens). Saved together; the TVs switch by
// themselves, also while the server is down.
import { useCallback, useEffect, useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { MONTH_DAYS } from '@xenia/signage'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner } from '@xenia/ui'
import { Button, Dropdown, EmptyState, Field, FilterChip, IconButton, InfoTip, Input, Spinner, Switch } from '@xenia/ui'
import * as api from './signageApi'
import { listScenes } from '../scenes/scenesApi'
const emptyEntry = playlistId => ({ playlist_id: playlistId, days: [], time_from: null, time_to: null, date_from: null, date_to: null, priority: 0 })
const DAYS = [0, 1, 2, 3, 4, 5, 6]
const SHORTCUTS = { everyday: [], weekdays: [0, 1, 2, 3, 4], weekend: [5, 6] }
const KEYS = ['id', 'name', 'playlist_id', 'screen_ids', 'priority', 'enabled', 'days', 'month_days', 'time_from', 'time_to', 'date_from', 'date_to', 'scene_id']
const bodyOf = lines => lines.map(l => Object.fromEntries(KEYS.map(k => [k, l[k] ?? (k === 'screen_ids' || k === 'days' || k === 'month_days' ? [] : null)])))
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
export default function SchedulesTab() {
const { t } = useTranslation('manager')
const [list, setList] = useState(null)
const [saved, setSaved] = useState(null)
const [lines, setLines] = useState(null)
const [playlists, setPlaylists] = useState([])
const [current, setCurrent] = useState(null)
const [draft, setDraft] = useState(null)
const [screens, setScreens] = useState([])
const [scenes, setScenes] = useState([])
const [busy, setBusy] = useState(false)
const [confirm, setConfirm] = useState(false)
const load = useCallback(async (pick) => {
const load = useCallback(async () => {
try {
const [l, p] = await Promise.all([api.listSchedules(), api.listPlaylists()])
setList(l); setPlaylists(p)
const s = l.find(x => x.id === pick) || (pick === undefined ? l[0] : null)
setCurrent(s?.id ?? null)
setDraft(s ? { name: s.name, fallback_playlist_id: s.fallback_playlist_id, entries: s.entries } : null)
const [l, p, s, sc] = await Promise.all([api.listSchedules(), api.listPlaylists(), api.listScreens(), listScenes().catch(() => [])])
setSaved(l); setLines(l); setPlaylists(p); setScreens(s); setScenes(sc)
} catch (err) { toast.error(errorMessage(err, t)) }
}, [t])
useEffect(() => { load() }, [load])
const saved = list?.find(x => x.id === current)
const dirty = useMemo(() => !!(saved && draft && JSON.stringify({ name: saved.name, fallback_playlist_id: saved.fallback_playlist_id, entries: saved.entries }) !== JSON.stringify(draft)), [saved, draft])
if (!list) return <div className="flex justify-center p-6"><Spinner /></div>
const dirty = useMemo(() => !!(saved && lines && !same(bodyOf(saved), bodyOf(lines))), [saved, lines])
if (!lines) return <div className="flex justify-center p-6"><Spinner /></div>
const act = async (fn, done, pick = current) => {
const set = (i, patch) => setLines(ls => ls.map((l, j) => (j === i ? { ...l, ...patch } : l)))
const add = () => setLines(ls => [...ls, { playlist_id: playlists[0]?.id, screen_ids: [], priority: 0, enabled: true, days: [], month_days: [], scene_id: null }])
const save = async () => {
setBusy(true)
try { const r = await fn(); toast.success(done); await load(r?.id ?? pick) } catch (err) { toast.error(errorMessage(err, t)) }
try { const l = await api.saveSchedules(bodyOf(lines)); setSaved(l); setLines(l); toast.success(t('settings.saved')) }
catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
const plOptions = playlists.map(p => ({ value: String(p.id), label: p.name }))
const setEntry = (i, patch) => setDraft(d => ({ ...d, entries: d.entries.map((e, j) => (j === i ? { ...e, ...patch } : e)) }))
const toggleDay = (i, day) => setEntry(i, { days: draft.entries[i].days.includes(day) ? draft.entries[i].days.filter(x => x !== day) : [...draft.entries[i].days, day].sort() })
return (
<div className="grid gap-5 xl:grid-cols-[14rem_1fr]" data-testid="signage-schedules">
<nav className="grid gap-2 content-start">
<ul className="grid gap-1.5">
{list.map(s => (
<li key={s.id}>
<button type="button" onClick={() => { if (!dirty || window.confirm(t('signage.discard'))) load(s.id) }} aria-current={s.id === current ? 'true' : undefined}
data-testid="signage-schedule-item" data-name={s.name}
className={`w-full text-left px-3 py-2 rounded-control border transition-colors duration-fast grid
${s.id === current ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface hover:bg-surface-2 text-ink'}`}>
<span className="text-label font-medium truncate">{s.name}</span>
<span className="text-caption text-ink-3 truncate">{s.playing_now ? t('signage.schedules.nowPlaying', { name: s.playing_now.name }) : t('signage.schedules.nowNothing')}</span>
</button>
</li>
))}
</ul>
<Button variant="secondary" icon={<Plus size={16} />} disabled={!playlists.length || busy} data-testid="signage-new-schedule"
onClick={() => act(() => api.createSchedule({ name: t('signage.schedules.newName'), fallback_playlist_id: playlists[0]?.id ?? null, entries: [] }), t('signage.schedules.created'))}>
{t('signage.schedules.new')}</Button>
{!playlists.length && <p className="text-caption text-ink-3">{t('signage.schedules.needPlaylist')}</p>}
</nav>
{!draft ? <EmptyState title={t('signage.schedules.none')} description={t('signage.schedules.noneHint')} /> : (
<div className="grid gap-4 content-start" data-testid="signage-schedule-editor" data-id={current}>
<div className="flex flex-wrap items-end gap-2">
<Field label={t('signage.playlistName')} className="flex-1 min-w-[12rem]">
<Input value={draft.name} maxLength={80} onChange={e => setDraft(d => ({ ...d, name: e.target.value }))} data-testid="signage-schedule-name" />
</Field>
<IconButton variant="ghost" label={t('fees.delete')} onClick={() => setConfirm(true)} data-testid="signage-schedule-delete"><Trash2 size={16} /></IconButton>
</div>
<p className="text-caption text-ink-3">{t('signage.schedules.how')}</p>
<div className="grid gap-4" data-testid="signage-schedules">
<p className="text-label text-ink-2 max-w-4xl">{t('signage.schedules.how')}</p>
{!playlists.length && <p className="text-label text-warning-ink">{t('signage.schedules.needPlaylist')}</p>}
{lines.length === 0 && <EmptyState title={t('signage.schedules.none')} description={t('signage.schedules.noneHint')} />}
<ol className="grid gap-3" data-testid="signage-schedule-entries">
{draft.entries.map((e, i) => (
<li key={i} className="rounded-card border border-line bg-surface p-3 grid gap-3" data-testid="signage-schedule-entry">
<div className="flex flex-wrap items-end gap-2">
<Field label={t('signage.schedules.plays')} className="flex-1 min-w-[10rem]">
<Select value={String(e.playlist_id)} onChange={ev => setEntry(i, { playlist_id: Number(ev.target.value) })} options={plOptions} data-testid="signage-entry-playlist" />
</Field>
<Field label={t('signage.schedules.priority')} hint={t('signage.schedules.priorityHint')}>
<Input inputMode="numeric" className="w-24" value={String(e.priority || 0)}
onChange={ev => setEntry(i, { priority: Math.min(100, Number(ev.target.value.replace(/\D/g, '')) || 0) })} data-testid="signage-entry-priority" />
</Field>
<IconButton variant="ghost" label={t('fees.delete')} onClick={() => setDraft(d => ({ ...d, entries: d.entries.filter((_, j) => j !== i) }))}><Trash2 size={16} /></IconButton>
</div>
<div className="flex flex-wrap gap-1.5" role="group" aria-label={t('signage.days')}>
{[0, 1, 2, 3, 4, 5, 6].map(d => (
<button key={d} type="button" aria-pressed={e.days.includes(d)} onClick={() => toggleDay(i, d)} data-testid={`signage-entry-day-${d}`}
className={`px-2.5 py-1 rounded-control border text-label transition-colors duration-fast
${e.days.includes(d) ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface-2 text-ink hover:bg-surface-3'}`}>
{t(`signage.weekdays.${d}`)}
</button>
))}
</div>
<div className="grid gap-3 grid-cols-2 lg:grid-cols-4">
<Field label={t('signage.timeFrom')}><Input type="time" value={e.time_from || ''} onChange={ev => setEntry(i, { time_from: ev.target.value || null })} data-testid="signage-entry-from" /></Field>
<Field label={t('signage.timeTo')}><Input type="time" value={e.time_to || ''} onChange={ev => setEntry(i, { time_to: ev.target.value || null })} data-testid="signage-entry-to" /></Field>
<Field label={t('signage.dateFrom')}><Input type="date" value={e.date_from || ''} onChange={ev => setEntry(i, { date_from: ev.target.value || null })} /></Field>
<Field label={t('signage.dateTo')}><Input type="date" value={e.date_to || ''} onChange={ev => setEntry(i, { date_to: ev.target.value || null })} /></Field>
</div>
</li>
{lines.map((l, i) => (
<Line key={l.id ?? `new-${i}`} line={l} set={patch => set(i, patch)} playlists={playlists} screens={screens} scenes={scenes}
onRemove={() => setLines(ls => ls.filter((_, j) => j !== i))} />
))}
</ol>
<Button variant="secondary" icon={<Plus size={16} />} onClick={() => setDraft(d => ({ ...d, entries: [...d.entries, emptyEntry(playlists[0]?.id)] }))}
disabled={!playlists.length || draft.entries.length >= 100} data-testid="signage-add-entry">{t('signage.schedules.addLine')}</Button>
<Field label={t('signage.schedules.otherwise')} hint={t('signage.schedules.otherwiseHint')}>
<Select value={draft.fallback_playlist_id == null ? '' : String(draft.fallback_playlist_id)} data-testid="signage-schedule-fallback"
onChange={e => setDraft(d => ({ ...d, fallback_playlist_id: e.target.value ? Number(e.target.value) : null }))}
options={[{ value: '', label: t('signage.screens.nothing') }, ...plOptions]} />
</Field>
{saved?.screens?.length > 0 && <p className="text-label text-ink-3">{t('signage.playingOn', { names: saved.screens.map(s => s.name).join(', ') })}</p>}
<div className="flex gap-2 items-center">
<Button loading={busy} disabled={!dirty || !draft.name.trim()} data-testid="signage-schedule-save"
onClick={() => act(() => api.updateSchedule(current, { ...draft, name: draft.name.trim() }), t('settings.saved'))}>{t('fees.save')}</Button>
<div className="flex flex-wrap items-center gap-2">
<Button variant="secondary" icon={<Plus size={16} />} onClick={add} disabled={!playlists.length || lines.length >= 200} data-testid="signage-add-entry">{t('signage.schedules.addLine')}</Button>
<span className="flex-1" />
{dirty && <span className="text-label text-ink-3">{t('display.looks.unsaved')}</span>}
<Button variant="secondary" disabled={!dirty || busy} onClick={() => setLines(saved)}>{t('signage.undo')}</Button>
<Button loading={busy} disabled={!dirty} onClick={save} data-testid="signage-schedule-save">{t('fees.save')}</Button>
</div>
</div>
)}
{confirm && saved && (
<Dialog open size="sm" title={t('signage.schedules.deleteTitle', { name: saved.name })} onClose={() => setConfirm(false)}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(false)}>{t('fees.cancel')}</Button>
<Button variant="danger" loading={busy} onClick={() => act(() => api.deleteSchedule(current), t('signage.schedules.deleted'), undefined).then(() => setConfirm(false))}>{t('fees.delete')}</Button>
</>}>
<p className="text-body text-ink-2">{t('signage.schedules.deleteBody')}</p>
</Dialog>
)}
)
}
function Line({ line: l, set, playlists, screens, scenes, onRemove }) {
const { t } = useTranslation('manager')
const days = l.days || []
const md = l.month_days || []
const shortcut = Object.entries(SHORTCUTS).find(([, v]) => same(v, days))?.[0]
return (
<li className={`rounded-card border border-line bg-surface shadow-raised p-card grid gap-4 ${l.enabled ? '' : 'opacity-70'}`} data-testid="signage-schedule-entry">
{/* playlist · screens · priority · delete: one height, one line (2026-11-21) */}
<div className="grid gap-3 items-end sm:grid-cols-[1fr_1fr_1fr_auto]">
<Field label={t('signage.schedules.plays')}>
<Dropdown value={l.playlist_id} onChange={v => set({ playlist_id: Number(v) })} data-testid="signage-entry-playlist"
options={playlists.map(p => ({ value: p.id, label: p.name, hint: t(`signage.orientations.${p.orientation}`) }))} />
</Field>
<Field label={t('signage.schedules.onScreens')}>
<Dropdown multiple value={l.screen_ids || []} onChange={v => set({ screen_ids: v.map(Number) })} allLabel={t('signage.schedules.allScreens')}
data-testid="signage-entry-screens" options={screens.map(s => ({ value: s.id, label: s.name }))} />
</Field>
<Field label={<span className="inline-flex items-center gap-1">{t('signage.schedules.priority')}<InfoTip>{t('signage.schedules.priorityHint')}</InfoTip></span>}>
<Input inputMode="numeric" value={String(l.priority || 0)} data-testid="signage-entry-priority"
onChange={ev => set({ priority: Math.min(100, Number(ev.target.value.replace(/\D/g, '')) || 0) })} />
</Field>
<IconButton tone="danger" label={t('fees.delete')} onClick={onRemove} data-testid="signage-entry-delete"><Trash2 size={16} /></IconButton>
</div>
<div className="grid gap-2">
<span className="text-label font-medium text-ink-2">{t('signage.days')}</span>
<div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t('signage.days')}>
{DAYS.map(d => (
<FilterChip key={d} size="sm" tone="accent" pressed={days.includes(d)} data-testid={`signage-entry-day-${d}`}
onClick={() => set({ days: days.includes(d) ? days.filter(x => x !== d) : [...days, d].sort() })}>{t(`signage.weekdays.${d}`)}</FilterChip>
))}
<span className="w-px h-6 bg-line mx-1" aria-hidden="true" />
{Object.entries(SHORTCUTS).map(([k, v]) => (
<FilterChip key={k} size="sm" tone="info" pressed={shortcut === k} onClick={() => set({ days: v })} data-testid={`signage-entry-${k}`}>{t(`signage.schedules.shortcuts.${k}`)}</FilterChip>
))}
</div>
<div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t('signage.schedules.smartDays')}>
<span className="text-caption text-ink-3 mr-1">{t('signage.schedules.smartDays')}</span>
{MONTH_DAYS.map(k => (
<FilterChip key={k} size="sm" tone={k === 'not_holiday' ? 'warning' : 'success'} pressed={md.includes(k)} data-testid={`signage-entry-md-${k}`}
onClick={() => set({ month_days: md.includes(k) ? md.filter(x => x !== k) : [...md, k] })}>{t(`signage.schedules.monthDays.${k}`)}</FilterChip>
))}
</div>
</div>
<div className="grid gap-3 grid-cols-2 lg:grid-cols-5 items-end">
<Field label={t('signage.timeFrom')}><Input type="time" value={l.time_from || ''} onChange={ev => set({ time_from: ev.target.value || null })} data-testid="signage-entry-from" /></Field>
<Field label={t('signage.timeTo')}><Input type="time" value={l.time_to || ''} onChange={ev => set({ time_to: ev.target.value || null })} data-testid="signage-entry-to" /></Field>
<Field label={t('signage.dateFrom')}><Input type="date" value={l.date_from || ''} onChange={ev => set({ date_from: ev.target.value || null })} /></Field>
<Field label={t('signage.dateTo')}><Input type="date" value={l.date_to || ''} onChange={ev => set({ date_to: ev.target.value || null })} /></Field>
<Field label={t('signage.schedules.scene')}>
<Dropdown value={l.scene_id ?? ''} onChange={v => set({ scene_id: v === '' ? null : Number(v) })} data-testid="signage-entry-scene"
options={[{ value: '', label: t('signage.schedules.anyScene') }, ...scenes.map(s => ({ value: s.id, label: s.name, dot: s.color || undefined }))]} />
</Field>
</div>
<div className="flex flex-wrap items-center gap-3">
<Switch checked={l.enabled !== false} onChange={v => set({ enabled: v })} label={t('signage.schedules.enabled')} />
<span className="flex-1" />
{l.playing_on?.length > 0 && <span className="text-label text-success-ink" data-testid="signage-entry-playing">{t('signage.schedules.playingNow', { names: l.playing_on.map(s => s.name).join(', ') })}</span>}
</div>
</li>
)
}
@@ -1,24 +1,24 @@
// Signage → Screens (plan step 5.6c): every paired signage TV with what it plays (a playlist, or a
// schedule that wins over it), its shape and how its picture is turned; a warning when a playlist
// was made for the other shape. New TVs are paired in Devices.
// Signage → Screens (plan step 5.6c; 2026-11-21): every paired signage TV with its default playlist,
// its shape and how its picture is turned, and what plays on it now. A schedule line for a screen
// (Schedules) wins over its default while it matches. A warning when a playlist it may play was
// made for the other shape. New TVs are paired in Devices.
import { useCallback, useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { Link } from 'react-router-dom'
import { AlertTriangle, Monitor } from 'lucide-react'
import { AlertTriangle, CalendarClock, Monitor, Smartphone } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { EmptyState, Field, Select, Spinner } from '@xenia/ui'
import { Dropdown, EmptyState, Field, Spinner } from '@xenia/ui'
import * as api from './signageApi'
export default function ScreensTab() {
const { t } = useTranslation('manager')
const [screens, setScreens] = useState(null)
const [playlists, setPlaylists] = useState([])
const [schedules, setSchedules] = useState([])
const load = useCallback(async () => {
try {
const [s, p, c] = await Promise.all([api.listScreens(), api.listPlaylists(), api.listSchedules()])
setScreens(s); setPlaylists(p); setSchedules(c)
const [s, p] = await Promise.all([api.listScreens(), api.listPlaylists()])
setScreens(s); setPlaylists(p)
} catch (err) { toast.error(errorMessage(err, t)) }
}, [t])
useEffect(() => { load() }, [load])
@@ -32,40 +32,44 @@ export default function ScreensTab() {
action={<Link to="/devices?pair=signage" className="text-accent-ink font-medium">{t('signage.screens.pair')}</Link>} />
}
return (
<ul className="grid gap-3" data-testid="signage-screens">
{screens.map(s => (
<li key={s.id} className="rounded-card border border-line bg-surface p-4 grid gap-3" data-testid="signage-screen" data-id={s.id} data-name={s.name}>
<div className="flex items-center gap-2">
<Monitor size={18} className="text-ink-2" aria-hidden="true" />
<span className="text-body font-semibold text-ink flex-1">{s.name}</span>
<div className="grid gap-3">
<p className="text-label text-ink-2 max-w-3xl">{t('signage.screens.intro')}</p>
<ul className="grid gap-3 xl:grid-cols-2" data-testid="signage-screens">
{screens.map(s => {
const Icon = s.orientation === 'portrait' ? Smartphone : Monitor
return (
<li key={s.id} className="rounded-card border border-line bg-surface shadow-raised p-card grid gap-4" data-testid="signage-screen" data-id={s.id} data-name={s.name}>
<div className="flex flex-wrap items-center gap-2">
<Icon size={18} className="text-ink-2" aria-hidden="true" />
<span className="text-body-lg font-semibold text-ink flex-1">{s.name}</span>
{s.orientation_mismatch && (
<span className="text-caption text-warning-ink flex items-center gap-1" data-testid="signage-screen-mismatch">
<AlertTriangle size={14} aria-hidden="true" />{t('signage.screens.mismatch')}
</span>
)}
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<Field label={t('signage.screens.playlist')}>
<Select value={s.playlist_id == null ? '' : String(s.playlist_id)} data-testid="signage-screen-playlist"
onChange={e => save(s.id, { playlist_id: e.target.value ? Number(e.target.value) : null })}
options={[{ value: '', label: t('signage.screens.nothing') }, ...playlists.map(p => ({ value: String(p.id), label: p.name }))]} />
<p className="text-label text-ink-2 flex items-center gap-1.5" data-testid="signage-screen-now">
{s.now?.scheduled && <CalendarClock size={14} className="text-accent-ink" aria-hidden="true" />}
{s.now ? t(s.now.scheduled ? 'signage.screens.nowScheduled' : 'signage.screens.nowDefault', { name: s.now.name }) : t('signage.screens.nowNothing')}
</p>
<div className="grid gap-3 sm:grid-cols-3">
<Field label={t('signage.screens.defaultPlaylist')}>
<Dropdown value={s.playlist_id ?? ''} data-testid="signage-screen-playlist" onChange={v => save(s.id, { playlist_id: v === '' ? null : Number(v) })}
options={[{ value: '', label: t('signage.screens.nothing') }, ...playlists.map(p => ({ value: p.id, label: p.name }))]} />
</Field>
<Field label={t('signage.screens.schedule')} hint={t('signage.screens.scheduleHint')}>
<Select value={s.schedule_id == null ? '' : String(s.schedule_id)} data-testid="signage-screen-schedule"
onChange={e => save(s.id, { schedule_id: e.target.value ? Number(e.target.value) : null })}
options={[{ value: '', label: t('signage.screens.noSchedule') }, ...schedules.map(c => ({ value: String(c.id), label: c.name }))]} />
</Field>
<Field label={t('signage.orientation')}>
<Select value={s.orientation} onChange={e => save(s.id, { orientation: e.target.value })} data-testid="signage-screen-orientation"
<Field label={t('signage.screens.shape')}>
<Dropdown value={s.orientation} onChange={v => save(s.id, { orientation: v })} data-testid="signage-screen-orientation"
options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) }))} />
</Field>
<Field label={t('signage.screens.rotation')} hint={t('signage.screens.rotationHint')}>
<Select value={String(s.rotation)} onChange={e => save(s.id, { rotation: Number(e.target.value) })} data-testid="signage-screen-rotation"
options={[0, 90, 180, 270].map(r => ({ value: String(r), label: t(`signage.screens.rotations.${r}`) }))} />
<Field label={t('signage.screens.rotation')}>
<Dropdown value={s.rotation} onChange={v => save(s.id, { rotation: Number(v) })} data-testid="signage-screen-rotation"
options={[0, 90, 180, 270].map(r => ({ value: r, label: t(`signage.screens.rotations.${r}`) }))} />
</Field>
</div>
</li>
))}
)
})}
</ul>
</div>
)
}
@@ -1,27 +1,32 @@
// Signage (plan steps 5.6a-c): the venue's playlists for its TVs (pick one to edit its timeline and
// slides; make a new one for a landscape or a portrait screen), which screen plays what, the
// schedules, the message of the day and the weather's town: one tab each.
// Signage (plan steps 5.6a-c; 2026-11-21): the screens (each one's default playlist, shape and
// turn), the playlists (pick one to edit its timeline and slides; make a new one for a landscape or
// a portrait screen), the schedules (which playlist plays when on which screens, scenes), the
// slides library (single slides to reuse, coming next), the message of the day and the weather's
// town: one tab each, in that order; the tab is in the address (?tab=).
// Backend: /api/signage (routers/signage.py).
import { useCallback, useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import toast from 'react-hot-toast'
import { Monitor, Plus, Smartphone } from 'lucide-react'
import { Layers, Monitor, Plus, Smartphone } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, Page, Select, Spinner } from '@xenia/ui'
import { Button, Dialog, EmptyState, Field, Input, Page, PageHeader, Select, Spinner, Tabs } from '@xenia/ui'
import * as api from './signageApi'
import PlaylistEditor from './PlaylistEditor'
import SchedulesTab from './SchedulesTab'
import ScreensTab from './ScreensTab'
import SignageSettingsTab from './SignageSettingsTab'
const TABS = ['playlists', 'screens', 'schedules', 'settings']
const TABS = ['screens', 'playlists', 'schedules', 'slides', 'settings']
export default function SignagePage() {
const { t } = useTranslation('manager')
const [list, setList] = useState(null)
const [current, setCurrent] = useState(null)
const [creating, setCreating] = useState(false)
const [tab, setTab] = useState('playlists')
const [params, setParams] = useSearchParams()
const tab = TABS.includes(params.get('tab')) ? params.get('tab') : 'screens'
const setTab = v => setParams(p => { const n = new URLSearchParams(p); n.set('tab', v); return n }, { replace: true })
const load = useCallback(async () => {
try { const l = await api.listPlaylists(); setList(l); return l } catch (err) { toast.error(errorMessage(err, t)); return null }
@@ -29,21 +34,11 @@ export default function SignagePage() {
useEffect(() => { load().then(l => { if (l?.length) setCurrent(c => c ?? l[0].id) }) }, [load])
return (
<Page testId="signage-page">
<header className="grid gap-1">
<h1 className="text-heading font-semibold text-ink">{t('signage.pageTitle')}</h1>
<p className="text-body text-ink-2 max-w-3xl">{t('signage.intro')}</p>
</header>
<div className="flex flex-wrap gap-1 border-b border-line" role="tablist" aria-label={t('signage.pageTitle')}>
{TABS.map(k => (
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`signage-tab-${k}`}
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast
${tab === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
{t(`signage.tabs.${k}`)}
</button>
))}
</div>
<Page testId="signage-page" header={<PageHeader title={t('signage.pageTitle')} subtitle={t('signage.intro')} />}
top={<Tabs size="lg" value={tab} onChange={setTab} aria-label={t('signage.pageTitle')}
tabs={TABS.map(k => ({ id: k, label: t(`signage.tabs.${k}`), testId: `signage-tab-${k}` }))} />}>
{tab === 'screens' && <ScreensTab />}
{tab === 'slides' && <EmptyState icon={<Layers size={28} />} title={t('signage.slidesTab.title')} description={t('signage.slidesTab.body')} />}
{tab === 'schedules' && <SchedulesTab />}
{tab === 'settings' && <SignageSettingsTab />}
{tab !== 'playlists' ? null : !list ? <div className="flex justify-center p-6"><Spinner /></div> : (
@@ -1,29 +1,37 @@
// One slide's settings (plan step 5.6a): its name, time on screen, transition, on / off, when it
// may show (days, hours, dates), and what it shows (picture, video, text, menu board's look).
// The parent keeps the draft and saves it; the preview follows every change.
// 2026-11-21: in two parts: SlideBasics (beside the preview) and SlideEditor (what it shows, below).
import { useTranslation } from '@xenia/i18n'
import { Field, Input, Select, Switch, Textarea } from '@xenia/ui'
import { Dropdown, Field, FilterChip, Input, Select, Switch, Textarea } from '@xenia/ui'
import { FONT_KEYS, TRANSITIONS } from './signageLogic'
import { BackgroundField, ColourField, MediaPick } from './SignageFields'
import MenuEditor from './MenuEditor'
import WidgetsEditor from './WidgetsEditor'
export default function SlideEditor({ slide, onChange, media, onMedia, misfit = [] }) {
/** The slide's basics, beside its preview: name, seconds on screen, on / off, transition, when it shows. */
export function SlideBasics({ slide, onChange }) {
const { t } = useTranslation('manager')
const set = patch => onChange({ ...slide, ...patch })
const c = slide.content || {}
const setC = patch => set({ content: { ...c, ...patch } })
const days = slide.days || []
const toggleDay = d => set({ days: days.includes(d) ? days.filter(x => x !== d) : [...days, d].sort() })
const bad = id => misfit.includes(id)
return (
<div className="grid gap-5" data-testid="signage-slide-editor" data-kind={slide.kind}>
<div className="grid gap-4 content-start" data-testid="signage-slide-basics">
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('signage.slideName')} hint={t('signage.slideNameHint')}>
<Field label={t('signage.slideName')}>
<Input value={slide.name || ''} maxLength={80} onChange={e => set({ name: e.target.value })} data-testid="signage-slide-name" />
</Field>
<div className="flex items-end pb-1">
{!(slide.kind === 'video' && slide.video_to_end) ? (
<Field label={t('signage.duration')}>
<Input inputMode="numeric" value={String(slide.duration_s ?? 10)} data-testid="signage-duration"
onChange={e => set({ duration_s: Math.min(3600, Number(e.target.value.replace(/\D/g, '')) || 0) })} />
</Field>
) : <span />}
<Field label={t('signage.transition')}>
<Dropdown value={slide.transition || ''} onChange={v => set({ transition: v || null })} data-testid="signage-transition"
options={[{ value: '', label: t('signage.transitionDefault') }, ...TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))]} />
</Field>
<div className="flex items-end pb-2.5">
<Switch checked={!!slide.enabled} onChange={on => set({ enabled: on })} label={t('signage.enabled')} data-testid="signage-slide-enabled" />
</div>
{slide.kind === 'video' && (
@@ -32,16 +40,6 @@ export default function SlideEditor({ slide, onChange, media, onMedia, misfit =
description={t('signage.videoToEndHint')} data-testid="signage-video-to-end" />
</div>
)}
{!(slide.kind === 'video' && slide.video_to_end) && (
<Field label={t('signage.duration')} hint={slide.kind === 'menu' ? t('signage.durationMenuHint') : undefined}>
<Input inputMode="numeric" value={String(slide.duration_s ?? 10)} data-testid="signage-duration"
onChange={e => set({ duration_s: Math.min(3600, Number(e.target.value.replace(/\D/g, '')) || 0) })} />
</Field>
)}
<Field label={t('signage.transition')}>
<Select value={slide.transition || ''} onChange={e => set({ transition: e.target.value || null })} data-testid="signage-transition"
options={[{ value: '', label: t('signage.transitionDefault') }, ...TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))]} />
</Field>
</div>
<fieldset className="grid gap-3 rounded-control border border-line p-3">
@@ -49,11 +47,9 @@ export default function SlideEditor({ slide, onChange, media, onMedia, misfit =
<p className="text-caption text-ink-3">{t('signage.whenHint')}</p>
<div className="flex flex-wrap gap-1.5" role="group" aria-label={t('signage.days')}>
{[0, 1, 2, 3, 4, 5, 6].map(d => (
<button key={d} type="button" aria-pressed={days.includes(d)} onClick={() => toggleDay(d)} data-testid={`signage-day-${d}`}
className={`px-2.5 py-1 rounded-control border text-label transition-colors duration-fast
${days.includes(d) ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface-2 text-ink hover:bg-surface-3'}`}>
<FilterChip key={d} size="sm" tone="accent" pressed={days.includes(d)} onClick={() => toggleDay(d)} data-testid={`signage-day-${d}`}>
{t(`signage.weekdays.${d}`)}
</button>
</FilterChip>
))}
</div>
<div className="grid gap-3 grid-cols-2">
@@ -63,7 +59,20 @@ export default function SlideEditor({ slide, onChange, media, onMedia, misfit =
<Field label={t('signage.dateTo')}><Input type="date" value={slide.date_to || ''} onChange={e => set({ date_to: e.target.value || null })} data-testid="signage-date-to" /></Field>
</div>
</fieldset>
</div>
)
}
/** What the slide shows (below the basics and the preview): picture, video, text, menu board. */
export default function SlideEditor({ slide, onChange, media, onMedia, misfit = [] }) {
const { t } = useTranslation('manager')
const set = patch => onChange({ ...slide, ...patch })
const c = slide.content || {}
const setC = patch => set({ content: { ...c, ...patch } })
const bad = id => misfit.includes(id)
return (
<div className="grid gap-5" data-testid="signage-slide-editor" data-kind={slide.kind}>
{slide.kind === 'image' && (
<div className="grid gap-3">
<MediaPick kind="image" label={t('signage.picture')} value={c.media_id} entry={media[String(c.media_id)]} misfit={bad(c.media_id)}
@@ -22,10 +22,9 @@ export const previewMenu = content => client.post('/api/signage/preview/menu', {
export const listScreens = () => client.get('/api/signage/screens').then(data)
export const updateScreen = (id, body) => client.put(`/api/signage/screens/${id}`, body).then(data)
// the schedule lines (2026-11-21): all of them, saved together
export const listSchedules = () => client.get('/api/signage/schedules').then(data)
export const createSchedule = body => client.post('/api/signage/schedules', body).then(data)
export const updateSchedule = (id, body) => client.put(`/api/signage/schedules/${id}`, body).then(data)
export const deleteSchedule = id => client.delete(`/api/signage/schedules/${id}`)
export const saveSchedules = lines => client.put('/api/signage/schedules', { lines }).then(data)
export const getMessage = () => client.get('/api/signage/message').then(data)
export const putMessage = text => client.put('/api/signage/message', { text }).then(data)
+2 -7
View File
@@ -12,13 +12,7 @@
// converts those routers.
// anyPerm instead of perm: any one of these keys is enough (the media library)
// label a key in the i18n `manager` namespace
import {
LayoutDashboard, LayoutGrid, ShoppingBag,
BookUser, Users, Receipt, CreditCard,
Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes,
BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText,
AppWindow, Settings, CookingPot, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck, Images, Tv,
} from 'lucide-react'
import { Activity, AppWindow, BadgeCheck, BarChart2, BookUser, Boxes, CalendarDays, ConciergeBell, CookingPot, CreditCard, FileText, Images, LayoutDashboard, LayoutGrid, LogIn, MonitorSmartphone, Package, PartyPopper, Percent, Plug, Printer, Receipt, Settings, ShieldCheck, ShoppingBag, ShoppingCart, StickyNote, TableProperties, Tag, Trash2, TrendingUp, Tv, UserCog, Users, Users2 } from 'lucide-react'
const DASH = 'core.dashboard.access'
// The media library: whoever manages something that shows pictures (routers/media.py MANAGE)
@@ -68,6 +62,7 @@ export const NAV = [
{ to: '/management/schedule', icon: CalendarDays, label: 'nav.schedule', module: 'staff_planning', perm: 'core.staff.manage' },
{ to: '/management/prep-zones', icon: CookingPot, label: 'nav.prepZones', module: 'catalog', perm: 'catalog.menu.manage' },
{ to: '/management/pricing', icon: Percent, label: 'nav.pricing', module: 'pricing', perm: 'pricing.manage' },
{ to: '/management/scenes', icon: PartyPopper, label: 'nav.scenes', module: 'core', perm: 'core.scenes.manage' },
{ to: '/notes', icon: StickyNote, label: 'nav.notes', module: 'notes', perm: 'notes.use' },
{ to: '/management/sessions', icon: LogIn, label: 'nav.sessions', module: 'core', perm: 'core.staff.manage' },
],
+7 -1
View File
@@ -187,7 +187,9 @@
"content_invalid": "Μια ρύθμιση της διαφάνειας δεν είναι έγκυρη ({{field}}: {{reason}}).",
"order_mismatch": "Η λίστα άλλαξε στο μεταξύ. Φορτώστε τη ξανά και δοκιμάστε πάλι.",
"weather_offline": "Η υπηρεσία καιρού δεν είναι διαθέσιμη: ο διακομιστής του καταστήματος χρειάζεται internet γι' αυτήν.",
"schedule_unknown": "Το πρόγραμμα {{schedule_id}} δεν βρέθηκε."
"schedule_unknown": "Το πρόγραμμα {{schedule_id}} δεν βρέθηκε.",
"scene_unknown": "Αυτή η σκηνή δεν υπάρχει πια.",
"screen_unknown": "Αυτή η οθόνη δεν υπάρχει πια."
},
"menu_tablet": {
"no_table": "Αυτό το tablet δεν είναι σε τραπέζι, οπότε δεν καλεί σερβιτόρο.",
@@ -358,5 +360,9 @@
"channel_price": {
"not_found": "Η τιμή καναλιού δεν βρέθηκε.",
"set_one_product": "Η σταθερή τιμή είναι για ένα προϊόν: επιλέξτε ένα προϊόν (χωρίς κατηγορίες) ή αλλάξτε την τιμή κατά ποσό ή ποσοστό."
},
"scene": {
"not_found": "Η σκηνή δεν βρέθηκε.",
"until_past": "Αυτή η ώρα έχει περάσει: διαλέξτε μια μεταγενέστερη."
}
}
+80 -12
View File
@@ -49,7 +49,8 @@
"qrCodes": "QR τραπεζιών",
"media": "Πολυμέσα",
"signage": "Προβολή",
"main": "Κύριο μενού"
"main": "Κύριο μενού",
"scenes": "Σκηνές"
},
"profile": {
"edit": "Επεξεργασία προφίλ",
@@ -1346,7 +1347,7 @@
"transition": "Μπαίνει με",
"transitionDefault": "Τη μετάβαση της λίστας",
"when": "Πότε εμφανίζεται",
"whenHint": "Κενό για πάντα. Διαλέξτε μέρες, ώρες (μπορεί να περνούν τα μεσάνυχτα) ή ημερομηνίες για να εμφανίζεται μόνο τότε.",
"whenHint": "Κενό για πάντα. Διαλέξτε ημέρες, ώρες (μπορεί να περνούν τα μεσάνυχτα) ή ημερομηνίες για να εμφανίζεται μόνο τότε. Αυτό στενεύει το πρόγραμμα της λίστας: μια διαφάνεια με ώρα εκτός των ωρών που παίζει η λίστα της δεν εμφανίζεται ποτέ.",
"days": "Μέρες",
"timeFrom": "Από (ώρα)",
"timeTo": "Έως (ώρα)",
@@ -1482,7 +1483,8 @@
"playlists": "Λίστες",
"screens": "Οθόνες",
"schedules": "Προγράμματα",
"settings": "Μήνυμα και καιρός"
"settings": "Μήνυμα και καιρός",
"slides": "Διαφάνειες"
},
"screens": {
"none": "Δεν υπάρχουν οθόνες προβολής ακόμα.",
@@ -1501,27 +1503,53 @@
"180": "Ανάποδα",
"270": "90° αριστερά"
},
"mismatch": "Μια λίστα εδώ φτιάχτηκε για το άλλο σχήμα"
"mismatch": "Μια λίστα εδώ φτιάχτηκε για το άλλο σχήμα",
"intro": "Κάθε οθόνη παίζει την προεπιλεγμένη λίστα της, εκτός αν ταιριάζει μια γραμμή προγράμματος γι' αυτήν (Οθόνες → Προγράμματα): τότε παίζει η λίστα εκείνης της γραμμής.",
"defaultPlaylist": "Προεπιλεγμένη λίστα",
"shape": "Σχήμα τηλεόρασης",
"nowScheduled": "Τώρα: {{name}} (από πρόγραμμα)",
"nowDefault": "Τώρα: {{name}} (η προεπιλογή της)",
"nowNothing": "Τώρα: τίποτα (κενή οθόνη)"
},
"schedules": {
"new": "Νέο πρόγραμμα",
"newName": "Νέο πρόγραμμα",
"created": "Το πρόγραμμα δημιουργήθηκε.",
"deleted": "Το πρόγραμμα διαγράφηκε.",
"none": "Δεν υπάρχουν προγράμματα ακόμα.",
"noneHint": "Ένα πρόγραμμα παίζει διαφορετικές λίστες σε διαφορετικές ώρες: μεσημέρι, βράδυ, Σαββατοκύριακα, γιορτές.",
"none": "Δεν υπάρχουν γραμμές προγράμματος ακόμα.",
"noneHint": "Χωρίς γραμμές κάθε οθόνη παίζει την προεπιλεγμένη λίστα της. Προσθέστε μια γραμμή για να παίζει άλλη λίστα το μεσημέρι, τα βράδια, τα Σαββατοκύριακα, τις αργίες ή σε λειτουργία πάρτι.",
"needPlaylist": "Φτιάξτε πρώτα μια λίστα.",
"nowPlaying": "τώρα: {{name}}",
"nowNothing": "τώρα: τίποτα",
"how": "Κάθε γραμμή παίζει τη λίστα της στις μέρες, στις ώρες (μπορεί να περνούν τα μεσάνυχτα) και στις ημερομηνίες της· κενό σημαίνει πάντα. Όταν ταιριάζουν δύο γραμμές, κερδίζει η μεγαλύτερη προτεραιότητα, μετά η πιο συγκεκριμένη (ημερομηνίες, μετά μέρες, μετά ώρες).",
"how": "Κάθε γραμμή παίζει τη λίστα της στις οθόνες της (καμία επιλεγμένη: σε όλες) τις ημέρες της, τις έξυπνες ημέρες, μεταξύ των ωρών της (μπορεί να περνούν τα μεσάνυχτα) και ημερομηνιών, και, αν διαλέξετε, μόνο όταν είναι ενεργή μια σκηνή. Κενό σημαίνει πάντα. Όταν ταιριάζουν δύο γραμμές σε μια οθόνη, κερδίζει η μεγαλύτερη προτεραιότητα, μετά η πιο συγκεκριμένη. Όταν δεν ταιριάζει καμία, η οθόνη παίζει την προεπιλεγμένη λίστα της (Οθόνες).",
"plays": "Παίζει",
"priority": "Προτεραιότητα",
"priorityHint": "Η μεγαλύτερη κερδίζει",
"priorityHint": "Όταν ταιριάζουν δύο γραμμές την ίδια ώρα σε μια οθόνη, κερδίζει ο μεγαλύτερος αριθμός (0 έως 100).",
"addLine": "Προσθήκη γραμμής",
"otherwise": "Τον υπόλοιπο χρόνο",
"otherwiseHint": "Όταν δεν ταιριάζει καμία γραμμή.",
"deleteTitle": "Διαγραφή «{{name}}»;",
"deleteBody": "Οι οθόνες που το έχουν γυρίζουν στη λίστα τους. Οι λίστες μένουν."
"deleteBody": "Οι οθόνες που το έχουν γυρίζουν στη λίστα τους. Οι λίστες μένουν.",
"onScreens": "Σε οθόνες",
"allScreens": "Όλες οι οθόνες",
"shortcuts": {
"everyday": "Κάθε μέρα",
"weekdays": "Καθημερινές",
"weekend": "Σαββατοκύριακο"
},
"smartDays": "Έξυπνες ημέρες",
"monthDays": {
"first": "1η του μήνα",
"last": "Τελευταία του μήνα",
"first_week": "Πρώτη εβδομάδα του μήνα",
"last_week": "Τελευταία εβδομάδα του μήνα",
"holiday": "Αργίες",
"not_holiday": "Όχι τις αργίες"
},
"scene": "Μόνο σε σκηνή",
"anyScene": "Πάντα (χωρίς σκηνή)",
"enabled": "Ενεργή",
"playingNow": "Παίζει τώρα σε: {{names}}"
},
"settings": {
"message": "Μήνυμα ημέρας",
@@ -1542,6 +1570,10 @@
"waiting": "Καμία πρόγνωση ακόμα.",
"refresh": "Ενημέρωση τώρα",
"forget": "Αφαίρεση πόλης"
},
"slidesTab": {
"title": "Έρχονται διαφάνειες για επαναχρησιμοποίηση",
"body": "Εδώ θα φτιάχνετε μεμονωμένες διαφάνειες, θα τις κρατάτε και θα τις προσθέτετε σε όποια λίστα θέλετε."
}
},
"overview": {
@@ -2303,15 +2335,18 @@
"order_channel": "Σημείο πώλησης",
"min_item_quantity": "Τουλάχιστον κάποια από το προϊόν",
"min_category_qty": "Τουλάχιστον κάποια από μια κατηγορία",
"min_order_value": "Σύνολο παραγγελίας τουλάχιστον"
"min_order_value": "Σύνολο παραγγελίας τουλάχιστον",
"scene_active": "Μια σκηνή είναι ενεργή"
},
"fields": {
"min_item_quantity": "Πόσα",
"min_category_qty": "Πόσα",
"min_order_value": "Ποσό",
"category_id": "Κατηγορία",
"price_group_id": "Ομάδα τιμών"
}
"price_group_id": "Ομάδα τιμών",
"scene_id": "Σκηνή"
},
"noScenes": "Δεν υπάρχουν σκηνές ακόμα: Διαχείριση → Σκηνές"
},
"actions": {
"add_percent": "± ποσοστό",
@@ -4017,5 +4052,38 @@
"renameYes_other": "Μετονομασία {{count}} τραπεζιών",
"andMore_one": "και {{count}} ακόμα",
"andMore_other": "και {{count}} ακόμα"
},
"scenes": {
"title": "Σκηνές",
"intro": "Λειτουργίες του καταστήματος, όπως «Λειτουργία πάρτι» ή «Βράδυ αγώνα». Όταν ενεργοποιείτε μία, αλλάζει αμέσως ό,τι την ακολουθεί: οι γραμμές των οθονών που παίζουν μόνο σε αυτήν (Οθόνες → Προγράμματα) και οι κανόνες τιμών ή οι προσφορές με τη συνθήκη «Μια σκηνή είναι ενεργή» (Προσφορές & τιμές). Μπορούν να είναι ενεργές πολλές μαζί.",
"new": "Νέα σκηνή",
"edit": "Επεξεργασία σκηνής",
"delete": "Διαγραφή",
"none": "Δεν υπάρχουν σκηνές ακόμα.",
"noneHint": "Φτιάξτε μία (π.χ. Λειτουργία πάρτι) και χρησιμοποιήστε την σε μια γραμμή προγράμματος οθονών ή σε έναν κανόνα τιμών.",
"on": "Ενεργή",
"onNow": "Ενεργή τώρα, μέχρι να την κλείσετε",
"onUntil": "Ενεργή έως {{time}}",
"turnedOn": "Η «{{name}}» ενεργοποιήθηκε.",
"turnedOff": "Η «{{name}}» απενεργοποιήθηκε.",
"for": "Όταν ενεργοποιηθεί, για",
"forOptions": {
"off": "Μέχρι να την κλείσετε",
"1": "1 ώρα",
"2": "2 ώρες",
"3": "3 ώρες",
"4": "4 ώρες",
"6": "6 ώρες",
"day": "Μέχρι το τέλος της ημέρας"
},
"name": "Όνομα",
"namePh": "π.χ. Λειτουργία πάρτι",
"description": "Περιγραφή (προαιρετικά)",
"descriptionPh": "π.χ. Παρασκευή και Σάββατο βράδυ μετά τις 23:00",
"colour": "Χρώμα",
"saved": "Η σκηνή αποθηκεύτηκε.",
"deleted": "Η σκηνή διαγράφηκε.",
"deleteTitle": "Διαγραφή «{{name}}»;",
"deleteBody": "Οι κανόνες τιμών με αυτήν παύουν να ισχύουν· οι γραμμές οθονών που έπαιζαν μόνο σε αυτήν απενεργοποιούνται."
}
}
+3 -5
View File
@@ -69,6 +69,9 @@
},
"system": {
"admin": "Συντήρηση μόνο από την υποστήριξη"
},
"scenes": {
"manage": "Δημιουργία σκηνών (λειτουργία πάρτι…) και ενεργοποίησή τους"
}
}
},
@@ -547,11 +550,6 @@
"hint": "Τι παίζει αυτή η οθόνη (Προβολή).",
"none": "Τίποτα (κενή οθόνη)"
},
"schedule": {
"label": "Πρόγραμμα",
"hint": "Παίζει τις λίστες του στις μέρες και ώρες τους· αντί για τη λίστα παραπάνω.",
"none": "Χωρίς πρόγραμμα (παίζει τη λίστα)"
},
"orientation": {
"label": "Προσανατολισμός",
"hint": "Πώς κρέμεται η τηλεόραση: οι διαφάνειες φτιάχνονται για αυτό το σχήμα.",
+7 -1
View File
@@ -187,7 +187,9 @@
"content_invalid": "This slide's setting isn't valid ({{field}}: {{reason}}).",
"order_mismatch": "The playlist changed in the meantime. Reload it and try again.",
"weather_offline": "The weather service can't be reached: the venue's server needs internet for it.",
"schedule_unknown": "Schedule {{schedule_id}} not found."
"schedule_unknown": "Schedule {{schedule_id}} not found.",
"scene_unknown": "That scene doesn't exist any more.",
"screen_unknown": "That screen doesn't exist any more."
},
"menu_tablet": {
"no_table": "This tablet isn't at a table, so it can't call a waiter.",
@@ -358,5 +360,9 @@
"channel_price": {
"not_found": "Channel price not found.",
"set_one_product": "A set price is for one product: pick one product (and no categories), or change the price by an amount or a percentage."
},
"scene": {
"not_found": "Scene not found.",
"until_past": "That time has already passed: pick a later one."
}
}
+80 -12
View File
@@ -49,7 +49,8 @@
"qrCodes": "Table QR codes",
"media": "Media",
"signage": "Signage",
"main": "Main menu"
"main": "Main menu",
"scenes": "Scenes"
},
"profile": {
"edit": "Edit profile",
@@ -1346,7 +1347,7 @@
"transition": "Comes in with",
"transitionDefault": "The playlist's transition",
"when": "When it shows",
"whenHint": "Leave empty for always. Pick days, hours (they may pass midnight) or dates to show it only then.",
"whenHint": "Leave empty for always. Pick days, hours (they may pass midnight) or dates to show it only then. This narrows the playlist's schedule: a slide whose time is outside the hours its playlist plays never shows.",
"days": "Days",
"timeFrom": "From (time)",
"timeTo": "To (time)",
@@ -1482,7 +1483,8 @@
"playlists": "Playlists",
"screens": "Screens",
"schedules": "Schedules",
"settings": "Message and weather"
"settings": "Message and weather",
"slides": "Slides"
},
"screens": {
"none": "No signage screens yet.",
@@ -1501,27 +1503,53 @@
"180": "Upside down",
"270": "90° left"
},
"mismatch": "A playlist here was made for the other shape"
"mismatch": "A playlist here was made for the other shape",
"intro": "Each screen plays its default playlist, unless a schedule line for it matches (Signage → Schedules): then that line's playlist plays.",
"defaultPlaylist": "Default playlist",
"shape": "TV shape",
"nowScheduled": "Now: {{name}} (by a schedule)",
"nowDefault": "Now: {{name}} (its default)",
"nowNothing": "Now: nothing (a blank screen)"
},
"schedules": {
"new": "New schedule",
"newName": "New schedule",
"created": "Schedule created.",
"deleted": "Schedule deleted.",
"none": "No schedules yet.",
"noneHint": "A schedule plays different playlists at different times: lunch, evenings, weekends, holidays.",
"none": "No schedule lines yet.",
"noneHint": "Without lines every screen plays its default playlist. Add a line to play another one at lunch, in the evenings, at weekends, on holidays or in party mode.",
"needPlaylist": "Make a playlist first.",
"nowPlaying": "now: {{name}}",
"nowNothing": "now: nothing",
"how": "Each line plays its playlist on its days, between its hours (they may pass midnight) and dates; empty means always. When two lines match, the higher priority wins, then the more specific one (dates, then days, then hours).",
"how": "Each line plays its playlist on its screens (none picked: every screen) on its days, smart days, between its hours (they may pass midnight) and dates, and, if you pick one, only while a scene is on. Empty means always. When two lines match on a screen, the higher priority wins, then the more specific one. When none matches, a screen plays its default playlist (Screens).",
"plays": "Plays",
"priority": "Priority",
"priorityHint": "Higher wins",
"priorityHint": "When two lines match at the same time on a screen, the higher number wins (0 to 100).",
"addLine": "Add a line",
"otherwise": "The rest of the time",
"otherwiseHint": "When no line matches.",
"deleteTitle": "Delete \"{{name}}\"?",
"deleteBody": "The screens on it go back to their playlist. The playlists stay."
"deleteBody": "The screens on it go back to their playlist. The playlists stay.",
"onScreens": "On screens",
"allScreens": "Every screen",
"shortcuts": {
"everyday": "Every day",
"weekdays": "Weekdays",
"weekend": "Weekend"
},
"smartDays": "Smart days",
"monthDays": {
"first": "1st of the month",
"last": "Last day of the month",
"first_week": "First week of the month",
"last_week": "Last week of the month",
"holiday": "Public holidays",
"not_holiday": "Not on public holidays"
},
"scene": "Only during a scene",
"anyScene": "Always (no scene)",
"enabled": "On",
"playingNow": "Playing now on {{names}}"
},
"settings": {
"message": "Message of the day",
@@ -1542,6 +1570,10 @@
"waiting": "No forecast yet.",
"refresh": "Fetch now",
"forget": "Remove the town"
},
"slidesTab": {
"title": "Slides to reuse are coming",
"body": "Here you will make single slides, keep them, and add them to any playlist."
}
},
"overview": {
@@ -2303,15 +2335,18 @@
"order_channel": "Sales point",
"min_item_quantity": "At least some of the product",
"min_category_qty": "At least some from a category",
"min_order_value": "Order total at least"
"min_order_value": "Order total at least",
"scene_active": "A scene is on"
},
"fields": {
"min_item_quantity": "How many",
"min_category_qty": "How many",
"min_order_value": "Amount",
"category_id": "Category",
"price_group_id": "Price group"
}
"price_group_id": "Price group",
"scene_id": "Scene"
},
"noScenes": "No scenes yet: Management → Scenes"
},
"actions": {
"add_percent": "± a percentage",
@@ -4017,5 +4052,38 @@
"renameYes_other": "Rename {{count}} tables",
"andMore_one": "and {{count}} more",
"andMore_other": "and {{count}} more"
},
"scenes": {
"title": "Scenes",
"intro": "Modes of the venue, like \"Party mode\" or \"Match night\". Turning one on changes at once what follows it: the signage lines that play only in it (Signage → Schedules) and the price rules or deals with the condition \"A scene is on\" (Offers & pricing). Several can be on together.",
"new": "New scene",
"edit": "Edit the scene",
"delete": "Delete",
"none": "No scenes yet.",
"noneHint": "Make one (e.g. Party mode), then use it in a signage schedule line or a price rule.",
"on": "On",
"onNow": "On now, until turned off",
"onUntil": "On until {{time}}",
"turnedOn": "\"{{name}}\" is on.",
"turnedOff": "\"{{name}}\" is off.",
"for": "When turned on, for",
"forOptions": {
"off": "Until turned off",
"1": "1 hour",
"2": "2 hours",
"3": "3 hours",
"4": "4 hours",
"6": "6 hours",
"day": "Until the end of the day"
},
"name": "Name",
"namePh": "e.g. Party mode",
"description": "Description (optional)",
"descriptionPh": "e.g. Friday and Saturday nights after 23:00",
"colour": "Colour",
"saved": "Scene saved.",
"deleted": "Scene deleted.",
"deleteTitle": "Delete \"{{name}}\"?",
"deleteBody": "Price rules with it stop applying; signage lines that played only in it are turned off."
}
}
+3 -5
View File
@@ -69,6 +69,9 @@
},
"system": {
"admin": "Support-only maintenance"
},
"scenes": {
"manage": "Make scenes (party mode…) and turn them on or off"
}
}
},
@@ -547,11 +550,6 @@
"hint": "What this screen plays (Signage).",
"none": "Nothing (a blank screen)"
},
"schedule": {
"label": "Schedule",
"hint": "Plays its playlists at their days and hours; used instead of the playlist above.",
"none": "No schedule (play the playlist)"
},
"orientation": {
"label": "Orientation",
"hint": "How the TV hangs: slides are built for this shape.",
+50 -8
View File
@@ -26,14 +26,55 @@ const mins = hhmm => {
return h * 60 + m
}
// ── smart days (owner 2026-11-21): the same as local_backend/core/calendar_days.py ──────────
export const MONTH_DAYS = ['first', 'last', 'first_week', 'last_week', 'holiday', 'not_holiday']
const FIXED_HOLIDAYS = ['01-01', '01-06', '03-25', '05-01', '08-15', '10-28', '12-25', '12-26']
const FROM_EASTER = [-48, -2, 0, 1, 50] // Clean Monday, Good Friday, Easter Sunday, Easter Monday, Whit Monday
const iso = d => d.toISOString().slice(0, 10)
/** The Orthodox Easter Sunday of a year, "YYYY-MM-DD" (Meeus' Julian algorithm + 13 days, 1900-2099). */
export function orthodoxEaster(year) {
const a = year % 4
const b = year % 7
const c = year % 19
const d = (19 * c + 15) % 30
const e = (2 * a + 4 * b - d + 34) % 7
const month = Math.floor((d + e + 114) / 31)
const day = ((d + e + 114) % 31) + 1
return iso(new Date(Date.UTC(year, month - 1, day + 13)))
}
/** A Greek public holiday (nationwide), for a "YYYY-MM-DD" date. */
export function isHoliday(date) {
if (FIXED_HOLIDAYS.includes(date.slice(5))) return true
const easter = new Date(`${orthodoxEaster(Number(date.slice(0, 4)))}T00:00:00Z`)
return FROM_EASTER.some(n => iso(new Date(easter.getTime() + n * 86400000)) === date)
}
/** Does a "YYYY-MM-DD" day pass a line's smart days (empty = every day)? Any one is enough; "not_holiday" keeps holidays out. */
export function monthDaysOk(tokens, date) {
const list = (tokens || []).filter(t => MONTH_DAYS.includes(t))
if (!list.length) return true
const hol = isHoliday(date)
if (list.includes('not_holiday') && hol) return false
const wanted = list.filter(t => t !== 'not_holiday')
if (!wanted.length) return true
const [y, m, d] = date.split('-').map(Number)
const last = new Date(Date.UTC(y, m, 0)).getUTCDate()
return wanted.some(t => (t === 'first' && d === 1) || (t === 'last' && d === last) || (t === 'first_week' && d <= 7)
|| (t === 'last_week' && d > last - 7) || (t === 'holiday' && hol))
}
function dayOk(w, local) {
const days = w.days || []
return (!days.length || days.includes(local.weekday)) &&
(!w.date_from || local.date >= w.date_from) && (!w.date_to || local.date <= w.date_to)
(!w.date_from || local.date >= w.date_from) && (!w.date_to || local.date <= w.date_to) && monthDaysOk(w.month_days, local.date)
}
/** Does a window (days, time_from / time_to that may pass midnight, date_from / date_to) cover `local`? */
export function matches(w, local) {
/** Does a window (days, smart days, time_from / time_to that may pass midnight, date_from / date_to,
* a scene that must be on) cover `local`? */
export function matches(w, local, scenes) {
if (w.scene_id != null && !(scenes || []).includes(w.scene_id)) return false
let start = mins(w.time_from)
let end = mins(w.time_to)
if (start == null && end == null) return dayOk(w, local)
@@ -45,14 +86,14 @@ export function matches(w, local) {
return false
}
const specific = e => ((e.date_from || e.date_to) ? 4 : 0) + (e.days?.length ? 2 : 0) + ((e.time_from || e.time_to) ? 1 : 0)
const specific = e => ((e.date_from || e.date_to) ? 4 : 0) + ((e.days?.length || e.month_days?.length) ? 2 : 0) + ((e.time_from || e.time_to) ? 1 : 0)
/** The playlist a schedule plays at `local`: highest priority, then the most specific, then the later entry. */
export function pick(entries, fallback, local) {
export function pick(entries, fallback, local, scenes) {
let best = null
let bestKey = null
;(entries || []).forEach((e, i) => {
if (e.playlist_id == null || !matches(e, local)) return
if (e.playlist_id == null || !matches(e, local, scenes)) return
const key = [e.priority || 0, specific(e), i]
if (!bestKey || key[0] > bestKey[0] || (key[0] === bestKey[0] && (key[1] > bestKey[1] || (key[1] === bestKey[1] && key[2] > bestKey[2])))) {
best = e.playlist_id
@@ -62,11 +103,12 @@ export function pick(entries, fallback, local) {
return best ?? fallback ?? null
}
/** The playlist to play now from the screen's answer (GET /api/signage/screen). */
/** The playlist to play now from the screen's answer (GET /api/signage/screen): a schedule line
* (with the scenes that were on when it last heard from the server), else the screen's default. */
export function playlistNow(data, now = new Date()) {
if (!data) return null
if (!data.schedule) return data.playlist || null
const id = pick(data.schedule.entries, data.schedule.fallback_playlist_id, localNow(data.schedule.timezone, now))
const id = pick(data.schedule.entries, data.schedule.fallback_playlist_id, localNow(data.schedule.timezone, now), data.schedule.scenes)
return id != null ? data.playlists?.[String(id)] ?? null : null
}
+17
View File
@@ -119,3 +119,20 @@ test('weather codes → icons', () => {
assert.equal(weatherIcon(45), 'fog')
assert.equal(weatherIcon(null), 'cloud')
})
test('smart days and scenes, the same dates as the server (owner 2026-11-21)', async () => {
const { isHoliday, matches, monthDaysOk, orthodoxEaster, pick } = await import('../src/logic.js')
assert.deepEqual([2025, 2026, 2027].map(orthodoxEaster), ['2025-04-20', '2026-04-12', '2027-05-02'])
assert.ok(isHoliday('2026-03-25') && isHoliday('2026-02-23') && isHoliday('2026-04-10') && isHoliday('2026-04-13'))
assert.ok(isHoliday('2026-06-01') && !isHoliday('2026-06-02'))
assert.ok(monthDaysOk(['first'], '2026-11-01') && !monthDaysOk(['first'], '2026-11-02'))
assert.ok(monthDaysOk(['last'], '2026-02-28') && !monthDaysOk(['last'], '2026-02-27'))
assert.ok(monthDaysOk(['first_week'], '2026-11-07') && !monthDaysOk(['first_week'], '2026-11-08'))
assert.ok(monthDaysOk(['last_week'], '2026-11-24') && !monthDaysOk(['last_week'], '2026-11-23'))
assert.ok(!monthDaysOk(['not_holiday'], '2026-12-25') && monthDaysOk(['not_holiday'], '2026-12-24'))
const sat = { weekday: 5, minutes: 13 * 60, date: '2026-11-21' }
const entries = [{ playlist_id: 40, date_from: '2026-11-21', date_to: '2026-11-21', priority: 5 }, { playlist_id: 50, scene_id: 1, priority: 9 }]
assert.equal(pick(entries, 99, sat), 40)
assert.equal(pick(entries, 99, sat, [1]), 50)
assert.ok(!matches({ scene_id: 2 }, sat, [1]))
})
+1 -1
View File
@@ -21,7 +21,7 @@ const PAGES = [
'dashboard', 'tables', 'tables?view=qr', 'online-orders', 'online-orders?tab=settings', 'crm/contacts', 'crm/customers',
'financials/expenses', 'financials/tabs', 'management/media', 'management/signage', 'management/staff', 'management/sessions',
'management/approvals', 'management/schedule', 'management/prep-zones', 'management/pricing', 'management/pricing?tab=channels',
'management/products', 'management/tables', 'management/tables?tab=floor', 'inventory/throwaways', 'notes',
'management/products', 'management/tables', 'management/tables?tab=floor', 'management/scenes', 'management/signage?tab=playlists', 'management/signage?tab=schedules', 'inventory/throwaways', 'notes',
'reports/today', 'reports/store', 'devices', 'license', 'apps', 'settings?tab=operation',
]
const SHOTS = ['dashboard', 'tables', 'tables?view=qr', 'online-orders?tab=settings', 'crm/contacts', 'crm/customers', 'financials/expenses',
+36 -21
View File
@@ -212,6 +212,10 @@ try {
await mgr.getByRole('button', { name: 'Sign in', exact: true }).click()
await mgr.waitForURL(u => u.pathname !== '/login', { timeout: 20_000 })
await mgr.goto(`${MANAGER}/management/signage`)
r.check('2026-11-21: Signage opens on Screens; the tabs: screens, playlists, schedules, slides, message and weather',
await shown(mgr, 'signage-tab-screens', 20_000) && await mgr.getByTestId('signage-tab-screens').getAttribute('aria-selected') === 'true'
&& JSON.stringify(await mgr.locator('[data-testid^="signage-tab-"]').evaluateAll(els => els.map(e => e.dataset.testid.slice(12)))) === JSON.stringify(['screens', 'playlists', 'schedules', 'slides', 'settings']))
await mgr.getByTestId('signage-tab-playlists').click()
r.check('5.6a: Management → Signage lists the playlists', await shown(mgr, 'signage-playlist-item', 20_000)
&& await mgr.getByTestId('signage-playlist-item').count() >= 2)
await mgr.getByTestId('signage-new-playlist').click()
@@ -237,6 +241,12 @@ try {
await mgr.getByTestId('signage-slide-save').click()
await sleep(800)
r.check('5.6a: …and the timeline card shows the warning', await mgr.getByTestId('signage-card-misfit').count() === 1)
const tl = await mgr.getByTestId('signage-slide-card').evaluateAll(els => els.map(e => e.getBoundingClientRect()))
r.check('2026-11-21: the timeline runs sideways, cards of one size', tl.length === 2 && Math.abs(tl[0].top - tl[1].top) < 1 && tl[1].left > tl[0].left && Math.abs(tl[0].width - tl[1].width) < 1)
const top = await mgr.getByTestId('signage-slide-basics').boundingBox()
const box = await mgr.getByTestId('signage-preview-box').boundingBox()
r.check('2026-11-21: the slide\'s basics and its preview side by side, one height', Math.abs(top.y - box.y) < 2 && Math.abs(top.height - box.height) < 2 && box.x > top.x,
JSON.stringify([top, box]))
await mgr.screenshot({ path: path.join(OUT, 'signage-editor.png'), fullPage: true })
// the picture first: the arrow on its card
await mgr.getByTestId('signage-slide-card').nth(1).getByTestId('signage-up').click()
@@ -306,38 +316,43 @@ try {
await mgr.getByTestId('signage-tab-screens').click()
const card = mgr.locator('[data-testid="signage-screen"][data-name="Window TV"]')
await card.waitFor({ timeout: 10_000 })
await card.getByTestId('signage-screen-playlist').selectOption({ label: 'Opening' })
const choose = async (where, testid, label) => { await where.getByTestId(testid).click(); await mgr.getByRole('option', { name: label }).first().click() }
await choose(card, 'signage-screen-playlist', 'Opening')
const opId = (await api('GET', '/api/signage/playlists', { token: boss })).find(x => x.name === 'Opening').id
r.check('5.6c: Screens: choosing the playlist switches the TV', !!(await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(opId), 15_000, 300)))
await card.getByTestId('signage-screen-rotation').selectOption('180')
r.check('5.6c: Screens: choosing the default playlist switches the TV', !!(await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(opId), 15_000, 300)))
await choose(card, 'signage-screen-rotation', 'Upside down')
r.check('5.6c: …and turning its picture', !!(await waitFor(async () => (await tv.getByTestId('signage-frame').getAttribute('data-rotation')) === '180', 15_000, 300)))
await card.getByTestId('signage-screen-rotation').selectOption('0')
// a schedule: "Opening" around now, "Window" the rest of the time
await choose(card, 'signage-screen-rotation', 'No')
await choose(card, 'signage-screen-playlist', 'Window')
await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300)
// a schedule line: "Opening" around now on this TV; it wins over the TV's default ("Window")
const nowAthens = new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/Athens', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(new Date())
const [hh] = nowAthens.split(':').map(Number)
const from = `${String(Math.max(0, hh - 1)).padStart(2, '0')}:00`
const to = `${String(Math.min(23, hh + 1)).padStart(2, '0')}:59`
await mgr.getByTestId('signage-tab-schedules').click()
await mgr.getByTestId('signage-new-schedule').click()
await mgr.getByTestId('signage-schedule-editor').waitFor({ timeout: 10_000 })
await mgr.getByTestId('signage-schedule-name').fill('Opening hours')
await mgr.getByTestId('signage-add-entry').click()
await mgr.getByTestId('signage-entry-playlist').selectOption({ label: 'Opening' })
await mgr.getByTestId('signage-entry-from').fill(from)
await mgr.getByTestId('signage-entry-to').fill(to)
await mgr.getByTestId('signage-schedule-fallback').selectOption({ label: 'Window' })
const line = mgr.getByTestId('signage-schedule-entry').last()
await choose(line, 'signage-entry-playlist', 'Opening')
await choose(line, 'signage-entry-screens', 'Window TV')
await mgr.keyboard.press('Escape')
await line.getByTestId('signage-entry-from').fill(from)
await line.getByTestId('signage-entry-to').fill(to)
const row = await Promise.all(['signage-entry-playlist', 'signage-entry-screens', 'signage-entry-priority'].map(id => line.getByTestId(id).boundingBox()))
r.check('2026-11-21: a line\'s playlist, screens and priority: one height, one line', row.every(b => Math.abs(b.y - row[0].y) < 1 && Math.abs(b.height - row[0].height) < 1), JSON.stringify(row))
await mgr.getByTestId('signage-schedule-save').click()
await sleep(900)
const sch = (await api('GET', '/api/signage/schedules', { token: boss })).find(x => x.name === 'Opening hours')
r.check('5.6c: a schedule built in the manager: "Opening" now, "Window" the rest of the time',
sch?.entries?.[0]?.time_from === from && sch.playing_now?.name === 'Opening' && sch.fallback_playlist_id === pl.id, JSON.stringify(sch))
let lines = []
for (let i = 0; i < 20 && !lines.length; i++) { await sleep(300); lines = await api('GET', '/api/signage/schedules', { token: boss }) }
r.check('5.6c: a schedule line built in the manager: "Opening" now on Window TV',
lines[0]?.time_from === from && lines[0].playlist_id === opId && JSON.stringify(lines[0].screen_ids) === JSON.stringify([dev.id])
&& lines[0].playing_on.some(x => x.name === 'Window TV'), JSON.stringify(lines))
r.check('5.6c: the TV plays what its line picks now (over its default)', !!(await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(opId), 15_000, 300)))
await mgr.getByTestId('signage-tab-screens').click()
await card.getByTestId('signage-screen-playlist').selectOption({ label: 'Window' })
await sleep(500)
await card.getByTestId('signage-screen-schedule').selectOption({ label: 'Opening hours' })
r.check('5.6c: the TV on the schedule plays what it picks now', !!(await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(opId), 15_000, 300)))
r.check('5.6c: Screens says it plays by a schedule', (await card.getByTestId('signage-screen-now').textContent()).includes('by a schedule'))
await mgr.screenshot({ path: path.join(OUT, 'signage-screens.png'), fullPage: true })
await card.getByTestId('signage-screen-schedule').selectOption('')
await mgr.getByTestId('signage-tab-schedules').click()
await mgr.screenshot({ path: path.join(OUT, 'signage-schedules.png'), fullPage: true })
await api('PUT', '/api/signage/schedules', { token: boss, body: { lines: [] } })
await mgr.context().close()
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } })
await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300)