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)
+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):
+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"