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:
+1
-1
@@ -48,7 +48,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
|
|||||||
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
|
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
|
||||||
| `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory |
|
| `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory |
|
||||||
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` |
|
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` |
|
||||||
| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`) |
|
| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget) |
|
||||||
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
|
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
|
||||||
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
|
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
|
||||||
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
||||||
|
|||||||
@@ -111,6 +111,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"signage.not_a_video": (422, "Pick a video for this slide."),
|
"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.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."),
|
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
|
||||||
|
"signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
|
||||||
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
||||||
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
"reservation.not_found": (404, "Booking {reservation_id} not found."),
|
||||||
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
|
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm, SettingDef
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='signage',
|
key='signage',
|
||||||
@@ -15,6 +15,15 @@ MODULE = Module(
|
|||||||
routers=(
|
routers=(
|
||||||
Mount('routers.signage', '/api/signage'),
|
Mount('routers.signage', '/api/signage'),
|
||||||
),
|
),
|
||||||
|
settings=(
|
||||||
|
SettingDef('signage.message', '', 'The message of the day on every signage screen with a message widget (Signage > Message of the day).'),
|
||||||
|
SettingDef('signage.weather.place', '', 'The place whose weather the screens show (picked from a town search in Signage).'),
|
||||||
|
SettingDef('signage.weather.latitude', '', 'Latitude of the weather place.'),
|
||||||
|
SettingDef('signage.weather.longitude', '', 'Longitude of the weather place.'),
|
||||||
|
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',),
|
||||||
device_app=DeviceApp(login_modes=('none',), scope=(), config=(
|
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
|
# 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'),
|
ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'),
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ from services.ws_bus import broadcast_sync
|
|||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
KEY = "signage.manage"
|
KEY = "signage.manage"
|
||||||
|
MESSAGE = "signage.message"
|
||||||
HEX = r"^#[0-9a-fA-F]{6}$"
|
HEX = r"^#[0-9a-fA-F]{6}$"
|
||||||
TIME = r"^([01]\d|2[0-3]):[0-5]\d$"
|
TIME = r"^([01]\d|2[0-3]):[0-5]\d$"
|
||||||
DATE = r"^\d{4}-\d{2}-\d{2}$"
|
DATE = r"^\d{4}-\d{2}-\d{2}$"
|
||||||
@@ -63,6 +64,34 @@ class Background(_Strict):
|
|||||||
fit: Literal["cover", "contain"] = "cover"
|
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):
|
class ImageContent(_Strict):
|
||||||
media_id: Optional[int] = None # a picture
|
media_id: Optional[int] = None # a picture
|
||||||
fit: Literal["cover", "contain"] = "cover"
|
fit: Literal["cover", "contain"] = "cover"
|
||||||
@@ -85,6 +114,7 @@ class TextContent(_Strict):
|
|||||||
text_colour: str = Field(default="#ffffff", pattern=HEX)
|
text_colour: str = Field(default="#ffffff", pattern=HEX)
|
||||||
text_size: int = Field(default=100, ge=50, le=250) # %
|
text_size: int = Field(default=100, ge=50, le=250) # %
|
||||||
background: Background = Field(default_factory=Background)
|
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"]
|
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
|
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # prices, headings, badges
|
||||||
text_size: int = Field(default=100, ge=50, le=250)
|
text_size: int = Field(default=100, ge=50, le=250)
|
||||||
background: Background = Field(default_factory=Background)
|
background: Background = Field(default_factory=Background)
|
||||||
|
widgets: List[Widget] = Field(default_factory=list, max_length=10)
|
||||||
|
|
||||||
@field_validator("sales_point")
|
@field_validator("sales_point")
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -193,6 +224,26 @@ class ScreenBody(BaseModel):
|
|||||||
|
|
||||||
# ── helpers ────────────────────────────────────────────────────────────────────
|
# ── 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:
|
def _playlist(db, pid: int) -> SignagePlaylist:
|
||||||
p = db.get(SignagePlaylist, pid)
|
p = db.get(SignagePlaylist, pid)
|
||||||
if p is None:
|
if p is None:
|
||||||
@@ -246,8 +297,8 @@ def _content(db, kind: str, raw: dict | None) -> dict:
|
|||||||
raise XeniaError("signage.not_a_video")
|
raise XeniaError("signage.not_a_video")
|
||||||
if kind != "video" and m.kind != "image":
|
if kind != "video" and m.kind != "image":
|
||||||
raise XeniaError("media.not_a_picture")
|
raise XeniaError("media.not_a_picture")
|
||||||
bg = (data.get("background") or {}).get("media_id")
|
pictures = [(data.get("background") or {}).get("media_id")] + [w.get("media_id") for w in data.get("widgets") or []]
|
||||||
if bg is not None and db.get(Media, bg).kind != "image":
|
if any(i is not None and db.get(Media, i).kind != "image" for i in pictures):
|
||||||
raise XeniaError("media.not_a_picture")
|
raise XeniaError("media.not_a_picture")
|
||||||
return data
|
return data
|
||||||
|
|
||||||
@@ -333,6 +384,11 @@ def _uses(db, media_id: int) -> list:
|
|||||||
media_store.register_usage("signage_slide", _uses)
|
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:
|
def menu_changed(db) -> None:
|
||||||
"""Products, categories or prices changed (main.py, the same requests that push the online menu):
|
"""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."""
|
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
|
s["transition"] = s["transition"] or p.transition
|
||||||
if s["kind"] == "menu":
|
if s["kind"] == "menu":
|
||||||
s["menu"] = resolve(db, s["content"]) # live prices and availability (5.4b)
|
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,
|
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"])])}
|
"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"]},
|
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]
|
out["version"] = hashlib.sha256(json.dumps(out, sort_keys=True, default=str).encode()).hexdigest()[:16]
|
||||||
return out
|
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")
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
"""The weather for signage screens (plan step 5.4c, owner 2026-11-17: "weather only works with
|
||||||
|
internet; if the internet is down, just hide the widget").
|
||||||
|
|
||||||
|
The venue's place is a setting (`signage.weather.place`, `.latitude`, `.longitude`, picked in the
|
||||||
|
editor from a town search). `weather_worker` (a signage module worker) asks Open-Meteo (free, no
|
||||||
|
key) every 30 minutes while it has internet and keeps the last answer in memory. A forecast older
|
||||||
|
than 3 hours counts as none: the screens get `weather: null` and hide the widget.
|
||||||
|
|
||||||
|
current() → {"place", "temperature", "code", "is_day", "days": [{date, max, min, code}], "units", "at"} | None
|
||||||
|
search(name) → places for the editor's search (name, country, region, latitude, longitude)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger("xenia.weather")
|
||||||
|
|
||||||
|
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
|
||||||
|
SEARCH_URL = "https://geocoding-api.open-meteo.com/v1/search"
|
||||||
|
EVERY_S = 30 * 60
|
||||||
|
STALE_S = 3 * 3600
|
||||||
|
TIMEOUT_S = 10
|
||||||
|
|
||||||
|
_last: dict = {"data": None, "at": 0.0, "key": None, "error": None, "tried": 0.0}
|
||||||
|
|
||||||
|
|
||||||
|
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 not in (None, "") else default
|
||||||
|
|
||||||
|
|
||||||
|
def place(db) -> dict | None:
|
||||||
|
"""The venue's place for the weather, or None when it isn't set."""
|
||||||
|
try:
|
||||||
|
lat, lon = float(_setting(db, "signage.weather.latitude")), float(_setting(db, "signage.weather.longitude"))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||||||
|
return None
|
||||||
|
units = _setting(db, "signage.weather.units", "celsius")
|
||||||
|
return {"name": _setting(db, "signage.weather.place") or f"{lat:.2f}, {lon:.2f}", "latitude": lat, "longitude": lon,
|
||||||
|
"units": units if units in ("celsius", "fahrenheit") else "celsius"}
|
||||||
|
|
||||||
|
|
||||||
|
def current(db, now: float | None = None) -> dict | None:
|
||||||
|
"""The last forecast for the venue's place while it is fresh; None hides the widget."""
|
||||||
|
where = place(db)
|
||||||
|
if where is None or _last["data"] is None or _last["key"] != _key(where):
|
||||||
|
return None
|
||||||
|
if (now or time.time()) - _last["at"] > STALE_S:
|
||||||
|
return None
|
||||||
|
return _last["data"]
|
||||||
|
|
||||||
|
|
||||||
|
def status(db) -> dict:
|
||||||
|
where = place(db)
|
||||||
|
return {"place": where, "weather": current(db), "fetched_at": _last["at"] or None,
|
||||||
|
"error": _last["error"] if where else None}
|
||||||
|
|
||||||
|
|
||||||
|
def _key(where: dict) -> tuple:
|
||||||
|
return (round(where["latitude"], 3), round(where["longitude"], 3), where["units"])
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch(where: dict, client: httpx.AsyncClient | None = None) -> dict:
|
||||||
|
params = {"latitude": where["latitude"], "longitude": where["longitude"], "timezone": "auto", "forecast_days": 3,
|
||||||
|
"current": "temperature_2m,weather_code,is_day", "daily": "temperature_2m_max,temperature_2m_min,weather_code",
|
||||||
|
"temperature_unit": where["units"]}
|
||||||
|
own = client is None
|
||||||
|
client = client or httpx.AsyncClient(timeout=TIMEOUT_S)
|
||||||
|
try:
|
||||||
|
r = await client.get(FORECAST_URL, params=params)
|
||||||
|
r.raise_for_status()
|
||||||
|
j = r.json()
|
||||||
|
finally:
|
||||||
|
if own:
|
||||||
|
await client.aclose()
|
||||||
|
cur, daily = j.get("current") or {}, j.get("daily") or {}
|
||||||
|
days = [{"date": d, "max": mx, "min": mn, "code": c}
|
||||||
|
for d, mx, mn, c in zip(daily.get("time", []), daily.get("temperature_2m_max", []),
|
||||||
|
daily.get("temperature_2m_min", []), daily.get("weather_code", []))]
|
||||||
|
return {"place": where["name"], "temperature": cur.get("temperature_2m"), "code": cur.get("weather_code"),
|
||||||
|
"is_day": bool(cur.get("is_day", 1)), "days": days, "units": where["units"], "at": cur.get("time")}
|
||||||
|
|
||||||
|
|
||||||
|
async def refresh(db, client: httpx.AsyncClient | None = None) -> bool:
|
||||||
|
"""Fetch now for the venue's place. True when a forecast came; the screens are told either way
|
||||||
|
when it changes whether they can show one."""
|
||||||
|
where = place(db)
|
||||||
|
before = current(db) is not None
|
||||||
|
_last["tried"] = time.time()
|
||||||
|
if where is None:
|
||||||
|
_last.update(data=None, key=None, error=None)
|
||||||
|
ok = False
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
data = await fetch(where, client)
|
||||||
|
_last.update(data=data, at=time.time(), key=_key(where), error=None)
|
||||||
|
ok = True
|
||||||
|
except Exception as e: # no internet, DNS, the service down: the widget hides
|
||||||
|
_last["error"] = type(e).__name__
|
||||||
|
logger.info("weather: no forecast (%s)", _last["error"])
|
||||||
|
ok = False
|
||||||
|
if ok or before != (current(db) is not None):
|
||||||
|
_tell_screens(db)
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
def _tell_screens(db) -> None:
|
||||||
|
try:
|
||||||
|
from routers.signage import tell_all_screens
|
||||||
|
tell_all_screens(db)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("weather: screens not told: %s", e)
|
||||||
|
|
||||||
|
|
||||||
|
async def search(name: str, language: str = "en", client: httpx.AsyncClient | None = None) -> list[dict]:
|
||||||
|
own = client is None
|
||||||
|
client = client or httpx.AsyncClient(timeout=TIMEOUT_S)
|
||||||
|
try:
|
||||||
|
r = await client.get(SEARCH_URL, params={"name": name, "count": 8, "language": language, "format": "json"})
|
||||||
|
r.raise_for_status()
|
||||||
|
results = r.json().get("results") or []
|
||||||
|
finally:
|
||||||
|
if own:
|
||||||
|
await client.aclose()
|
||||||
|
return [{"name": x.get("name"), "country": x.get("country"), "region": x.get("admin1"),
|
||||||
|
"latitude": x.get("latitude"), "longitude": x.get("longitude")} for x in results]
|
||||||
|
|
||||||
|
|
||||||
|
async def weather_worker():
|
||||||
|
"""Every 30 minutes (a signage module worker; stops when signage is turned off)."""
|
||||||
|
from database import SessionLocal
|
||||||
|
while True:
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
await refresh(db)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("weather worker: %s", e)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
await asyncio.sleep(EVERY_S)
|
||||||
|
|
||||||
|
|
||||||
|
def reset() -> None:
|
||||||
|
_last.update(data=None, at=0.0, key=None, error=None, tried=0.0)
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""Signage widgets (plan step 5.4c): logo, name, date, clock, message of the day, QR code and
|
||||||
|
weather on menu and text slides; the message changes on every screen at once; the weather comes
|
||||||
|
from the internet and is simply hidden (null) when it can't be fetched."""
|
||||||
|
import asyncio
|
||||||
|
import time
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||||
|
from tests.test_media import jpeg, media_dir, mp4, up # noqa: F401 (fixture + helpers)
|
||||||
|
from tests.test_signage import playlist, slide
|
||||||
|
|
||||||
|
FORECAST = {"current": {"time": "2026-11-17T12:00", "temperature_2m": 17.4, "weather_code": 2, "is_day": 1},
|
||||||
|
"daily": {"time": ["2026-11-17", "2026-11-18"], "temperature_2m_max": [19.0, 16.5],
|
||||||
|
"temperature_2m_min": [9.1, 8.0], "weather_code": [2, 61]}}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _fresh_weather():
|
||||||
|
from services import weather
|
||||||
|
weather.reset()
|
||||||
|
yield
|
||||||
|
weather.reset()
|
||||||
|
|
||||||
|
|
||||||
|
@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 tv(client, owner_h, pair):
|
||||||
|
token, r = pair("signage", "TV")
|
||||||
|
p = playlist(client, owner_h, "Window")
|
||||||
|
client.put(f"/api/signage/screens/{r.json()['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
||||||
|
return {"h": {"X-Xenia-Device": token}, "id": r.json()["id"], "playlist": p["id"]}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def internet(monkeypatch):
|
||||||
|
"""Open-Meteo answered by a fake: `internet["up"] = False` cuts the line."""
|
||||||
|
from services import weather
|
||||||
|
state = {"up": True, "calls": []}
|
||||||
|
|
||||||
|
def handler(request):
|
||||||
|
state["calls"].append(str(request.url))
|
||||||
|
if not state["up"]:
|
||||||
|
raise httpx.ConnectError("no internet")
|
||||||
|
if "geocoding" in str(request.url):
|
||||||
|
return httpx.Response(200, json={"results": [{"name": "Kalavryta", "country": "Greece", "admin1": "West Greece",
|
||||||
|
"latitude": 38.03, "longitude": 22.11}]})
|
||||||
|
return httpx.Response(200, json=FORECAST)
|
||||||
|
real = httpx.AsyncClient
|
||||||
|
monkeypatch.setattr(weather.httpx, "AsyncClient", lambda **kw: real(transport=httpx.MockTransport(handler), **kw))
|
||||||
|
return state
|
||||||
|
|
||||||
|
|
||||||
|
def test_widgets_on_slides(client, owner_h, tv, monkeypatch):
|
||||||
|
from services import cloud_sync
|
||||||
|
monkeypatch.setitem(cloud_sync.license_state, "apps_url", "https://menu.example.com")
|
||||||
|
monkeypatch.setattr(cloud_sync.settings, "SITE_ID", "taverna-1")
|
||||||
|
logo, video = up(client, owner_h, jpeg(400, 200)).json(), up(client, owner_h, mp4(), name="v.mp4", ctype="video/mp4").json()
|
||||||
|
widgets = [{"kind": "logo", "position": "top-left", "media_id": logo["id"]}, {"kind": "clock", "position": "top-right", "clock_seconds": True},
|
||||||
|
{"kind": "date", "position": "bottom-left"}, {"kind": "message", "position": "bottom-bar"},
|
||||||
|
{"kind": "qr", "position": "bottom-right", "qr_caption": "Order online"}, {"kind": "weather", "weather_days": 3}]
|
||||||
|
s = slide(client, owner_h, tv["playlist"], "text", content={"title": "Welcome", "widgets": widgets})
|
||||||
|
got = next(x for x in client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"] if x["id"] == s["id"])
|
||||||
|
ws = got["content"]["widgets"]
|
||||||
|
assert [w["kind"] for w in ws] == ["logo", "clock", "date", "message", "qr", "weather"]
|
||||||
|
assert ws[4]["link"] == "https://menu.example.com/order/taverna-1"
|
||||||
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["media"][str(logo["id"])]["kind"] == "image"
|
||||||
|
slide(client, owner_h, tv["playlist"], "menu", content={"select": "all", "widgets": [{"kind": "name", "position": "top-bar", "size": "large"}]})
|
||||||
|
url = f"/api/signage/playlists/{tv['playlist']}/slides"
|
||||||
|
assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"widgets": [{"kind": "logo", "media_id": video["id"]}]}})) == "media.not_a_picture"
|
||||||
|
assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"widgets": [{"kind": "logo", "position": "middle"}]}})) == "signage.content_invalid"
|
||||||
|
assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"widgets": [{"kind": "disco"}]}})) == "signage.content_invalid"
|
||||||
|
assert err(client.post(url, headers=owner_h, json={"kind": "text", "content": {"widgets": [{"kind": "qr", "qr_target": "custom", "qr_url": "ftp://x"}]}})) == "signage.content_invalid"
|
||||||
|
# a logo in a widget is protected in the library
|
||||||
|
assert client.delete(f"/api/media/{logo['id']}", headers=owner_h).status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_message_of_the_day_reaches_every_screen(client, owner_h, tv, pair, sent):
|
||||||
|
_, other = pair("signage", "TV 2")
|
||||||
|
r = client.put("/api/signage/message", headers=owner_h, json={"text": " Today: fresh fish! "})
|
||||||
|
assert r.json() == {"text": "Today: fresh fish!"}
|
||||||
|
assert sent == [("signage.changed", sorted([tv["id"], other.json()["id"]]))]
|
||||||
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["message"] == "Today: fresh fish!"
|
||||||
|
client.put("/api/signage/message", headers=owner_h, json={"text": ""})
|
||||||
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["message"] is None
|
||||||
|
assert client.get("/api/signage/message", headers=owner_h).json() == {"text": None}
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_weather_shows_with_internet_and_hides_without(client, owner_h, tv, internet, sent, db):
|
||||||
|
from services import weather
|
||||||
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"] is None # no place yet
|
||||||
|
places = client.get("/api/signage/weather/places?q=Kalav", headers=owner_h).json()
|
||||||
|
assert places[0]["name"] == "Kalavryta" and places[0]["latitude"] == 38.03
|
||||||
|
r = client.put("/api/signage/weather/place", headers=owner_h, json={"name": "Kalavryta", "latitude": 38.03, "longitude": 22.11})
|
||||||
|
assert r.status_code == 200 and r.json()["weather"]["temperature"] == 17.4 and r.json()["error"] is None
|
||||||
|
assert ("signage.changed", [tv["id"]]) in sent
|
||||||
|
w = client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"]
|
||||||
|
assert w["place"] == "Kalavryta" and w["code"] == 2 and [d["max"] for d in w["days"]] == [19.0, 16.5] and w["units"] == "celsius"
|
||||||
|
# the internet goes: the last forecast stays while it is fresh, then the widget hides
|
||||||
|
internet["up"] = False
|
||||||
|
sent.clear()
|
||||||
|
assert asyncio.run(weather.refresh(db)) is False
|
||||||
|
assert client.get("/api/signage/weather", headers=owner_h).json()["error"] == "ConnectError"
|
||||||
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"] is not None
|
||||||
|
assert weather.current(db, now=time.time() + weather.STALE_S + 1) is None
|
||||||
|
assert err(client.get("/api/signage/weather/places?q=Patra", headers=owner_h)) == "signage.weather_offline"
|
||||||
|
# forgetting the place hides it at once
|
||||||
|
internet["up"] = True
|
||||||
|
client.delete("/api/signage/weather/place", headers=owner_h)
|
||||||
|
assert client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_fahrenheit_and_a_new_place(client, owner_h, internet):
|
||||||
|
client.put("/api/signage/weather/place", headers=owner_h, json={"name": "Patra", "latitude": 38.24, "longitude": 21.73, "units": "fahrenheit"})
|
||||||
|
assert "temperature_unit=fahrenheit" in internet["calls"][-1]
|
||||||
|
assert client.put("/api/signage/weather/place", headers=owner_h, json={"name": "X", "latitude": 99, "longitude": 0}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_who_may(client, make_user, login):
|
||||||
|
waiter = login(make_user(role="waiter"))
|
||||||
|
assert client.put("/api/signage/message", headers=waiter, json={"text": "x"}).status_code == 403
|
||||||
|
assert client.get("/api/signage/weather", headers=waiter).status_code == 403
|
||||||
@@ -146,6 +146,7 @@
|
|||||||
"not_a_screen": "Η συσκευή {{device_id}} δεν είναι οθόνη προβολής.",
|
"not_a_screen": "Η συσκευή {{device_id}} δεν είναι οθόνη προβολής.",
|
||||||
"not_a_video": "Διαλέξτε βίντεο για αυτή τη διαφάνεια.",
|
"not_a_video": "Διαλέξτε βίντεο για αυτή τη διαφάνεια.",
|
||||||
"content_invalid": "Μια ρύθμιση της διαφάνειας δεν είναι έγκυρη ({{field}}: {{reason}}).",
|
"content_invalid": "Μια ρύθμιση της διαφάνειας δεν είναι έγκυρη ({{field}}: {{reason}}).",
|
||||||
"order_mismatch": "Η λίστα άλλαξε στο μεταξύ. Φορτώστε τη ξανά και δοκιμάστε πάλι."
|
"order_mismatch": "Η λίστα άλλαξε στο μεταξύ. Φορτώστε τη ξανά και δοκιμάστε πάλι.",
|
||||||
|
"weather_offline": "Η υπηρεσία καιρού δεν είναι διαθέσιμη: ο διακομιστής του καταστήματος χρειάζεται internet γι' αυτήν."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -146,6 +146,7 @@
|
|||||||
"not_a_screen": "Device {{device_id}} isn't a signage screen.",
|
"not_a_screen": "Device {{device_id}} isn't a signage screen.",
|
||||||
"not_a_video": "Pick a video for this slide.",
|
"not_a_video": "Pick a video for this slide.",
|
||||||
"content_invalid": "This slide's setting isn't valid ({{field}}: {{reason}}).",
|
"content_invalid": "This slide's setting isn't valid ({{field}}: {{reason}}).",
|
||||||
"order_mismatch": "The playlist changed in the meantime. Reload it and try again."
|
"order_mismatch": "The playlist changed in the meantime. Reload it and try again.",
|
||||||
|
"weather_offline": "The weather service can't be reached: the venue's server needs internet for it."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user