feat(backend): signage schedules: which playlist plays when, switching by itself (platform-v2 step 5.4d)

- signage_schedules (Alembic 0030): entries {playlist, days, hours (may pass
  midnight), dates, priority} and a fallback playlist. A screen's `schedule`
  (ref) wins over its single playlist.
- services/signage_schedule.pick (pure): highest priority, then the most
  specific (dates > days > hours), then the later entry; no match → fallback.
- GET /api/signage/screen with a schedule: the schedule (with the venue's time
  zone) and every playlist in it, `playlist` = the one playing now, so the
  player can switch while the server is down.
- schedule_worker (signage module, 30 s) tells a screen when its pick changes.
- /api/signage/schedules CRUD (playing now, the screens on it); deleting a
  playlist takes it out of schedules; changes reach screens through schedules.
- Devices page: a signage screen's Schedule.
- tests: test_signage_schedule.py (6); 526 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 18:47:33 +02:00
co-authored by Claude Opus 5.5
parent b5951ba373
commit 0d766d3c86
15 changed files with 493 additions and 30 deletions
+1
View File
@@ -108,6 +108,7 @@ CODES: dict[str, tuple[int, str]] = {
"signage.playlist_unknown": (404, "Playlist {playlist_id} not found."),
"signage.slide_unknown": (404, "Slide {slide_id} not found."),
"signage.not_a_screen": (404, "Device {device_id} isn't a signage screen."),
"signage.schedule_unknown": (404, "Schedule {schedule_id} not found."),
"signage.not_a_video": (422, "Pick a video for this slide."),
"signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."),
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
@@ -55,6 +55,9 @@ def _ref_exists(source: str, value: int, db) -> bool:
if source == "signage_playlists":
from models.signage import SignagePlaylist
return db.get(SignagePlaylist, value) is not None
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,37 @@
"""Signage schedules (plan step 5.4d): which playlist a screen plays when.
Revision ID: 0030_signage_schedules
Revises: 0029_signage
Create Date: 2026-11-17 21:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0030_signage_schedules'
down_revision = '0029_signage'
branch_labels = None
depends_on = None
def upgrade() -> 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(), nullable=True),
sa.Column('entries', sa.JSON(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.ForeignKeyConstraint(['fallback_playlist_id'], ['signage_playlists.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('signage_schedules', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_signage_schedules_id'), ['id'], unique=False)
def downgrade() -> None:
with op.batch_alter_table('signage_schedules', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_signage_schedules_id'))
op.drop_table('signage_schedules')
+14
View File
@@ -51,3 +51,17 @@ class SignageSlide(Base):
content = Column(JSON, nullable=False, default=dict)
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"
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)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
+3 -1
View File
@@ -23,10 +23,12 @@ MODULE = Module(
SettingDef('signage.weather.units', 'celsius', "Temperatures in 'celsius' | 'fahrenheit'", type='enum', choices=('celsius', 'fahrenheit')),
),
# the weather for the screens' widget, every 30 min while there is internet (5.4c)
workers=('services.weather:weather_worker',),
workers=('services.weather:weather_worker', 'services.signage_schedule:schedule_worker'),
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)),
)),
+159 -23
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, SignageSlide
from models.signage import SignagePlaylist, SignageSchedule, SignageSlide
from services import media as media_store
from services.ws_bus import broadcast_sync
@@ -216,8 +216,32 @@ class OrderBody(BaseModel):
slide_ids: List[int]
class ScheduleEntry(BaseModel):
playlist_id: int
days: List[int] = Field(default_factory=list) # [0..6], Monday = 0; [] = every day
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)
@field_validator("days")
@classmethod
def _days(cls, v):
if any(d not in range(7) for d in v):
raise ValueError("days are 0 (Monday) to 6 (Sunday)")
return sorted(set(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 ScreenBody(BaseModel):
playlist_id: Optional[int] = None
schedule_id: Optional[int] = None
orientation: Optional[Orientation] = None
rotation: Optional[Literal[0, 90, 180, 270]] = None
@@ -330,7 +354,23 @@ def _screen_config(dev) -> dict:
def _screens_playing(db, playlist_id: int) -> list[int]:
return [d.id for d in _screens(db) if _screen_config(d).get("playlist") == playlist_id]
"""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
def _tell(ids: list[int]) -> None:
@@ -435,11 +475,16 @@ def update_playlist(playlist_id: int, body: PlaylistUpdate, db: Session = Depend
@router.delete("/playlists/{playlist_id}", status_code=204)
def delete_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
p = _playlist(db, playlist_id)
stopped = []
stopped = _screens_playing(db, p.id)
for d in _screens(db):
if (d.config or {}).get("playlist") == p.id:
d.config = {**(d.config or {}), "playlist": None}
stopped.append(d.id)
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
db.delete(p)
db.commit()
_tell(stopped)
@@ -544,9 +589,16 @@ def duplicate_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(r
def _screen_out(db, d) -> dict:
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()
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"],
"orientation_mismatch": bool(p and p.orientation != cfg["orientation"])}
"orientation_mismatch": any(o != cfg["orientation"] for o in shapes)}
@router.get("/screens")
@@ -563,7 +615,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"}.get(key, key)] = getattr(body, key)
cfg[{"playlist_id": "playlist", "schedule_id": "schedule"}.get(key, key)] = getattr(body, key)
d.config = validate(for_app("signage"), cfg, db)
db.commit()
broadcast_sync("device.updated", {}, device_ids=[d.id])
@@ -573,29 +625,46 @@ def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db
# ── the screen itself ──────────────────────────────────────────────────────────
def _resolved(db, p: SignagePlaylist) -> dict:
"""A playlist as a screen plays it: enabled slides, transitions filled in, menus, QR links, media."""
from services.signage_menu import resolve
slides = [_slide_out(s) for s in p.slides if s.enabled]
for s in slides:
s["transition"] = s["transition"] or p.transition
if s["kind"] == "menu":
s["menu"] = resolve(db, s["content"]) # live prices and availability (5.4b)
for w in s["content"].get("widgets") or []:
if w["kind"] == "qr":
w["link"] = _qr_link(w)
return {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides,
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])}
@router.get("/screen")
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).
`version` changes whenever anything here does (the player's cache key)."""
cfg = _screen_config(dev)
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
playlist = None
if p is not None:
from services.signage_menu import resolve
slides = [_slide_out(s) for s in p.slides if s.enabled]
for s in slides:
s["transition"] = s["transition"] or p.transition
if s["kind"] == "menu":
s["menu"] = resolve(db, s["content"]) # live prices and availability (5.4b)
for w in s["content"].get("widgets") or []:
if w["kind"] == "qr":
w["link"] = _qr_link(w)
playlist = {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides,
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])}
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."""
from core.timeutil import venue_now, venue_tz
from services import weather
from services.signage_schedule import pick
cfg = _screen_config(dev)
sch = db.get(SignageSchedule, cfg["schedule"]) if cfg.get("schedule") else None
schedule, playlists, playlist = None, None, None
if sch is not None:
ids = _schedule_playlists(sch)
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())
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}
else:
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") 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,
"playlist": playlist, "schedule": schedule, "playlists": playlists,
# for the widgets (5.4c): weather None = hide it (no internet, no place, too old)
"venue": {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None,
"weather": weather.current(db)}}
@@ -603,6 +672,73 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
return out
# ── schedules (5.4d) ───────────────────────────────────────────────────────────
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 _schedule_out(db, s: SignageSchedule) -> dict:
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)
@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)]
@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)
db.commit()
db.refresh(s)
return _schedule_out(db, s)
@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):
+118
View File
@@ -0,0 +1,118 @@
"""Signage schedules (plan step 5.4d): 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:
- its days include today (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).
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).
`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
changes.
"""
from __future__ import annotations
import asyncio
import logging
from datetime import datetime, timedelta
logger = logging.getLogger("xenia.signage")
def _minutes(hhmm: str | None) -> int | None:
if not hhmm:
return None
h, m = hhmm.split(":")
return int(h) * 60 + int(m)
def _date_ok(e: dict, day) -> bool:
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"])
def matches(e: dict, local: datetime) -> bool:
"""Does entry `e` cover this venue-local moment?"""
days = e.get("days") or []
start, end = _minutes(e.get("time_from")), _minutes(e.get("time_to"))
now = local.hour * 60 + local.minute
if start is None and end is None:
return (not days or local.weekday() in days) and _date_ok(e, local.date())
start = 0 if start is None else start
end = 24 * 60 if end is None else end
if start < end: # the same day
return start <= now < end and (not days or local.weekday() in days) and _date_ok(e, local.date())
# passes midnight: before midnight it is today's window, after midnight yesterday's
if now >= start:
return (not days or local.weekday() in days) and _date_ok(e, local.date())
if now < end:
y = local - timedelta(days=1)
return (not days or y.weekday() in days) and _date_ok(e, y.date())
return False
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) + \
(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:
"""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):
continue
key = (e.get("priority") or 0, _specific(e), i)
if best_key is None or key > best_key:
best, best_key = e["playlist_id"], key
return best if best is not None else fallback
# ── telling screens when their pick changes ───────────────────────────────────
_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)."""
from core.timeutil import venue_now
from models.signage import SignageSchedule
from routers.signage import _screen_config, _screens
local = local or venue_now()
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
if d.id in _playing and _playing[d.id] != now:
changed.append(d.id)
_playing[d.id] = now
return changed
async def schedule_worker():
"""Every 30 s (a signage module worker): a screen whose schedule now picks another playlist is told."""
from database import SessionLocal
while True:
db = SessionLocal()
try:
ids = due_changes(db)
if ids:
from routers.signage import _tell
_tell(ids)
logger.info("signage: schedule switched screens %s", ids)
except Exception as e:
logger.warning("signage schedule worker: %s", e)
finally:
db.close()
await asyncio.sleep(30)
def reset() -> None:
_playing.clear()
@@ -0,0 +1,138 @@
"""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
import pytest
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
MON_10 = datetime(2026, 11, 16, 10, 0) # a Monday
MON_13 = datetime(2026, 11, 16, 13, 0)
SAT_13 = datetime(2026, 11, 21, 13, 0)
SAT_23 = datetime(2026, 11, 21, 23, 30)
SUN_01 = datetime(2026, 11, 22, 1, 0)
MON_01 = datetime(2026, 11, 16, 1, 0)
def test_which_entries_match():
lunch = {"playlist_id": 1, "time_from": "12:00", "time_to": "15:00"}
assert matches(lunch, MON_13) and not matches(lunch, MON_10)
night = {"playlist_id": 2, "days": [5], "time_from": "22:00", "time_to": "02:00"} # Saturday night
assert matches(night, SAT_23) and matches(night, SUN_01) # after midnight: Saturday's
assert not matches(night, MON_01)
xmas = {"playlist_id": 3, "date_from": "2026-12-20", "date_to": "2026-12-27"}
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
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
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
@pytest.fixture
def sent(monkeypatch):
import routers.signage as sg
got = []
monkeypatch.setattr(sg, "broadcast_sync", lambda kind, data, **kw: got.append((kind, kw.get("device_ids"))))
return got
@pytest.fixture
def at(monkeypatch):
"""Freeze the venue clock: at(datetime) sets it."""
import core.timeutil as tu
from core.timeutil import venue_tz
state = {"now": MON_10}
monkeypatch.setattr(tu, "venue_now", lambda: state["now"].replace(tzinfo=venue_tz()))
return lambda dt: state.update(now=dt)
@pytest.fixture
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(),
"lunch": lunch["id"], "weekend": weekend["id"], "normal": normal["id"]}
def test_a_screen_gets_its_schedule_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 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
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
def test_the_server_tells_a_screen_when_its_playlist_switches(client, db, setup, at):
"""Done when (5.4d): the schedule switches the screen's playlist at the set hour."""
from services import signage_schedule as ss
ss.reset()
at(datetime(2026, 11, 16, 11, 59))
assert ss.due_changes(db) == [] # first look: remembered
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) == []
at(datetime(2026, 11, 16, 15, 0))
assert ss.due_changes(db) == [setup["id"]] # and ends
ss.reset()
def test_changes_and_deletes(client, owner_h, setup, sent, at):
at(MON_10)
sid = setup["schedule"]["id"]
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()
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
got = client.get("/api/signage/screen", headers=setup["h"]).json()
assert got["schedule"] is None and got["playlist"] is None
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")