feat(backend): signage widgets, the message of the day, the weather (platform-v2 step 5.4c)
- Widget on text and menu slides: logo (a picture), name, date (short/long), clock (seconds), message (the venue's or its own text), QR code (ordering / QR menu / a link; the screen gets the link), weather (1-3 days); position (corners, top / bottom bar) and size. Logos count as media usage. - The screen gets `venue`: name, message of the day, weather. - PUT /api/signage/message (one place, every screen told at once). - services/weather.py: the venue's place (town search through /api/signage/weather/places, PUT/DELETE /weather/place, °C/°F), Open-Meteo every 30 min (signage worker), kept in memory; no place, no internet or older than 3 h → weather null and the widget hides. signage.weather_offline when the town search can't reach the service. Checked against the real service. - tests: test_signage_widgets.py (5, a fake Open-Meteo); 520 passed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -41,6 +41,7 @@ from services.ws_bus import broadcast_sync
|
||||
|
||||
router = APIRouter()
|
||||
KEY = "signage.manage"
|
||||
MESSAGE = "signage.message"
|
||||
HEX = r"^#[0-9a-fA-F]{6}$"
|
||||
TIME = r"^([01]\d|2[0-3]):[0-5]\d$"
|
||||
DATE = r"^\d{4}-\d{2}-\d{2}$"
|
||||
@@ -63,6 +64,34 @@ class Background(_Strict):
|
||||
fit: Literal["cover", "contain"] = "cover"
|
||||
|
||||
|
||||
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"]
|
||||
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar"]
|
||||
|
||||
|
||||
class Widget(_Strict):
|
||||
"""Something small on a menu or text slide (5.4c), in a corner or a bar."""
|
||||
kind: WidgetKind
|
||||
position: Position = "top-right"
|
||||
size: Literal["small", "medium", "large"] = "medium"
|
||||
media_id: Optional[int] = None # logo: a picture
|
||||
text: Optional[str] = Field(default=None, max_length=200) # message: this text instead of the venue's
|
||||
date_style: Literal["short", "long"] = "long"
|
||||
clock_seconds: bool = False
|
||||
qr_target: Literal["ordering", "menu", "custom"] = "ordering"
|
||||
qr_url: Optional[str] = Field(default=None, max_length=300)
|
||||
qr_caption: Optional[str] = Field(default=None, max_length=80)
|
||||
weather_days: int = Field(default=1, ge=1, le=3) # today, or today + the next days
|
||||
|
||||
@field_validator("qr_url")
|
||||
@classmethod
|
||||
def _url(cls, v):
|
||||
import re as _re
|
||||
v = (v or "").strip() or None
|
||||
if v and not _re.match(r"^https?://", v):
|
||||
raise ValueError("a link starts with http:// or https://")
|
||||
return v
|
||||
|
||||
|
||||
class ImageContent(_Strict):
|
||||
media_id: Optional[int] = None # a picture
|
||||
fit: Literal["cover", "contain"] = "cover"
|
||||
@@ -85,6 +114,7 @@ class TextContent(_Strict):
|
||||
text_colour: str = Field(default="#ffffff", pattern=HEX)
|
||||
text_size: int = Field(default=100, ge=50, le=250) # %
|
||||
background: Background = Field(default_factory=Background)
|
||||
widgets: List[Widget] = Field(default_factory=list, max_length=10)
|
||||
|
||||
|
||||
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"]
|
||||
@@ -118,6 +148,7 @@ class MenuContent(_Strict):
|
||||
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # prices, headings, badges
|
||||
text_size: int = Field(default=100, ge=50, le=250)
|
||||
background: Background = Field(default_factory=Background)
|
||||
widgets: List[Widget] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator("sales_point")
|
||||
@classmethod
|
||||
@@ -193,6 +224,26 @@ class ScreenBody(BaseModel):
|
||||
|
||||
# ── helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _setting(db, key: str, default: str = "") -> str:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
return row.value if row and row.value is not None else default
|
||||
|
||||
|
||||
def _save_setting(db, key: str, value: str) -> None:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if row is None:
|
||||
db.add(PosSettings(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
|
||||
|
||||
def _qr_link(w: dict) -> str | None:
|
||||
from routers.customer_display import _qr_link as link
|
||||
return link({"qr_target": w.get("qr_target") or "ordering", "qr_url": w.get("qr_url")})
|
||||
|
||||
|
||||
def _playlist(db, pid: int) -> SignagePlaylist:
|
||||
p = db.get(SignagePlaylist, pid)
|
||||
if p is None:
|
||||
@@ -246,8 +297,8 @@ def _content(db, kind: str, raw: dict | None) -> dict:
|
||||
raise XeniaError("signage.not_a_video")
|
||||
if kind != "video" and m.kind != "image":
|
||||
raise XeniaError("media.not_a_picture")
|
||||
bg = (data.get("background") or {}).get("media_id")
|
||||
if bg is not None and db.get(Media, bg).kind != "image":
|
||||
pictures = [(data.get("background") or {}).get("media_id")] + [w.get("media_id") for w in data.get("widgets") or []]
|
||||
if any(i is not None and db.get(Media, i).kind != "image" for i in pictures):
|
||||
raise XeniaError("media.not_a_picture")
|
||||
return data
|
||||
|
||||
@@ -333,6 +384,11 @@ def _uses(db, media_id: int) -> list:
|
||||
media_store.register_usage("signage_slide", _uses)
|
||||
|
||||
|
||||
def tell_all_screens(db) -> None:
|
||||
"""Something every screen may show changed (the message of the day, the weather)."""
|
||||
_tell([d.id for d in _screens(db)])
|
||||
|
||||
|
||||
def menu_changed(db) -> None:
|
||||
"""Products, categories or prices changed (main.py, the same requests that push the online menu):
|
||||
the screens with a menu board on their playlist read it again."""
|
||||
@@ -532,9 +588,90 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
|
||||
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"])])}
|
||||
from services import weather
|
||||
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
|
||||
"playlist": playlist}
|
||||
"playlist": playlist,
|
||||
# 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)}}
|
||||
out["version"] = hashlib.sha256(json.dumps(out, sort_keys=True, default=str).encode()).hexdigest()[:16]
|
||||
return out
|
||||
|
||||
|
||||
# ── the message of the day and the weather (5.4c) ──────────────────────────────
|
||||
|
||||
class MessageBody(BaseModel):
|
||||
text: Optional[str] = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
class PlaceBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
latitude: float = Field(ge=-90, le=90)
|
||||
longitude: float = Field(ge=-180, le=180)
|
||||
units: Literal["celsius", "fahrenheit"] = "celsius"
|
||||
|
||||
|
||||
@router.get("/message")
|
||||
def get_message(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
return {"text": _setting(db, MESSAGE) or None}
|
||||
|
||||
|
||||
@router.put("/message")
|
||||
def put_message(body: MessageBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""The message of the day: one place to change it for every screen, at once."""
|
||||
_save_setting(db, MESSAGE, (body.text or "").strip())
|
||||
db.commit()
|
||||
tell_all_screens(db)
|
||||
return {"text": (body.text or "").strip() or None}
|
||||
|
||||
|
||||
@router.get("/weather")
|
||||
def weather_status(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from services import weather
|
||||
return weather.status(db)
|
||||
|
||||
|
||||
@router.put("/weather/place")
|
||||
async def weather_place(body: PlaceBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from services import weather
|
||||
_save_setting(db, "signage.weather.place", body.name.strip())
|
||||
_save_setting(db, "signage.weather.latitude", f"{body.latitude:.4f}")
|
||||
_save_setting(db, "signage.weather.longitude", f"{body.longitude:.4f}")
|
||||
_save_setting(db, "signage.weather.units", body.units)
|
||||
db.commit()
|
||||
await weather.refresh(db)
|
||||
return weather.status(db)
|
||||
|
||||
|
||||
@router.delete("/weather/place")
|
||||
async def weather_forget(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from services import weather
|
||||
for k in ("signage.weather.place", "signage.weather.latitude", "signage.weather.longitude"):
|
||||
_save_setting(db, k, "")
|
||||
db.commit()
|
||||
await weather.refresh(db)
|
||||
return weather.status(db)
|
||||
|
||||
|
||||
@router.post("/weather/refresh")
|
||||
async def weather_refresh(db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
from services import weather
|
||||
await weather.refresh(db)
|
||||
return weather.status(db)
|
||||
|
||||
|
||||
@router.get("/weather/places")
|
||||
async def weather_places(q: str, language: str = "en", user=Depends(require(KEY))):
|
||||
"""Towns for the editor's search (needs internet: none → `signage.weather_offline`)."""
|
||||
from services import weather
|
||||
if len(q.strip()) < 2:
|
||||
return []
|
||||
try:
|
||||
return await weather.search(q.strip(), language if language in ("en", "el") else "en")
|
||||
except Exception:
|
||||
raise XeniaError("signage.weather_offline")
|
||||
|
||||
Reference in New Issue
Block a user