Files
xenia-pos-local/local_backend/services/signage_schedule.py
T
bonaminandClaude Opus 5.5 0d766d3c86 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>
2026-11-17 18:47:33 +02:00

119 lines
4.6 KiB
Python

"""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()