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
+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)
+113 -105
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)
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()
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()
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):