feat(signage): new widgets (shape, scrolling text, countdown, opening hours, Wi-Fi, contact details); the venue's opening hours on the server, edited on the Schedule page

Shapes: rectangle, circle, triangle, polygon, star or own corners, fill or gradient,
border. Countdown: to a time every day or a date, from now / a span before / a set
time, in venue time (the slide shows what is left right now). Opening hours, Wi-Fi
(with a join-the-network code) and contact details read the venue's identity and
opening hours (GET/PUT /api/identity/hours; Schedule -> Opening hours, shaded on its
timeline); the editor warns with a link when they're missing. Plan 6R.15, F-112.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 13:24:54 +02:00
co-authored by Claude Opus 5.5
parent 2a38602d45
commit f26e51273c
22 changed files with 1002 additions and 46 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -33,6 +33,7 @@ MODULE = Module(
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'), SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'), SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'),
SettingDef('venue.name', '', 'Venue name shown on screens and tickets.', type='str'), SettingDef('venue.name', '', 'Venue name shown on screens and tickets.', type='str'),
SettingDef('venue.opening_hours', '{}', 'Opening hours, Monday first (6R.15; JSON {days, note}; edited on the Schedule page, shown by signage).', type='json'),
SettingDef('venue.identity', '{}', "The venue's identity (6R.14): slogan, colours, logos, Wi-Fi, contact details (JSON; Settings > Identity, routers/identity.py).", type='json'), SettingDef('venue.identity', '{}', "The venue's identity (6R.14): slogan, colours, logos, Wi-Fi, contact details (JSON; Settings > Identity, routers/identity.py).", type='json'),
SettingDef('venue.theme', 'amber', "Accent colour of the staff apps (the waiter's phones first, plan step 4.6): 'teal' | 'amber' | 'blue' | 'violet' | 'rose'", type='enum', choices=('teal', 'amber', 'blue', 'violet', 'rose')), SettingDef('venue.theme', 'amber', "Accent colour of the staff apps (the waiter's phones first, plan step 4.6): 'teal' | 'amber' | 'blue' | 'violet' | 'rose'", type='enum', choices=('teal', 'amber', 'blue', 'violet', 'rose')),
SettingDef('venue.type', '', 'Kind of venue (restaurant, cafe, bar...), chosen in the setup wizard.', type='str'), SettingDef('venue.type', '', 'Kind of venue (restaurant, cafe, bar...), chosen in the setup wizard.', type='str'),
+59 -1
View File
@@ -2,6 +2,8 @@
GET /api/identity its name, slogan, colours, logos, Wi-Fi and contact details (anyone who opens the manager) GET /api/identity its name, slogan, colours, logos, Wi-Fi and contact details (anyone who opens the manager)
PUT /api/identity all of it at once (core.settings.manage) PUT /api/identity all of it at once (core.settings.manage)
GET /api/identity/hours the opening hours, Monday first (6R.15)
PUT /api/identity/hours {days: [[{from, to}], … 7], note} (core.settings.manage or core.staff.manage: the Schedule page)
Stored as the settings `venue.name` (the name everything already shows) and `venue.identity` (JSON, Stored as the settings `venue.name` (the name everything already shows) and `venue.identity` (JSON,
the rest). Logos are media library pictures, protected while used. Signage screens get it with the rest). Logos are media library pictures, protected while used. Signage screens get it with
@@ -17,12 +19,14 @@ from fastapi import APIRouter, Depends
from pydantic import BaseModel, ConfigDict, Field, field_validator from pydantic import BaseModel, ConfigDict, Field, field_validator
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from core.access.deps import require from core.access.deps import require, require_any
from core.errors import XeniaError from core.errors import XeniaError
from database import get_db from database import get_db
router = APIRouter() router = APIRouter()
KEY = "venue.identity" KEY = "venue.identity"
HOURS = "venue.opening_hours"
TIME = r"^([01]\d|2[0-3]):[0-5]\d$"
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$" HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"
LOGOS = ("main", "light", "dark", "icon") LOGOS = ("main", "light", "dark", "icon")
@@ -191,3 +195,57 @@ def put_identity(body: IdentityBody, db: Session = Depends(get_db), user=Depends
except Exception: except Exception:
pass # signage not installed / off: nothing to tell pass # signage not installed / off: nothing to tell
return identity_out(db) return identity_out(db)
# ── opening hours (6R.15): edited on the Schedule page, shown by signage's opening hours widget ──
class Span(_Strict):
"""Open from … to … (venue time; `to` before `from` passes midnight)."""
from_: str = Field(alias="from", pattern=TIME)
to: str = Field(pattern=TIME)
model_config = ConfigDict(extra="forbid", populate_by_name=True)
class Hours(_Strict):
days: List[List[Span]] = Field(default_factory=lambda: [[] for _ in range(7)]) # Monday first; [] = closed
note: Optional[str] = Field(default=None, max_length=120) # "Closed on holidays"
@field_validator("days")
@classmethod
def _seven(cls, v):
if len(v) != 7 or any(len(d) > 3 for d in v):
raise ValueError("seven days, up to three spans a day")
return v
@field_validator("note")
@classmethod
def _note(cls, v):
return _text(v, 120)
def hours_out(db) -> dict:
"""{days: [[{from, to}]…7], note, set}: `set` false while no day has hours."""
try:
h = Hours(**json.loads(_setting(db, HOURS) or "{}"))
except Exception:
h = Hours()
days = [[{"from": x.from_, "to": x.to} for x in d] for d in h.days]
return {"days": days, "note": h.note, "set": any(days)}
@router.get("/hours")
def get_hours(db: Session = Depends(get_db), user=Depends(require("core.dashboard.access"))):
return hours_out(db)
@router.put("/hours")
def put_hours(body: Hours, db: Session = Depends(get_db), user=Depends(require_any("core.settings.manage", "core.staff.manage"))):
days = [[{"from": x.from_, "to": x.to} for x in sorted(d, key=lambda x: x.from_)] for d in body.days]
_save(db, HOURS, json.dumps({"days": days, "note": body.note}, ensure_ascii=False))
db.commit()
try:
from routers.signage import tell_all_screens
tell_all_screens(db)
except Exception:
pass
return hours_out(db)
+39 -4
View File
@@ -82,7 +82,10 @@ class Background(_Strict):
fit: Literal["cover", "contain"] = "cover" fit: Literal["cover", "contain"] = "cover"
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack"] WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack",
"shape", "ticker", "countdown", "hours", "wifi", "contact"] # 6R.15
WHEN = r"^(\d{4}-\d{2}-\d{2}T)?([01]\d|2[0-3]):[0-5]\d$" # a countdown's moment: "HH:MM" (every day) or "YYYY-MM-DDTHH:MM"
ContactKey = Literal["phone", "phone2", "email", "address", "website", "google", "facebook", "instagram", "tiktok", "tripadvisor", "whatsapp", "viber"]
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"] Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
@@ -251,7 +254,7 @@ class Widget(_Strict):
box: Optional[Box] = None # position "custom" box: Optional[Box] = None # position "custom"
align: Literal["auto", "left", "center", "right"] = "auto" # inside its place; auto: by its corner / box align: Literal["auto", "left", "center", "right"] = "auto" # inside its place; auto: by its corner / box
media_id: Optional[int] = None # logo: a picture 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 text: Optional[str] = Field(default=None, max_length=500) # message: this text instead of the venue's; text, ticker, a countdown's / hours' title
date_style: Literal["short", "long"] = "long" date_style: Literal["short", "long"] = "long"
clock_seconds: bool = False clock_seconds: bool = False
qr_target: Literal["ordering", "menu", "custom"] = "ordering" qr_target: Literal["ordering", "menu", "custom"] = "ordering"
@@ -274,6 +277,37 @@ class Widget(_Strict):
qr_background: Optional[str] = Field(default=None, pattern=HEX) # around them (default white) qr_background: Optional[str] = Field(default=None, pattern=HEX) # around them (default white)
direction: Literal["row", "column"] = "row" # stack: side by side / one over the other direction: Literal["row", "column"] = "row" # stack: side by side / one over the other
cells: List[Cell] = Field(default_factory=list, max_length=6) cells: List[Cell] = Field(default_factory=list, max_length=6)
# a shape (6R.15): in its box; a fill (flat, or a gradient to fill_to at fill_angle), a border
shape: Literal["rectangle", "circle", "triangle", "polygon", "star", "custom"] = "rectangle"
shape_sides: int = Field(default=6, ge=3, le=12) # polygon: its sides; star: its points
shape_inner: int = Field(default=45, ge=15, le=90) # star: its inner corners, % of the outer
shape_points: Optional[str] = Field(default=None, max_length=600) # custom: "x,y x,y …" in % of its box
fill: Optional[str] = Field(default=None, pattern=HEX)
fill_to: Optional[str] = Field(default=None, pattern=HEX) # None: one colour
fill_angle: int = Field(default=180, ge=0, le=359)
stroke: Optional[str] = Field(default=None, pattern=HEX)
stroke_width: int = Field(default=0, ge=0, le=20) # steps of ½ % of the shape's shorter side
radius: int = Field(default=0, ge=0, le=50) # rectangle: rounded corners, % of its shorter side
# scrolling text
ticker_speed: int = Field(default=4, ge=1, le=10)
ticker_direction: Literal["left", "right"] = "left"
# a countdown: to a time every day or a date and time (venue time); it counts from now, from a span
# before, or from a time; before that it shows the whole span or nothing; at the end a text or nothing
countdown_to: Optional[str] = Field(default=None, pattern=WHEN)
countdown_start: Literal["now", "before", "at"] = "now"
countdown_before: int = Field(default=120, ge=1, le=10080) # minutes
countdown_at: Optional[str] = Field(default=None, pattern=WHEN)
countdown_waiting: Literal["full", "hide"] = "full"
countdown_done: Optional[str] = Field(default=None, max_length=80)
countdown_done_hide: bool = False
# the opening hours (from the Schedule page): the week, or today only; days with the same hours on one line
hours_style: Literal["week", "today"] = "week"
hours_group: bool = True
# Wi-Fi (from the identity): its code to join, the password written out
wifi_qr: bool = True
wifi_password: bool = True
# contact details (from the identity): which, in this order
contact_fields: List[ContactKey] = Field(default_factory=lambda: ["phone", "website", "instagram"], max_length=12)
@model_validator(mode="after") @model_validator(mode="after")
def _place(self): def _place(self):
@@ -1491,12 +1525,13 @@ def _venue(db) -> dict:
it: no internet, no place, too old) and its badges (owner review 5); its identity (6R.14: slogan, it: no internet, no place, too old) and its badges (owner review 5); its identity (6R.14: slogan,
colours, logos, Wi-Fi, contact) and time zone.""" colours, logos, Wi-Fi, contact) and time zone."""
from core.timeutil import venue_tz from core.timeutil import venue_tz
from routers.identity import identity_out from routers.identity import hours_out, identity_out
from services import signage_badges, weather from services import signage_badges, weather
ident = identity_out(db) ident = identity_out(db)
ident.pop("name", None) ident.pop("name", None)
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None,
"weather": weather.current(db), "badges": signage_badges.load(db), "identity": ident, "timezone": venue_tz().key} "weather": weather.current(db), "badges": signage_badges.load(db), "identity": ident, "timezone": venue_tz().key,
"hours": hours_out(db)}
class SlidePreviewBody(BaseModel): class SlidePreviewBody(BaseModel):
+39
View File
@@ -45,3 +45,42 @@ def test_checked(client, owner_h):
assert err(client.put("/api/identity", headers=owner_h, json={"logos": {"main": 99999}})) == "media.not_found" assert err(client.put("/api/identity", headers=owner_h, json={"logos": {"main": 99999}})) == "media.not_found"
too_many = [{"name": f"c{i}", "colour": "#000000"} for i in range(13)] too_many = [{"name": f"c{i}", "colour": "#000000"} for i in range(13)]
assert client.put("/api/identity", headers=owner_h, json={"colours": too_many}).status_code == 422 assert client.put("/api/identity", headers=owner_h, json={"colours": too_many}).status_code == 422
def test_opening_hours(client, owner_h, screens, sent):
assert client.get("/api/identity/hours", headers=owner_h).json() == {"days": [[]] * 7, "note": None, "set": False}
days = [[{"from": "18:00", "to": "23:00"}, {"from": "12:00", "to": "15:00"}]] * 5 + [[{"from": "12:00", "to": "01:00"}], []]
sent.clear()
r = client.put("/api/identity/hours", headers=owner_h, json={"days": days, "note": " Closed on holidays "})
assert r.status_code == 200, r.text
j = r.json()
assert j["set"] is True and j["days"][0] == [{"from": "12:00", "to": "15:00"}, {"from": "18:00", "to": "23:00"}]
assert j["days"][6] == [] and j["note"] == "Closed on holidays"
assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent
assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]["hours"]["days"][5] == [{"from": "12:00", "to": "01:00"}]
assert client.put("/api/identity/hours", headers=owner_h, json={"days": [[]] * 6}).status_code == 422
assert client.put("/api/identity/hours", headers=owner_h, json={"days": [[{"from": "25:00", "to": "01:00"}]] + [[]] * 6}).status_code == 422
def test_new_widgets_are_typed(client, owner_h):
from tests.test_signage import playlist, slide
p = playlist(client, owner_h)
widgets = [
{"kind": "shape", "position": "custom", "box": {"x": 10, "y": 10, "w": 20, "h": 20}, "shape": "star", "shape_sides": 5, "fill": "#ff0000", "fill_to": "#0000ff"},
{"kind": "ticker", "position": "bottom-bar", "text": "Fresh fish today " * 10, "ticker_speed": 7},
{"kind": "countdown", "countdown_to": "17:00", "countdown_start": "before", "countdown_before": 120, "countdown_done": "Happy hour!"},
{"kind": "countdown", "countdown_to": "2026-12-31T23:59"},
{"kind": "hours", "hours_style": "today"},
{"kind": "wifi", "wifi_qr": False},
{"kind": "contact", "contact_fields": ["phone", "instagram"]},
]
s = slide(client, owner_h, p["id"], "blank", content={"widgets": widgets})
got = s["content"]["widgets"]
assert [w["kind"] for w in got] == [w["kind"] for w in widgets]
assert got[0]["shape"] == "star" and got[2]["countdown_before"] == 120 and got[6]["contact_fields"] == ["phone", "instagram"]
bad = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h,
json={"kind": "blank", "content": {"widgets": [{"kind": "countdown", "countdown_to": "5pm"}]}})
assert err(bad) == "signage.content_invalid"
bad = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h,
json={"kind": "blank", "content": {"widgets": [{"kind": "contact", "contact_fields": ["fax"]}]}})
assert err(bad) == "signage.content_invalid"
@@ -0,0 +1,87 @@
// The venue's opening hours (6R.15, owner 2026-11-22): each day closed or open in up to three spans
// (a span may pass midnight), and a note. Kept on the server (PUT /api/identity/hours): the
// schedule's timeline shades them and signage's opening hours widget shows them.
import { useState } from 'react'
import toast from 'react-hot-toast'
import { useQueryClient } from '@tanstack/react-query'
import { Copy, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { HOURS_KEY, useHours } from '../../shell/useIdentity'
import { hoursValid } from './scheduleLogic'
const MONDAY = '2026-11-16'
export default function OpeningHoursDialog({ onClose }) {
const { data } = useHours()
return data ? <HoursForm saved={data} onClose={onClose} /> : <Dialog open size="md" onClose={onClose}><div className="py-8 flex justify-center"><Spinner /></div></Dialog>
}
function HoursForm({ saved, onClose }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const qc = useQueryClient()
const [days, setDays] = useState(() => saved.days.map(d => d.map(x => ({ ...x }))))
const [note, setNote] = useState(saved.note || '')
const [busy, setBusy] = useState(false)
const dayName = i => fmt.formatDateTime(`2026-11-${16 + i}T12:00:00Z`, { weekday: 'long' })
const setDay = (i, spans) => setDays(ds => ds.map((d, j) => (j === i ? spans : d)))
const ok = hoursValid(days)
const save = async () => {
setBusy(true)
try {
const { data } = await client.put('/api/identity/hours', { days, note: note.trim() || null })
qc.setQueryData(HOURS_KEY, data)
toast.success(t('schedule.openingSaved'))
onClose()
} catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
return (
<Dialog open size="lg" onClose={onClose} title={t('schedule.openingTitle')} description={t('schedule.openingIntro')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('schedule.back')}</Button>
<Button loading={busy} disabled={!ok} onClick={save} data-testid="opening-save">{t('schedule.save')}</Button>
</>}>
<div className="grid gap-2" data-testid="opening-hours" data-monday={MONDAY}>
{days.map((spans, i) => (
<div key={i} className="grid gap-2 sm:grid-cols-[9rem_minmax(0,1fr)] items-start border-b border-line pb-2" data-testid="opening-day" data-day={i}>
<span className="text-body font-medium text-ink capitalize pt-2.5">{dayName(i)}</span>
<div className="grid gap-1.5">
{spans.length === 0 && <span className="text-label text-ink-3 pt-2.5">{t('schedule.closedDay')}</span>}
{spans.map((x, k) => (
<div key={k} className="flex items-center gap-2">
<Input type="time" value={x.from} aria-label={t('schedule.opens')} className="w-32" data-testid="opening-from"
onChange={e => setDay(i, spans.map((y, n) => (n === k ? { ...y, from: e.target.value } : y)))} />
<span className="text-ink-3">–</span>
<Input type="time" value={x.to} aria-label={t('schedule.closes')} className="w-32" data-testid="opening-to"
onChange={e => setDay(i, spans.map((y, n) => (n === k ? { ...y, to: e.target.value } : y)))} />
<IconButton size="sm" tone="danger" label={t('schedule.removeSpan')} onClick={() => setDay(i, spans.filter((_, n) => n !== k))}><Trash2 size={15} /></IconButton>
</div>
))}
<div className="flex flex-wrap gap-1.5">
{spans.length < 3 && (
<Button size="sm" variant="secondary" icon={<Plus size={14} />} data-testid="opening-add"
onClick={() => setDay(i, [...spans, spans.length ? { from: '18:00', to: '23:00' } : { from: '12:00', to: '23:00' }])}>
{t(spans.length ? 'schedule.addSpan' : 'schedule.openThisDay')}
</Button>
)}
{i === 0 && (
<Button size="sm" variant="ghost" icon={<Copy size={14} />} data-testid="opening-copy" onClick={() => setDays(ds => ds.map(() => spans.map(x => ({ ...x }))))}>
{t('schedule.copyToAll')}
</Button>
)}
</div>
</div>
</div>
))}
<Field label={t('schedule.openingNote')} hint={t('schedule.openingNoteHint')}>
<Input value={note} maxLength={120} onChange={e => setNote(e.target.value)} />
</Field>
{!ok && <p className="text-label text-danger-ink">{t('schedule.openingInvalid')}</p>}
</div>
</Dialog>
)
}
@@ -7,7 +7,7 @@
import { useMemo, useState } from 'react' import { useMemo, useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query' import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { ChevronLeft, ChevronRight, Plus, Settings2 } from 'lucide-react' import { ChevronLeft, ChevronRight, Clock, Plus, Settings2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, IconButton, Page, PageHeader, Segmented, Spinner, cx } from '@xenia/ui' import { Button, EmptyState, IconButton, Page, PageHeader, Segmented, Spinner, cx } from '@xenia/ui'
@@ -15,7 +15,10 @@ import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import ShiftDialog from './ShiftDialog' import ShiftDialog from './ShiftDialog'
import ViewDialog from './ViewDialog' import ViewDialog from './ViewDialog'
import { addDays, gridOf, hourMarks, inOpening, loadView, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals } from './scheduleLogic' import OpeningHoursDialog from './OpeningHoursDialog'
import { useHours } from '../../shell/useIdentity'
import { useSearchParams } from 'react-router-dom'
import { addDays, gridOf, hourMarks, inSpans, weekdayOf, loadView, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals } from './scheduleLogic'
const STATE = { const STATE = {
planned: 'border-info bg-info-soft text-info-ink', planned: 'border-info bg-info-soft text-info-ink',
@@ -33,6 +36,10 @@ export default function SchedulePage() {
const [start, setStart] = useState(() => weekStartOf(today, loadView().mondayFirst)) const [start, setStart] = useState(() => weekStartOf(today, loadView().mondayFirst))
const [editing, setEditing] = useState(null) // { date, userId, shift? } const [editing, setEditing] = useState(null) // { date, userId, shift? }
const [settings, setSettings] = useState(false) const [settings, setSettings] = useState(false)
const [params, setParams] = useSearchParams()
const hoursOpen = params.get('hours') === '1'
const setHoursOpen = on => setParams(p => { const n = new URLSearchParams(p); if (on) n.set('hours', '1'); else n.delete('hours'); return n }, { replace: true })
const { data: hours } = useHours()
const setView = next => { setViewState(next); saveView(next) } const setView = next => { setViewState(next); saveView(next) }
const { data, isPending } = useLiveQuery({ const { data, isPending } = useLiveQuery({
@@ -67,6 +74,7 @@ export default function SchedulePage() {
<Button variant="secondary" onClick={() => setStart(weekStartOf(today, view.mondayFirst))}>{t('schedule.thisWeek')}</Button> <Button variant="secondary" onClick={() => setStart(weekStartOf(today, view.mondayFirst))}>{t('schedule.thisWeek')}</Button>
<IconButton variant="secondary" label={t('schedule.next')} onClick={() => setStart(s => addDays(s, 7))} data-testid="schedule-next"><ChevronRight size={16} /></IconButton> <IconButton variant="secondary" label={t('schedule.next')} onClick={() => setStart(s => addDays(s, 7))} data-testid="schedule-next"><ChevronRight size={16} /></IconButton>
</span> </span>
<Button variant="secondary" icon={<Clock size={16} />} onClick={() => setHoursOpen(true)} data-testid="schedule-opening">{t('schedule.openingButton')}</Button>
<IconButton variant="secondary" label={t('schedule.settings')} onClick={() => setSettings(true)}><Settings2 size={16} /></IconButton> <IconButton variant="secondary" label={t('schedule.settings')} onClick={() => setSettings(true)}><Settings2 size={16} /></IconButton>
</>} /> </>} />
@@ -121,7 +129,7 @@ export default function SchedulePage() {
</table> </table>
</div> </div>
) : ( ) : (
<HoursView days={days} today={today} people={people} scheduled={scheduled} view={view} dayLabel={dayLabel} dateLabel={dateLabel} <HoursView days={days} today={today} people={people} scheduled={scheduled} view={view} hours={hours} dayLabel={dayLabel} dateLabel={dateLabel}
onAdd={d => setEditing({ date: d, userId: null })} onOpen={(d, s) => setEditing({ date: d, userId: s.user_id, shift: s })} /> onAdd={d => setEditing({ date: d, userId: null })} onOpen={(d, s) => setEditing({ date: d, userId: s.user_id, shift: s })} />
)} )}
@@ -134,13 +142,14 @@ export default function SchedulePage() {
{editing && <ShiftDialog people={people} scheduled={scheduled} {...editing} {editing && <ShiftDialog people={people} scheduled={scheduled} {...editing}
onClose={() => setEditing(null)} onDelete={id => { remove.mutate(id); setEditing(null) }} onClose={() => setEditing(null)} onDelete={id => { remove.mutate(id); setEditing(null) }}
onSaved={() => { setEditing(null); qc.invalidateQueries({ queryKey: ['schedule-week'] }) }} />} onSaved={() => { setEditing(null); qc.invalidateQueries({ queryKey: ['schedule-week'] }) }} />}
{hoursOpen && <OpeningHoursDialog onClose={() => setHoursOpen(false)} />}
{settings && <ViewDialog view={view} onClose={() => setSettings(false)} {settings && <ViewDialog view={view} onClose={() => setSettings(false)}
onSave={next => { if (next.mondayFirst !== view.mondayFirst) setStart(weekStartOf(start, next.mondayFirst)); setView(next); setSettings(false) }} />} onSave={next => { if (next.mondayFirst !== view.mondayFirst) setStart(weekStartOf(start, next.mondayFirst)); setView(next); setSettings(false) }} />}
</Page> </Page>
) )
} }
function HoursView({ days, today, people, scheduled, view, dayLabel, dateLabel, onAdd, onOpen }) { function HoursView({ days, today, people, scheduled, view, hours, dayLabel, dateLabel, onAdd, onOpen }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const marks = hourMarks(view.firstHour) const marks = hourMarks(view.firstHour)
const nameOf = id => people.find(p => p.id === id)?.nickname || people.find(p => p.id === id)?.name || `#${id}` const nameOf = id => people.find(p => p.id === id)?.nickname || people.find(p => p.id === id)?.name || `#${id}`
@@ -160,7 +169,7 @@ function HoursView({ days, today, people, scheduled, view, dayLabel, dateLabel,
</div> </div>
<div className="relative w-full cursor-copy" style={{ height: 24 * HOUR_PX }} onClick={() => onAdd(d)} title={t('schedule.addOn', { day: dayLabel(d) })} data-testid="schedule-day"> <div className="relative w-full cursor-copy" style={{ height: 24 * HOUR_PX }} onClick={() => onAdd(d)} title={t('schedule.addOn', { day: dayLabel(d) })} data-testid="schedule-day">
{marks.map((h, i) => ( {marks.map((h, i) => (
<span key={h} className={cx('absolute inset-x-0 border-t', h === 0 ? 'border-info' : 'border-line', inOpening(h, view.open, view.close) && 'bg-accent-soft/40')} <span key={h} className={cx('absolute inset-x-0 border-t', h === 0 ? 'border-info' : 'border-line', inSpans(h, hours?.days?.[weekdayOf(d)]) && 'bg-accent-soft/40')}
style={{ top: i * HOUR_PX, height: HOUR_PX }} aria-hidden="true" /> style={{ top: i * HOUR_PX, height: HOUR_PX }} aria-hidden="true" />
))} ))}
{shifts.map(s => { {shifts.map(s => {
@@ -1,8 +1,8 @@
// How this browser shows the schedule (plan step 6.11): the week's first day, the timeline's // How this browser shows the schedule (plan step 6.11): the week's first day, the timeline's
// first hour, the opening hours shaded on it. Nothing here changes the schedule itself. // first hour. Nothing here changes the schedule itself (the opening hours are the venue's: OpeningHoursDialog).
import { useState } from 'react' import { useState } from 'react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select } from '@xenia/ui' import { Button, Dialog, Field, Select } from '@xenia/ui'
export default function ViewDialog({ view, onClose, onSave }) { export default function ViewDialog({ view, onClose, onSave }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -23,10 +23,6 @@ export default function ViewDialog({ view, onClose, onSave }) {
<Select value={String(v.firstHour)} onChange={e => set('firstHour', Number(e.target.value))} <Select value={String(v.firstHour)} onChange={e => set('firstHour', Number(e.target.value))}
options={Array.from({ length: 24 }, (_, h) => ({ value: String(h), label: `${String(h).padStart(2, '0')}:00` }))} /> options={Array.from({ length: 24 }, (_, h) => ({ value: String(h), label: `${String(h).padStart(2, '0')}:00` }))} />
</Field> </Field>
<div className="grid grid-cols-2 gap-3">
<Field label={t('schedule.opens')} hint={t('schedule.openingHint')}><Input type="time" value={v.open} onChange={e => set('open', e.target.value)} /></Field>
<Field label={t('schedule.closes')}><Input type="time" value={v.close} onChange={e => set('close', e.target.value)} /></Field>
</div>
</div> </div>
</Dialog> </Dialog>
) )
@@ -100,8 +100,17 @@ export function inOpening(hour, open, close) {
return a <= b ? hour >= a && hour < b : hour >= a || hour < b return a <= b ? hour >= a && hour < b : hour >= a || hour < b
} }
/** Is an hour mark inside any of a day's opening spans ([{from, to}], 6R.15: the venue's hours, kept on the server)? */
export const inSpans = (hour, spans) => (spans || []).some(x => inOpening(hour, x.from, x.to))
/** Monday 0 … Sunday 6 of a "YYYY-MM-DD". */
export const weekdayOf = d => (new Date(`${d}T12:00:00Z`).getUTCDay() + 6) % 7
/** Opening hours that can be saved: every span has both times and they differ. */
export const hoursValid = days => days.every(d => d.every(x => /^\d\d:\d\d$/.test(x.from || '') && /^\d\d:\d\d$/.test(x.to || '') && x.from !== x.to))
/** The schedule's view settings kept in this browser (a per-viewer convenience). */ /** The schedule's view settings kept in this browser (a per-viewer convenience). */
export const VIEW_DEFAULTS = { view: 'people', mondayFirst: true, firstHour: 6, open: '', close: '' } export const VIEW_DEFAULTS = { view: 'people', mondayFirst: true, firstHour: 6 }
const VIEW_KEY = 'xenia:schedule:view' const VIEW_KEY = 'xenia:schedule:view'
export function loadView(storage = globalThis.localStorage) { export function loadView(storage = globalThis.localStorage) {
try { return { ...VIEW_DEFAULTS, ...JSON.parse(storage?.getItem(VIEW_KEY) || '{}') } } catch { return { ...VIEW_DEFAULTS } } try { return { ...VIEW_DEFAULTS, ...JSON.parse(storage?.getItem(VIEW_KEY) || '{}') } } catch { return { ...VIEW_DEFAULTS } }
@@ -0,0 +1,173 @@
// The settings of the widgets added in 6R.15 (owner 2026-11-22): a shape, a scrolling text, a
// countdown, the opening hours, the guests' Wi-Fi and the contact details. The last three read the
// venue (Settings → Identity, the Schedule page's opening hours): when that is missing the card says
// so with a link to where it is set. Used by WidgetsEditor (its row and the part under it).
import { Link } from 'react-router-dom'
import { useTranslation } from '@xenia/i18n'
import { ColourField, Dropdown, Field, Input, Notice, NumberInput, Segmented, Slider, Switch } from '@xenia/ui'
import { useHours, useIdentity } from '../../shell/useIdentity'
import { CONTACT_KEYS, WIDGET_COLOURS } from './signageLogic'
const SHAPES = ['rectangle', 'circle', 'triangle', 'polygon', 'star', 'custom']
const isDate = v => !!v && v.length > 5
/** On the widget's row (where / size / alignment): its main choices. */
export function MoreInlineFields({ w, set }) {
const { t } = useTranslation('manager')
const k = 'signage.widgets'
if (w.kind === 'shape') {
return (<>
<Field label={t(`${k}.shape.kind`)}>
<Dropdown value={w.shape || 'rectangle'} onChange={shape => set({ shape })} data-testid="signage-widget-shape"
options={SHAPES.map(x => ({ value: x, label: t(`${k}.shape.kinds.${x}`) }))} />
</Field>
{(w.shape === 'polygon' || w.shape === 'star') && (
<Field label={t(w.shape === 'star' ? `${k}.shape.points` : `${k}.shape.sides`)}>
<NumberInput value={w.shape_sides ?? 6} min={3} max={12} onChange={v => set({ shape_sides: v ?? 3 })} data-testid="signage-widget-shape-sides" />
</Field>
)}
</>)
}
if (w.kind === 'ticker') {
return (<>
<Field label={t(`${k}.ticker.text`)} className="col-span-2">
<Input value={w.text || ''} maxLength={500} onChange={e => set({ text: e.target.value || null })} data-testid="signage-widget-ticker-text" />
</Field>
<Field label={t(`${k}.ticker.direction`)}>
<Segmented fill value={w.ticker_direction || 'left'} onChange={ticker_direction => set({ ticker_direction })}
options={['left', 'right'].map(v => ({ value: v, label: t(`${k}.ticker.directions.${v}`) }))} />
</Field>
</>)
}
if (w.kind === 'countdown') {
const to = w.countdown_to || ''
return (<>
<Field label={t(`${k}.countdown.title`)}>
<Input value={w.text || ''} maxLength={80} placeholder={t(`${k}.countdown.titlePlaceholder`)} onChange={e => set({ text: e.target.value || null })} />
</Field>
<Field label={t(`${k}.countdown.ends`)}>
<Segmented fill value={isDate(to) ? 'date' : 'daily'} data-testid="signage-widget-countdown-mode"
onChange={m => set({ countdown_to: m === 'date' ? `${new Date().toISOString().slice(0, 10)}T${to.slice(-5) || '17:00'}` : (to.slice(-5) || '17:00') })}
options={['daily', 'date'].map(v => ({ value: v, label: t(`${k}.countdown.modes.${v}`) }))} />
</Field>
<Field label={t(isDate(to) ? `${k}.countdown.at` : `${k}.countdown.everyDayAt`)}>
<Input type={isDate(to) ? 'datetime-local' : 'time'} value={to} data-testid="signage-widget-countdown-to"
onChange={e => set({ countdown_to: e.target.value ? e.target.value.slice(0, isDate(to) ? 16 : 5) : null })} />
</Field>
</>)
}
if (w.kind === 'hours') {
return (<>
<Field label={t(`${k}.hours.style`)}>
<Segmented fill value={w.hours_style || 'week'} onChange={hours_style => set({ hours_style })} data-testid="signage-widget-hours-style"
options={['week', 'today'].map(v => ({ value: v, label: t(`${k}.hours.styles.${v}`) }))} />
</Field>
<Field label={t(`${k}.countdown.title`)}>
<Input value={w.text || ''} maxLength={80} placeholder={t(`${k}.hours.titlePlaceholder`)} onChange={e => set({ text: e.target.value || null })} />
</Field>
</>)
}
if (w.kind === 'wifi') {
return (
<Field label={t(`${k}.wifi.shows`)} className="col-span-2">
<div className="flex gap-2 flex-wrap">
<Switch boxed className="h-control" checked={w.wifi_qr !== false} onChange={on => set({ wifi_qr: on })} label={t(`${k}.wifi.qr`)} data-testid="signage-widget-wifi-qr" />
<Switch boxed className="h-control" checked={w.wifi_password !== false} onChange={on => set({ wifi_password: on })} label={t(`${k}.wifi.password`)} />
</div>
</Field>
)
}
if (w.kind === 'contact') {
return (
<Field label={t(`${k}.contact.shows`)} className="col-span-2">
<Dropdown multiple value={w.contact_fields || ['phone', 'website', 'instagram']} onChange={contact_fields => set({ contact_fields })} data-testid="signage-widget-contact-fields"
allLabel={t(`${k}.contact.none`)} options={CONTACT_KEYS.map(x => ({ value: x, label: t(`identity.contact.${x}`) }))} />
</Field>
)
}
return null
}
/** Under the row: what needs more room, and what the venue still has to set. */
export function MoreBelowFields({ w, set }) {
const { t } = useTranslation('manager')
const { data: identity } = useIdentity()
const { data: hours } = useHours()
const k = 'signage.widgets'
if (w.kind === 'shape') {
return (
<div className="grid gap-4 items-end grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]">
{w.shape === 'custom' && (
<Field label={t(`${k}.shape.custom`)} hint={t(`${k}.shape.customHint`)} className="col-span-2">
<Input value={w.shape_points || ''} maxLength={600} placeholder="50,0 100,100 0,100" onChange={e => set({ shape_points: e.target.value || null })} data-testid="signage-widget-shape-points" />
</Field>
)}
<ColourField label={t(`${k}.shape.fill`)} value={w.fill || WIDGET_COLOURS.shape} onChange={fill => set({ fill })} testId="signage-widget-fill" />
<ColourField label={t(`${k}.shape.fillTo`)} value={w.fill_to || WIDGET_COLOURS.shape} onChange={fill_to => set({ fill_to })} testId="signage-widget-fill-to"
auto={{ label: t(`${k}.shape.oneColour`), on: !w.fill_to, pick: () => set({ fill_to: null }) }} />
{w.fill_to && <Slider label={t(`${k}.shape.angle`)} value={w.fill_angle ?? 180} min={0} max={345} step={15} suffix="°" onChange={fill_angle => set({ fill_angle })} />}
<ColourField label={t(`${k}.shape.stroke`)} value={w.stroke || WIDGET_COLOURS.text} onChange={stroke => set({ stroke, stroke_width: w.stroke_width || 4 })} testId="signage-widget-stroke"
auto={{ label: t(`${k}.shape.noStroke`), on: !w.stroke || !w.stroke_width, pick: () => set({ stroke: null, stroke_width: 0 }) }} />
{w.stroke && w.stroke_width > 0 && <Slider label={t(`${k}.shape.strokeWidth`)} value={w.stroke_width} min={1} max={20} onChange={stroke_width => set({ stroke_width })} />}
{w.shape === 'star' && <Slider label={t(`${k}.shape.inner`)} value={w.shape_inner ?? 45} min={15} max={90} step={5} suffix="%" onChange={shape_inner => set({ shape_inner })} />}
{(w.shape || 'rectangle') === 'rectangle' && <Slider label={t(`${k}.shape.radius`)} value={w.radius || 0} min={0} max={50} suffix="%" onChange={radius => set({ radius })} />}
</div>
)
}
if (w.kind === 'ticker') {
return <Slider label={t(`${k}.ticker.speed`)} value={w.ticker_speed || 4} min={1} max={10} onChange={ticker_speed => set({ ticker_speed })} testId="signage-widget-ticker-speed" />
}
if (w.kind === 'countdown') {
const start = w.countdown_start || 'now'
return (
<div className="grid gap-4 items-end grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]">
<Field label={t(`${k}.countdown.starts`)}>
<Dropdown value={start} onChange={countdown_start => set({ countdown_start, ...(countdown_start === 'at' && !w.countdown_at ? { countdown_at: (w.countdown_to || '15:00').slice(-5) } : {}) })}
data-testid="signage-widget-countdown-start" options={['now', 'before', 'at'].map(v => ({ value: v, label: t(`${k}.countdown.startModes.${v}`) }))} />
</Field>
{start === 'before' && (
<Field label={t(`${k}.countdown.minutesBefore`)}>
<NumberInput value={w.countdown_before ?? 120} min={1} max={10080} suffix={t(`${k}.countdown.min`)} onChange={v => set({ countdown_before: v ?? 1 })} data-testid="signage-widget-countdown-before" />
</Field>
)}
{start === 'at' && (
<Field label={t(`${k}.countdown.startsAt`)}>
<Input type={isDate(w.countdown_to) ? 'datetime-local' : 'time'} value={w.countdown_at || ''} onChange={e => set({ countdown_at: e.target.value || null })} />
</Field>
)}
{start !== 'now' && (
<Field label={t(`${k}.countdown.waiting`)}>
<Dropdown value={w.countdown_waiting || 'full'} onChange={countdown_waiting => set({ countdown_waiting })}
options={['full', 'hide'].map(v => ({ value: v, label: t(`${k}.countdown.waitingModes.${v}`) }))} />
</Field>
)}
<Field label={t(`${k}.countdown.done`)} hint={t(`${k}.countdown.doneHint`)}>
<Input value={w.countdown_done || ''} maxLength={80} placeholder={t(`${k}.countdown.donePlaceholder`)} onChange={e => set({ countdown_done: e.target.value || null, countdown_done_hide: !e.target.value })} />
</Field>
</div>
)
}
if (w.kind === 'hours') {
return (
<div className="grid gap-3">
<Switch checked={w.hours_group !== false} onChange={hours_group => set({ hours_group })} label={t(`${k}.hours.group`)} description={t(`${k}.hours.groupHint`)} />
{hours && !hours.set && (
<Notice tone="warning" title={t(`${k}.hours.missing`)} data-testid="signage-widget-hours-missing">
<Link to="/management/schedule?hours=1" className="text-accent-ink font-medium underline">{t(`${k}.hours.setThem`)}</Link>
</Notice>
)}
</div>
)
}
if (w.kind === 'wifi' || w.kind === 'contact') {
const missing = w.kind === 'wifi' ? identity && !identity.wifi?.ssid : identity && !(w.contact_fields || ['phone', 'website', 'instagram']).some(x => identity.contact?.[x])
return missing
? (
<Notice tone="warning" title={t(`${k}.${w.kind}.missing`)} data-testid={`signage-widget-${w.kind}-missing`}>
<Link to="/settings?tab=identity" className="text-accent-ink font-medium underline">{t(`${k}.fromIdentity`)}</Link>
</Notice>
)
: <p className="text-caption text-ink-3 -mt-2">{t(`${k}.${w.kind}.hint`)} <Link to="/settings?tab=identity" className="text-accent-ink underline">{t(`${k}.fromIdentity`)}</Link></p>
}
return null
}
@@ -18,11 +18,14 @@
// has every setting a slide's widget has, aligned both ways in its place or moved and sized there on // has every setting a slide's widget has, aligned both ways in its place or moved and sized there on
// the preview (Custom); the message of the day changed from its widget. The picked widget is a path // the preview (Custom); the message of the day changed from its widget. The picked widget is a path
// ("2", "2.1.0": see WidgetCanvas). // ("2", "2.1.0": see WidgetCanvas).
// 6R.15 (owner 2026-11-22): a shape, a scrolling text, a countdown, the opening hours, Wi-Fi and contact
// details (MoreWidgetFields).
// Up to the venue's limit (10 recommended; Signage → Message & settings → Performance). // Up to the venue's limit (10 recommended; Signage → Message & settings → Performance).
import { Fragment, useEffect, useRef, useState } from 'react' import { Fragment, useEffect, useRef, useState } from 'react'
import { import {
AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart, ArrowDown, ArrowUp, Bold, Italic, Palette, RotateCcw, Underline, BookImage, CalendarDays, ChevronDown, Clock, CloudSun, Columns3, GripVertical, AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart, ArrowDown, ArrowUp, Bold, Italic, Palette, RotateCcw, Underline, BookImage, CalendarDays, ChevronDown, Clock, CloudSun, Columns3, GripVertical,
ImageIcon, LayoutList, MessageSquare, Plus, QrCode, Rows3, Store, Trash2, Type, UtensilsCrossed, ImageIcon, LayoutList, MessageSquare, Plus, QrCode, Rows3, Store, Trash2, Type, UtensilsCrossed,
CalendarClock, Contact, MoveHorizontal, Shapes, Timer, Wifi,
} from 'lucide-react' } from 'lucide-react'
import { cellWidgets, evenShares, setShare } from '@xenia/signage' import { cellWidgets, evenShares, setShare } from '@xenia/signage'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
@@ -31,12 +34,14 @@ import MessageOfTheDay from './MessageOfTheDay'
import { usePerformance } from './usePerformance' import { usePerformance } from './usePerformance'
import * as api from './signageApi' import * as api from './signageApi'
import MenuEditor from './MenuEditor' import MenuEditor from './MenuEditor'
import { MoreBelowFields as MoreBelow, MoreInlineFields as MoreInline } from './MoreWidgetFields'
import { MediaPick, Section } from './SignageFields' import { MediaPick, Section } from './SignageFields'
import { import {
CELL_KINDS, cellWidget, fillPlace, FONT_KEYS, WIDGET_COLOURS, moved, newWidget, pickedAfterMove, presetWidget, WEATHER_CHOICES, weatherChoice, WIDGET_KINDS, WIDGET_POSITIONS, CELL_KINDS, cellWidget, fillPlace, FONT_KEYS, WIDGET_COLOURS, moved, newWidget, pickedAfterMove, presetWidget, WEATHER_CHOICES, weatherChoice, WIDGET_KINDS, WIDGET_POSITIONS,
} from './signageLogic' } from './signageLogic'
const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, text: Type, qr: QrCode, weather: CloudSun, menu: UtensilsCrossed, hstack: Columns3, vstack: Rows3 } const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, text: Type, qr: QrCode, weather: CloudSun, menu: UtensilsCrossed, hstack: Columns3, vstack: Rows3,
shape: Shapes, ticker: MoveHorizontal, countdown: Timer, hours: CalendarClock, wifi: Wifi, contact: Contact }
const iconOf = w => (w.kind === 'stack' ? (w.direction === 'column' ? Rows3 : Columns3) : ICON[w.kind] || LayoutList) const iconOf = w => (w.kind === 'stack' ? (w.direction === 'column' ? Rows3 : Columns3) : ICON[w.kind] || LayoutList)
const kindLabel = (t, w) => t(`signage.widgets.kinds.${w.kind === 'stack' ? (w.direction === 'column' ? 'vstack' : 'hstack') : w.kind}`) const kindLabel = (t, w) => t(`signage.widgets.kinds.${w.kind === 'stack' ? (w.direction === 'column' ? 'vstack' : 'hstack') : w.kind}`)
const ROW = 'grid gap-4 items-end grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]' const ROW = 'grid gap-4 items-end grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]'
@@ -177,7 +182,7 @@ function VerticalField({ w, set }) {
} }
// which widgets have text (their colour, font, style and size), a QR code's own colours, a plate // which widgets have text (their colour, font, style and size), a QR code's own colours, a plate
const TEXT_KINDS = ['name', 'date', 'clock', 'message', 'text', 'qr', 'weather'] const TEXT_KINDS = ['name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'ticker', 'countdown', 'hours', 'wifi', 'contact']
/** /**
* A widget's own look (owner review 5), folded under "Text and colours": its colour (text and * A widget's own look (owner review 5), folded under "Text and colours": its colour (text and
@@ -187,7 +192,7 @@ const TEXT_KINDS = ['name', 'date', 'clock', 'message', 'text', 'qr', 'weather']
function LookFields({ w, set }) { function LookFields({ w, set }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
if (w.kind === 'menu' || w.kind === 'stack') return null if (w.kind === 'menu' || w.kind === 'stack' || w.kind === 'shape') return null
const text = TEXT_KINDS.includes(w.kind) const text = TEXT_KINDS.includes(w.kind)
const changed = !!(w.colour || w.background_colour || w.font || w.bold != null || w.italic || w.underline || (w.text_size && w.text_size !== 100) || w.qr_colour || w.qr_background) const changed = !!(w.colour || w.background_colour || w.font || w.bold != null || w.italic || w.underline || (w.text_size && w.text_size !== 100) || w.qr_colour || w.qr_background)
const styles = [w.bold !== false && 'bold', w.italic && 'italic', w.underline && 'underline'].filter(Boolean) const styles = [w.bold !== false && 'bold', w.italic && 'italic', w.underline && 'underline'].filter(Boolean)
@@ -218,7 +223,7 @@ function LookFields({ w, set }) {
</Field> </Field>
<Slider label={t('signage.widgets.textSize')} value={w.text_size || 100} min={50} max={200} step={10} suffix="%" onChange={text_size => set({ text_size })} testId="signage-widget-text-size" /> <Slider label={t('signage.widgets.textSize')} value={w.text_size || 100} min={50} max={200} step={10} suffix="%" onChange={text_size => set({ text_size })} testId="signage-widget-text-size" />
</>} </>}
{w.kind === 'qr' && <> {(w.kind === 'qr' || w.kind === 'wifi') && <>
<ColourField label={t('signage.widgets.qrColour')} value={w.qr_colour || WIDGET_COLOURS.qr} onChange={qr_colour => set({ qr_colour })} testId="signage-widget-qr-colour" opacity={false} /> <ColourField label={t('signage.widgets.qrColour')} value={w.qr_colour || WIDGET_COLOURS.qr} onChange={qr_colour => set({ qr_colour })} testId="signage-widget-qr-colour" opacity={false} />
<ColourField label={t('signage.widgets.qrBackground')} value={w.qr_background || WIDGET_COLOURS.qrBackground} onChange={qr_background => set({ qr_background })} testId="signage-widget-qr-background" /> <ColourField label={t('signage.widgets.qrBackground')} value={w.qr_background || WIDGET_COLOURS.qrBackground} onChange={qr_background => set({ qr_background })} testId="signage-widget-qr-background" />
</>} </>}
@@ -249,6 +254,7 @@ function MessageHint() {
/** The options only some widgets have, on the same row as where / size / alignment. */ /** The options only some widgets have, on the same row as where / size / alignment. */
function InlineFields({ w, set }) { function InlineFields({ w, set }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
if (['shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact'].includes(w.kind)) return <MoreInline w={w} set={set} />
if (w.kind === 'message') { if (w.kind === 'message') {
return ( return (
<Field label={t('signage.widgets.ownText')} className="col-span-2"> <Field label={t('signage.widgets.ownText')} className="col-span-2">
@@ -305,6 +311,7 @@ function InlineFields({ w, set }) {
/** What needs more room, under the row: the picture, hints, the QR's own link, a menu's list, a stack's parts. */ /** What needs more room, under the row: the picture, hints, the QR's own link, a menu's list, a stack's parts. */
function BelowFields({ w, set, media, onMedia, extras, path, depth, selected, onSelect }) { function BelowFields({ w, set, media, onMedia, extras, path, depth, selected, onSelect }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
if (['shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact'].includes(w.kind)) return <MoreBelow w={w} set={set} />
if (w.kind === 'logo') { if (w.kind === 'logo') {
return <MediaPick kind="image" value={w.media_id} entry={media[String(w.media_id)]} testid="signage-widget-logo" return <MediaPick kind="image" value={w.media_id} entry={media[String(w.media_id)]} testid="signage-widget-logo"
onChange={item => { onMedia(item); set({ media_id: item.id }) }} /> onChange={item => { onMedia(item); set({ media_id: item.id }) }} />
@@ -137,9 +137,9 @@ export function mediaLookup(map) {
// ── menu boards and widgets (5.6b) ─────────────────────────────────────────── // ── menu boards and widgets (5.6b) ───────────────────────────────────────────
export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu'] export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact']
/** What a stack's part can show (2026-11-21): a widget, a stack one level deep, a library slide. */ /** What a stack's part can show (2026-11-21): a widget, a stack one level deep, a library slide. */
export const CELL_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu'] export const CELL_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu', 'shape', 'ticker', 'countdown', 'hours', 'wifi', 'contact']
/** A new widget of a kind ('hstack' / 'vstack': a stack side by side / one over the other), where it /** A new widget of a kind ('hstack' / 'vstack': a stack side by side / one over the other), where it
* usually goes: a menu or a stack in a box of its own (they fill a box). */ * usually goes: a menu or a stack in a box of its own (they fill a box). */
@@ -151,16 +151,24 @@ export function newWidget(kind) {
if (kind === 'menu') { if (kind === 'menu') {
return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 55, y: 10, w: 40, h: 80 }, board: { select: 'all', columns: 1, sales_point: 'in_store' } } return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 55, y: 10, w: 40, h: 80 }, board: { select: 'all', columns: 1, sales_point: 'in_store' } }
} }
return { kind, position: kind === 'message' || kind === 'text' ? 'bottom-bar' : 'top-right', size: 'medium', align: 'auto', if (kind === 'shape') return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 40, y: 30, w: 20, h: 35 }, shape: 'rectangle', radius: 10 }
...(kind === 'text' ? { text: '' } : {}) } return { kind, position: NEW_PLACE[kind] || 'top-right', size: 'medium', align: 'auto',
...(kind === 'text' || kind === 'ticker' ? { text: '' } : {}), ...(kind === 'countdown' ? { countdown_to: '17:00' } : {}) }
} }
/** The contact details a contact widget can show (routers/identity.py Contact, signage ContactKey). */
export const CONTACT_KEYS = ['phone', 'phone2', 'email', 'address', 'website', 'google', 'facebook', 'instagram', 'tiktok', 'tripadvisor', 'whatsapp', 'viber']
// where a new widget goes (6R.15 kinds; the others top right, texts in the bottom bar)
const NEW_PLACE = { message: 'bottom-bar', text: 'bottom-bar', ticker: 'bottom-bar', countdown: 'top-center', hours: 'top-left', wifi: 'bottom-right', contact: 'bottom-left' }
/** A widget put in a stack's part: only what it shows (a part has no corner, size or box). */ /** A widget put in a stack's part: only what it shows (a part has no corner, size or box). */
export function cellWidget(kind) { export function cellWidget(kind) {
if (kind === 'hstack' || kind === 'vstack') { if (kind === 'hstack' || kind === 'vstack') {
return { kind: 'stack', direction: kind === 'hstack' ? 'row' : 'column', align: 'auto', cells: [{ share: 50 }, { share: 50 }] } return { kind: 'stack', direction: kind === 'hstack' ? 'row' : 'column', align: 'auto', cells: [{ share: 50 }, { share: 50 }] }
} }
return { kind, align: 'auto', ...(kind === 'menu' ? { board: { select: 'all', columns: 1, sales_point: 'in_store' } } : {}), ...(kind === 'text' ? { text: '' } : {}) } return { kind, align: 'auto', ...(kind === 'menu' ? { board: { select: 'all', columns: 1, sales_point: 'in_store' } } : {}), ...(kind === 'text' || kind === 'ticker' ? { text: '' } : {}),
...(kind === 'countdown' ? { countdown_to: '17:00' } : {}) }
} }
/** The weather's days, as one choice: from (0 today, 1 tomorrow, 2 the day after) and how many. */ /** The weather's days, as one choice: from (0 today, 1 tomorrow, 2 the day after) and how many. */
@@ -388,7 +396,7 @@ export function toggleMonthDay(line, key) {
/** A menu's colours until the venue picks its own (the TV's data, as the player draws them). */ /** A menu's colours until the venue picks its own (the TV's data, as the player draws them). */
export const MENU_COLOURS = { accent: '#f59e0b', text: '#ffffff', newBadge: '#38bdf8' } export const MENU_COLOURS = { accent: '#f59e0b', text: '#ffffff', newBadge: '#38bdf8' }
/** A widget's colours before the venue picks its own (owner review 5). */ /** A widget's colours before the venue picks its own (owner review 5). */
export const WIDGET_COLOURS = { text: '#ffffff', plate: '#00000080', qr: '#000000', qrBackground: '#ffffff' } export const WIDGET_COLOURS = { text: '#ffffff', plate: '#00000080', qr: '#000000', qrBackground: '#ffffff', shape: '#f59e0b' }
/** A menu's look as new ("Reset the look", owner review 4): every part back to the board's. */ /** A menu's look as new ("Reset the look", owner review 4): every part back to the board's. */
export const MENU_LOOK_DEFAULTS = { export const MENU_LOOK_DEFAULTS = {
@@ -5,6 +5,13 @@ import client from '../api/client'
export const IDENTITY_KEY = ['identity'] export const IDENTITY_KEY = ['identity']
/** The venue's opening hours (6R.15): { days: [[{from, to}]…7], note, set }; edited on the Schedule page. */
export const HOURS_KEY = ['opening-hours']
export function useHours() {
const can = useCan('core.dashboard.access')
return useQuery({ queryKey: HOURS_KEY, queryFn: () => client.get('/api/identity/hours').then(r => r.data), enabled: !!can, staleTime: 60_000 })
}
/** The venue's identity ({ name, slogan, colours, logos, wifi, contact }); data undefined while it loads. */ /** The venue's identity ({ name, slogan, colours, logos, wifi, contact }); data undefined while it loads. */
export function useIdentity() { export function useIdentity() {
const can = useCan('core.dashboard.access') const can = useCan('core.dashboard.access')
+7 -1
View File
@@ -5,7 +5,7 @@ import {
customKeys, filterStaff, groupCounts, groupOf, staffBody, staffForm, staffProblems, validPin, zonesBody, zonesOf, zonesSummary, customKeys, filterStaff, groupCounts, groupOf, staffBody, staffForm, staffProblems, validPin, zonesBody, zonesOf, zonesSummary,
} from '../src/pages/staff/staffLogic.js' } from '../src/pages/staff/staffLogic.js'
import { import {
addDays, clashWith, gridOf, hourMarks, hoursOf, inOpening, loadView, overlaps, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals, addDays, clashWith, gridOf, hourMarks, hoursOf, hoursValid, inOpening, inSpans, loadView, overlaps, placeOnDay, saveView, shiftState, weekDays, weekStartOf, weekTotals,
} from '../src/pages/schedule/scheduleLogic.js' } from '../src/pages/schedule/scheduleLogic.js'
const staff = [ const staff = [
@@ -79,6 +79,12 @@ test('shifts: hours past midnight, clashes, the grid, states, totals, the timeli
assert.equal(hourMarks(22)[2], 0) assert.equal(hourMarks(22)[2], 0)
assert.equal(inOpening(23, '18:00', '02:00'), true) assert.equal(inOpening(23, '18:00', '02:00'), true)
assert.equal(inOpening(3, '18:00', '02:00'), false) assert.equal(inOpening(3, '18:00', '02:00'), false)
// the venue's hours, several spans a day (6R.15)
assert.equal(inSpans(13, [{ from: '12:00', to: '15:00' }, { from: '18:00', to: '23:00' }]), true)
assert.equal(inSpans(16, [{ from: '12:00', to: '15:00' }, { from: '18:00', to: '23:00' }]), false)
assert.equal(inSpans(10, undefined), false)
assert.equal(hoursValid([[{ from: '12:00', to: '15:00' }], []]), true)
assert.equal(hoursValid([[{ from: '12:00', to: '' }]]), false)
}) })
test('the view settings stay in this browser and survive a broken store', () => { test('the view settings stay in this browser and survive a broken store', () => {
+108 -3
View File
@@ -1480,7 +1480,13 @@
"text": "Κείμενο", "text": "Κείμενο",
"menu": "Μενού", "menu": "Μενού",
"hstack": "Οριζόντια στοίβα", "hstack": "Οριζόντια στοίβα",
"vstack": "Κάθετη στοίβα" "vstack": "Κάθετη στοίβα",
"shape": "Σχήμα",
"ticker": "Κυλιόμενο κείμενο",
"countdown": "Αντίστροφη μέτρηση",
"hours": "Ωράριο",
"wifi": "Wi-Fi",
"contact": "Στοιχεία επικοινωνίας"
}, },
"position": "Πού", "position": "Πού",
"size": "Μέγεθος", "size": "Μέγεθος",
@@ -1569,7 +1575,94 @@
"qrBackground": "Φόντο κωδικού QR", "qrBackground": "Φόντο κωδικού QR",
"changeMessage": "Αλλαγή μηνύματος", "changeMessage": "Αλλαγή μηνύματος",
"full_one": "Αυτή η διαφάνεια έχει τα περισσότερα widgets που επιτρέπονται ({{count}}). Προβολή → Μήνυμα & ρυθμίσεις → Απόδοση.", "full_one": "Αυτή η διαφάνεια έχει τα περισσότερα widgets που επιτρέπονται ({{count}}). Προβολή → Μήνυμα & ρυθμίσεις → Απόδοση.",
"full_other": "Αυτή η διαφάνεια έχει τα περισσότερα widgets που επιτρέπονται ({{count}}). Προβολή → Μήνυμα & ρυθμίσεις → Απόδοση." "full_other": "Αυτή η διαφάνεια έχει τα περισσότερα widgets που επιτρέπονται ({{count}}). Προβολή → Μήνυμα & ρυθμίσεις → Απόδοση.",
"shape": {
"kind": "Σχήμα",
"kinds": {
"rectangle": "Ορθογώνιο",
"circle": "Κύκλος / έλλειψη",
"triangle": "Τρίγωνο",
"polygon": "Πολύγωνο",
"star": "Αστέρι",
"custom": "Δικές σας γωνίες"
},
"sides": "Πλευρές",
"points": "Ακτίνες",
"custom": "Γωνίες",
"customHint": "Κάθε γωνία ως x,y σε % του πλαισίου του σχήματος, χωρισμένες με κενά.",
"fill": "Γέμισμα",
"fillTo": "Διαβάθμιση προς",
"oneColour": "Ένα χρώμα",
"angle": "Κατεύθυνση διαβάθμισης",
"stroke": "Περίγραμμα",
"noStroke": "Χωρίς περίγραμμα",
"strokeWidth": "Πάχος περιγράμματος",
"inner": "Βάθος αστεριού",
"radius": "Στρογγυλεμένες γωνίες"
},
"ticker": {
"text": "Το κείμενο",
"direction": "Κινείται",
"directions": {
"left": "Προς τα αριστερά",
"right": "Προς τα δεξιά"
},
"speed": "Ταχύτητα"
},
"countdown": {
"title": "Τίτλος",
"titlePlaceholder": "π.χ. Το happy hour τελειώνει σε",
"ends": "Τελειώνει",
"modes": {
"daily": "Κάθε μέρα",
"date": "Σε ημερομηνία"
},
"everyDayAt": "Κάθε μέρα στις",
"at": "Στις",
"starts": "Αρχίζει να μετρά",
"startModes": {
"now": "Πάντα (από οποιαδήποτε ώρα)",
"before": "Λίγη ώρα πριν το τέλος",
"at": "Σε ορισμένη ώρα"
},
"minutesBefore": "Λεπτά πριν το τέλος",
"min": "λεπ.",
"startsAt": "Αρχίζει στις",
"waiting": "Πριν αρχίσει",
"waitingModes": {
"full": "Δείχνει όλο τον χρόνο, σταματημένο",
"hide": "Κρύβεται"
},
"done": "Όταν τελειώσει, δείχνει",
"doneHint": "Κενό: η μέτρηση κρύβεται.",
"donePlaceholder": "π.χ. Ώρα για happy hour!"
},
"hours": {
"style": "Δείχνει",
"styles": {
"week": "Την εβδομάδα",
"today": "Σήμερα"
},
"titlePlaceholder": "π.χ. Ωράριο λειτουργίας",
"group": "Μέρες με το ίδιο ωράριο σε μία γραμμή",
"groupHint": "Π.χ. Δευ–Παρ 12:00–23:00.",
"missing": "Το ωράριο του καταστήματος δεν έχει οριστεί ακόμη: το widget μένει κρυφό.",
"setThem": "Ορίστε το στη σελίδα Πρόγραμμα"
},
"wifi": {
"shows": "Δείχνει",
"qr": "Κωδικό σύνδεσης (QR)",
"password": "Τον κωδικό",
"missing": "Το Wi-Fi πελατών δεν έχει οριστεί ακόμη: το widget μένει κρυφό.",
"hint": "Το δίκτυο και ο κωδικός έρχονται από την ταυτότητα του καταστήματος."
},
"contact": {
"shows": "Δείχνει",
"none": "Τίποτα",
"missing": "Κανένα από αυτά τα στοιχεία δεν έχει οριστεί ακόμη: το widget μένει κρυφό.",
"hint": "Τα στοιχεία έρχονται από την ταυτότητα του καταστήματος· τα κενά δεν εμφανίζονται."
},
"fromIdentity": "Ρυθμίσεις → Ταυτότητα"
}, },
"tabs": { "tabs": {
"playlists": "Λίστες", "playlists": "Λίστες",
@@ -3507,7 +3600,19 @@
"firstHourHint": "Για την προβολή «Ανά ώρα».", "firstHourHint": "Για την προβολή «Ανά ώρα».",
"opens": "Ανοίγει", "opens": "Ανοίγει",
"closes": "Κλείνει", "closes": "Κλείνει",
"openingHint": "Σκιασμένα στον άξονα." "openingHint": "Σκιασμένα στον άξονα.",
"openingButton": "Ωράριο",
"openingTitle": "Ωράριο λειτουργίας",
"openingIntro": "Πότε είναι ανοιχτό το κατάστημα, μέρα με τη μέρα (έως τρία διαστήματα τη μέρα· ένα διάστημα μπορεί να περνά τα μεσάνυχτα). Σκιάζεται στη χρονογραμμή και εμφανίζεται από το widget ωραρίου της ψηφιακής σήμανσης.",
"openingSaved": "Το ωράριο αποθηκεύτηκε",
"closedDay": "Κλειστά",
"removeSpan": "Αφαίρεση ωρών",
"addSpan": "Προσθήκη ωρών",
"openThisDay": "Ανοιχτά αυτή τη μέρα",
"copyToAll": "Ίδιο για κάθε μέρα",
"openingNote": "Σημείωση",
"openingNoteHint": "Π.χ. «Κλειστά τις αργίες» (προαιρετικό).",
"openingInvalid": "Κάθε διάστημα χρειάζεται δύο διαφορετικές ώρες."
}, },
"reports": { "reports": {
"failed": "Η αναφορά δεν φορτώθηκε.", "failed": "Η αναφορά δεν φορτώθηκε.",
+2 -1
View File
@@ -491,7 +491,8 @@
"calibrate": { "calibrate": {
"title": "Βαθμονόμηση εικόνας: {{name}}", "title": "Βαθμονόμηση εικόνας: {{name}}",
"hint": "Στον διαχειριστή (Ψηφιακή σήμανση → Οθόνες) μετακινήστε κάθε άκρη μέχρι τα βέλη να ακουμπούν τις άκρες της οθόνης." "hint": "Στον διαχειριστή (Ψηφιακή σήμανση → Οθόνες) μετακινήστε κάθε άκρη μέχρι τα βέλη να ακουμπούν τις άκρες της οθόνης."
} },
"closed": "Κλειστά"
}, },
"menuTablet": { "menuTablet": {
"title": "Μενού", "title": "Μενού",
+108 -3
View File
@@ -1480,7 +1480,13 @@
"text": "Text", "text": "Text",
"menu": "Menu", "menu": "Menu",
"hstack": "Horizontal stack", "hstack": "Horizontal stack",
"vstack": "Vertical stack" "vstack": "Vertical stack",
"shape": "Shape",
"ticker": "Scrolling text",
"countdown": "Countdown",
"hours": "Opening hours",
"wifi": "Wi-Fi",
"contact": "Contact details"
}, },
"position": "Where", "position": "Where",
"size": "Size", "size": "Size",
@@ -1569,7 +1575,94 @@
"qrBackground": "QR code background", "qrBackground": "QR code background",
"changeMessage": "Change the message", "changeMessage": "Change the message",
"full_one": "This slide holds the most widgets allowed ({{count}}). Signage → Message & settings → Performance.", "full_one": "This slide holds the most widgets allowed ({{count}}). Signage → Message & settings → Performance.",
"full_other": "This slide holds the most widgets allowed ({{count}}). Signage → Message & settings → Performance." "full_other": "This slide holds the most widgets allowed ({{count}}). Signage → Message & settings → Performance.",
"shape": {
"kind": "Shape",
"kinds": {
"rectangle": "Rectangle",
"circle": "Circle / ellipse",
"triangle": "Triangle",
"polygon": "Polygon",
"star": "Star",
"custom": "Your own corners"
},
"sides": "Sides",
"points": "Points",
"custom": "Corners",
"customHint": "Each corner as x,y in % of the shape's box, separated by spaces.",
"fill": "Fill",
"fillTo": "Gradient to",
"oneColour": "One colour",
"angle": "Gradient direction",
"stroke": "Border",
"noStroke": "No border",
"strokeWidth": "Border width",
"inner": "Star depth",
"radius": "Rounded corners"
},
"ticker": {
"text": "The text",
"direction": "Moves",
"directions": {
"left": "To the left",
"right": "To the right"
},
"speed": "Speed"
},
"countdown": {
"title": "Title",
"titlePlaceholder": "e.g. Happy hour ends in",
"ends": "Ends",
"modes": {
"daily": "Every day",
"date": "On a date"
},
"everyDayAt": "Every day at",
"at": "At",
"starts": "Starts counting",
"startModes": {
"now": "Always (from any time)",
"before": "A time before the end",
"at": "At a set time"
},
"minutesBefore": "Minutes before the end",
"min": "min",
"startsAt": "Starts at",
"waiting": "Before it starts",
"waitingModes": {
"full": "Show the whole time, standing",
"hide": "Hide it"
},
"done": "When it ends, show",
"doneHint": "Empty: the countdown hides.",
"donePlaceholder": "e.g. It's happy hour!"
},
"hours": {
"style": "Shows",
"styles": {
"week": "The week",
"today": "Today"
},
"titlePlaceholder": "e.g. Opening hours",
"group": "Days with the same hours on one line",
"groupHint": "E.g. Mon–Fri 12:00–23:00.",
"missing": "The venue's opening hours aren't set yet: the widget stays hidden.",
"setThem": "Set them on the Schedule page"
},
"wifi": {
"shows": "Shows",
"qr": "A code to join",
"password": "The password",
"missing": "The guests' Wi-Fi isn't set yet: the widget stays hidden.",
"hint": "The network and password come from the venue's identity."
},
"contact": {
"shows": "Shows",
"none": "Nothing chosen",
"missing": "None of these contact details is set yet: the widget stays hidden.",
"hint": "The details come from the venue's identity; empty ones don't show."
},
"fromIdentity": "Settings → Identity"
}, },
"tabs": { "tabs": {
"playlists": "Playlists", "playlists": "Playlists",
@@ -3507,7 +3600,19 @@
"firstHourHint": "For the \"By hour\" view.", "firstHourHint": "For the \"By hour\" view.",
"opens": "Opens", "opens": "Opens",
"closes": "Closes", "closes": "Closes",
"openingHint": "Shaded on the timeline." "openingHint": "Shaded on the timeline.",
"openingButton": "Opening hours",
"openingTitle": "Opening hours",
"openingIntro": "When the venue is open, day by day (up to three spans a day; a span may pass midnight). Shaded on the timeline and shown by signage's opening hours widget.",
"openingSaved": "Opening hours saved",
"closedDay": "Closed",
"removeSpan": "Remove these hours",
"addSpan": "Add hours",
"openThisDay": "Open this day",
"copyToAll": "Same for every day",
"openingNote": "A note",
"openingNoteHint": "E.g. \"Closed on holidays\" (optional).",
"openingInvalid": "Each span needs two different times."
}, },
"reports": { "reports": {
"failed": "This report couldn't be loaded.", "failed": "This report couldn't be loaded.",
+2 -1
View File
@@ -491,7 +491,8 @@
"calibrate": { "calibrate": {
"title": "Calibrating the picture of {{name}}", "title": "Calibrating the picture of {{name}}",
"hint": "In the manager (Signage → Screens), move each edge until the arrows touch the edges of the screen." "hint": "In the manager (Signage → Screens), move each edge until the arrows touch the edges of the screen."
} },
"closed": "Closed"
}, },
"menuTablet": { "menuTablet": {
"title": "Menu", "title": "Menu",
+171 -6
View File
@@ -2,12 +2,13 @@
// fonts and sizes here are the venue's own choices for its TV (slide content = data, CS-16), so // fonts and sizes here are the venue's own choices for its TV (slide content = data, CS-16), so
// they are inline styles, not tokens. Sizes scale with the screen (cqmin), so a slide looks the // they are inline styles, not tokens. Sizes scale with the screen (cqmin), so a slide looks the
// same on any TV. // same on any TV.
import { Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Moon, Sun } from 'lucide-react' import { useEffect, useRef, useState } from 'react'
import { Camera, Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Globe, Lock, Mail, MapPin, MessageCircle, Moon, Music, Phone, Star, Sun, ThumbsUp, Wifi } from 'lucide-react'
import { QRCodeSVG } from 'qrcode.react' import { QRCodeSVG } from 'qrcode.react'
import { BADGE_ICONS } from './badges' import { BADGE_ICONS } from './badges'
import { cq, CQ_BOX } from './cq' import { cq, CQ_BOX } from './cq'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { badgeColours, badgeName, cellWidgets, TIGHT, fitUnit, FONTS, itemBadges, menuLook, menuPages, pageAt, priceChars, textWidth, visibleGroups, weatherIcon, widgetAlign } from './logic' import { badgeColours, badgeName, cellWidgets, countdownState, countdownText, TIGHT, fitUnit, FONTS, hoursRows, itemBadges, localNow, menuLook, menuPages, pageAt, priceChars, shapePoints, textWidth, visibleGroups, weatherIcon, widgetAlign, wifiQr } from './logic'
/** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */ /** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */
export function Background({ bg, media }) { export function Background({ bg, media }) {
@@ -173,8 +174,8 @@ const plate = (w, pad) => ({
...(w.colour ? { color: w.colour } : {}), ...(w.colour ? { color: w.colour } : {}),
...(w.background_colour ? { background: w.background_colour, borderRadius: cq(1.2), ...(pad ? { padding: `${cq(0.8)} ${cq(1.6)}` } : {}) } : {}), ...(w.background_colour ? { background: w.background_colour, borderRadius: cq(1.2), ...(pad ? { padding: `${cq(0.8)} ${cq(1.6)}` } : {}) } : {}),
}) })
// a menu or a stack in a corner or a bar has no box of its own: it gets one of this size (cqmin) // a menu, a stack, a shape or a scrolling text in a corner or a bar has no box of its own: it gets one of this size (cqmin)
const BOXED = { menu: [48, 56], stack: [60, 36] } const BOXED = { menu: [48, 56], stack: [60, 36], shape: [18, 18], ticker: [80, 7] }
/** /**
* The widgets of a slide: in their corners and bars, or (moved and sized by hand: position * The widgets of a slide: in their corners and bars, or (moved and sized by hand: position
@@ -186,8 +187,9 @@ const BOXED = { menu: [48, 56], stack: [60, 36] }
*/ */
export function Widgets({ widgets, media, venue, now, colour, extras, embed }) { export function Widgets({ widgets, media, venue, now, colour, extras, embed }) {
const fmt = useFormat() const fmt = useFormat()
const { t } = useTranslation('terminal')
if (!widgets?.length) return null if (!widgets?.length) return null
const ctx = { media, venue, now, fmt, extras: extras || {}, embed } const ctx = { media, venue, now, fmt, extras: extras || {}, embed, t }
const shown = widgets.map((w, i) => [w, i, widgetBody(w, ctx, placedBy(w), String(i))]).filter(([, , body]) => body) const shown = widgets.map((w, i) => [w, i, widgetBody(w, ctx, placedBy(w), String(i))]).filter(([, , body]) => body)
const bar = where => shown.filter(([w]) => w.position === where) const bar = where => shown.filter(([w]) => w.position === where)
const bars = [['top-bar', { top: 0 }], ['bottom-bar', { bottom: 0 }]] const bars = [['top-bar', { top: 0 }], ['bottom-bar', { bottom: 0 }]]
@@ -198,7 +200,8 @@ export function Widgets({ widgets, media, venue, now, colour, extras, embed }) {
style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: cq(3), padding: `${cq(2)} ${cq(4)}`, style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: cq(3), padding: `${cq(2)} ${cq(4)}`,
background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: cq(9) }}> background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: cq(9) }}>
{bar(where).map(([w, i, body]) => ( {bar(where).map(([w, i, body]) => (
<div key={i} data-widget={i} style={{ display: 'flex', flexDirection: 'column', alignItems: SELF[widgetAlign(w)], textAlign: widgetAlign(w), ...plate(w, true) }}>{body}</div> <div key={i} data-widget={i} style={{ display: 'flex', flexDirection: 'column', alignItems: SELF[widgetAlign(w)], textAlign: widgetAlign(w), ...plate(w, true),
...(w.kind === 'ticker' ? { flex: 1, minWidth: 0, alignSelf: 'stretch', justifyContent: 'center' } : {}) }}>{body}</div>
))} ))}
</div> </div>
))} ))}
@@ -307,9 +310,171 @@ function widgetBody(w, ctx, fit, path) {
if (w.kind === 'weather') return weatherBody(w, venue?.weather, unit, text, formatDate) if (w.kind === 'weather') return weatherBody(w, venue?.weather, unit, text, formatDate)
if (w.kind === 'menu') return boxed(<MenuWidget board={w.board || {}} menu={x.menu} now={now} badges={venue?.badges} />, 'menu') if (w.kind === 'menu') return boxed(<MenuWidget board={w.board || {}} menu={x.menu} now={now} badges={venue?.badges} />, 'menu')
if (w.kind === 'stack') return boxed(<Stack w={w} path={path} ctx={ctx} />, 'stack') if (w.kind === 'stack') return boxed(<Stack w={w} path={path} ctx={ctx} />, 'stack')
// 6R.15
if (w.kind === 'shape') return boxed(<ShapeBody w={w} id={`sg-fill-${path.replace(/\./g, '-')}`} />, 'shape')
if (w.kind === 'ticker') {
if (!w.text) return null
const inBar = (w.position || '').endsWith('-bar')
const u = fit ? fitUnit(3.4 * 1.3, 0.1) : n => cq(+(n * s).toFixed(3))
const body = <Ticker w={w} style={text(u, 3.4, 600)} />
return inBar ? body : boxed(body, 'ticker')
}
if (w.kind === 'countdown') {
const st = countdownState(w, localNow(venue?.timezone, now), now.getSeconds())
if (st.state === 'none' || (st.state === 'waiting' && w.countdown_waiting === 'hide')) return null
if (st.state === 'done') return w.countdown_done_hide || !w.countdown_done ? null : line(w.countdown_done, 'signage-w-countdown-done', 700)
const digits = countdownText(st.left)
const label = w.text || ''
const u = unit((label ? 2.4 * 1.15 + 0.4 : 0) + 6 * 1.1, Math.max(textWidth(digits.length, 6) * 0.9, label ? textWidth(label.length, 2.4) : 0))
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'inherit', gap: u(0.4) }} data-testid="signage-w-countdown" data-state={st.state} data-left={st.left}>
{label && <span style={text(u, 2.4, 600)}>{label}</span>}
<span style={{ ...text(u, 6, 800), lineHeight: 1.1, fontVariantNumeric: 'tabular-nums' }}>{digits}</span>
</div>
)
}
if (w.kind === 'hours') return hoursBody(w, ctx, unit, text)
if (w.kind === 'wifi') return wifiBody(w, venue?.identity?.wifi, unit, text)
if (w.kind === 'contact') return contactBody(w, venue?.identity?.contact, unit, text)
return null return null
} }
/** A shape (6R.15) filling its box: a rectangle (rounded corners) or circle as a box, the others as SVG corners; a fill or a gradient, a border. */
function ShapeBody({ w, id }) {
const fill = w.fill || '#f59e0b'
const angle = w.fill_angle ?? 180
const border = w.stroke && w.stroke_width ? cq(+(w.stroke_width / 2).toFixed(2)) : null // ½ % of its shorter side a step
const pts = shapePoints(w)
if (!pts) {
return (
<div style={{ width: '100%', height: '100%', boxSizing: 'border-box', background: w.fill_to ? `linear-gradient(${angle}deg, ${fill}, ${w.fill_to})` : fill,
borderRadius: w.shape === 'circle' ? '50%' : cq(w.radius || 0), ...(border ? { border: `${border} solid ${w.stroke}` } : {}) }}
data-testid="signage-w-shape" data-shape={w.shape || 'rectangle'} />
)
}
const rad = (angle * Math.PI) / 180
const dx = Math.sin(rad) / 2
const dy = -Math.cos(rad) / 2
return (
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: '100%', height: '100%', overflow: 'visible', display: 'block' }}
data-testid="signage-w-shape" data-shape={w.shape} aria-hidden="true">
{w.fill_to && (
<defs>
<linearGradient id={id} x1={0.5 - dx} y1={0.5 - dy} x2={0.5 + dx} y2={0.5 + dy}>
<stop offset="0" stopColor={fill} /><stop offset="1" stopColor={w.fill_to} />
</linearGradient>
</defs>
)}
<polygon points={pts} fill={w.fill_to ? `url(#${id})` : fill} vectorEffect="non-scaling-stroke"
style={border ? { stroke: w.stroke, strokeWidth: border, strokeLinejoin: 'round' } : undefined} />
</svg>
)
}
/** A scrolling text (6R.15): one line moving across its place, round and round; its speed follows its height. */
function Ticker({ w, style }) {
const box = useRef(null)
const run = useRef(null)
const [size, setSize] = useState(null)
useEffect(() => {
const el = box.current
if (!el || typeof ResizeObserver === 'undefined') return undefined
const ro = new ResizeObserver(() => setSize(s => (s && s.w === el.clientWidth && s.h === el.clientHeight ? s : { w: el.clientWidth, h: el.clientHeight })))
ro.observe(el)
return () => ro.disconnect()
}, [])
useEffect(() => {
const r = run.current
if (!size || !r?.animate) return undefined
const T = r.scrollWidth
const left = (w.ticker_direction || 'left') === 'left'
const pxPerS = (w.ticker_speed || 4) * Math.max(8, r.offsetHeight) * 0.9
const a = r.animate([{ transform: `translateX(${left ? size.w : -T}px)` }, { transform: `translateX(${left ? -T : size.w}px)` }],
{ duration: ((size.w + T) / pxPerS) * 1000, iterations: Infinity })
return () => a.cancel()
}, [size, w.text, w.ticker_speed, w.ticker_direction, style.fontSize])
return (
<div ref={box} style={{ width: '100%', height: '100%', overflow: 'hidden', display: 'flex', alignItems: 'center', position: 'relative' }} data-testid="signage-w-ticker">
<span ref={run} style={{ ...style, whiteSpace: 'nowrap', display: 'inline-block', willChange: 'transform' }}>{w.text}</span>
</div>
)
}
const MONDAY = '2026-11-16' // a Monday: day names from the venue's language
const dayShort = (fmt, i) => fmt.formatDate(`2026-11-${16 + i}T12:00:00Z`, 'weekday').slice(0, 3)
/** The opening hours (6R.15): the week (days with the same hours on one line) or today; today stands out. */
function hoursBody(w, ctx, unit, text) {
const { venue, now, fmt, t } = ctx
const hours = venue?.hours
if (!hours?.set) return null
const today = localNow(venue?.timezone, now).weekday
const rows = hoursRows(hours, { group: w.hours_group !== false, today, only: w.hours_style === 'today' ? today : null })
const daysText = r => (r.days.length > 1 ? `${dayShort(fmt, r.days[0])}–${dayShort(fmt, r.days[r.days.length - 1])}` : dayShort(fmt, r.days[0]))
const spansText = r => (r.spans.length ? r.spans.map(x => `${x.from}–${x.to}`).join(', ') : t('signage.closed'))
const widest = Math.max(...rows.map(r => daysText(r).length + 2 + spansText(r).length), w.text ? w.text.length : 0)
const u = unit((rows.length + (w.text ? 1.3 : 0)) * 3 * 1.35, textWidth(widest, 3))
return (
<div style={{ display: 'grid', gridTemplateColumns: 'auto auto', columnGap: u(2), rowGap: u(0.4), alignItems: 'baseline', textAlign: 'left' }}
data-testid="signage-w-hours" data-rows={rows.length} data-start={MONDAY}>
{w.text && <span style={{ ...text(u, 3.4, 800), gridColumn: '1 / -1' }}>{w.text}</span>}
{rows.map(r => (
<span key={r.days.join()} style={{ display: 'contents' }} data-today={r.today ? 'true' : undefined}>
<span style={{ ...text(u, 3, r.today ? 800 : 600), opacity: r.today || w.hours_style === 'today' ? 1 : 0.85 }}>{daysText(r)}</span>
<span style={{ ...text(u, 3, r.today ? 800 : 500), fontVariantNumeric: 'tabular-nums' }}>{spansText(r)}</span>
</span>
))}
</div>
)
}
/** The guests' Wi-Fi (6R.15, from the identity): its code to join, the network and the password. */
function wifiBody(w, wifi, unit, text) {
if (!wifi?.ssid) return null
const qr = w.wifi_qr !== false ? wifiQr(wifi) : ''
const pw = w.wifi_password !== false && wifi.security !== 'nopass' && wifi.password ? wifi.password : ''
const lines = [wifi.ssid, pw, wifi.note].filter(Boolean)
const chars = Math.max(...lines.map(l => l.length)) + 2
const u = unit(Math.max(qr ? 13 : 0, lines.length * 3.4 * 1.35), (qr ? 14.5 : 0) + textWidth(chars, 3.4))
const icon = { width: u(3), height: u(3), flexShrink: 0 }
return (
<div style={{ display: 'flex', alignItems: 'center', gap: u(1.5), textAlign: 'left' }} data-testid="signage-w-wifi">
{qr && (
<div style={{ background: w.qr_background || '#fff', padding: u(0.7), borderRadius: u(0.8), lineHeight: 0 }}>
<QRCodeSVG value={qr} size={256} fgColor={w.qr_colour || '#000000'} bgColor={w.qr_background || '#ffffff'} style={{ width: u(11.5), height: u(11.5) }} />
</div>
)}
<div style={{ display: 'grid', gap: u(0.5) }}>
<span style={{ display: 'flex', alignItems: 'center', gap: u(0.8), ...text(u, 3.4, 800) }}><Wifi style={icon} aria-hidden="true" />{wifi.ssid}</span>
{pw && <span style={{ display: 'flex', alignItems: 'center', gap: u(0.8), ...text(u, 3.4, 600) }}><Lock style={icon} aria-hidden="true" />{pw}</span>}
{wifi.note && <span style={{ ...text(u, 2.6, 500), opacity: 0.85 }}>{wifi.note}</span>}
</div>
</div>
)
}
const CONTACT_ICONS = { phone: Phone, phone2: Phone, email: Mail, address: MapPin, website: Globe, google: MapPin, facebook: ThumbsUp,
instagram: Camera, tiktok: Music, tripadvisor: Star, whatsapp: MessageCircle, viber: MessageCircle }
/** The venue's contact details (6R.15, from the identity): the chosen ones that are set, one a line with an icon. */
function contactBody(w, contact, unit, text) {
const rows = (w.contact_fields || ['phone', 'website', 'instagram']).filter(k => contact?.[k]).map(k => [k, contact[k]])
if (!rows.length) return null
const u = unit(rows.length * 3.2 * 1.4, textWidth(Math.max(...rows.map(([, v]) => v.length)) + 2, 3.2))
return (
<div style={{ display: 'grid', gap: u(0.6), textAlign: 'left' }} data-testid="signage-w-contact" data-rows={rows.length}>
{rows.map(([k, v]) => {
const Icon = CONTACT_ICONS[k] || Globe
return (
<span key={k} style={{ display: 'flex', alignItems: 'center', gap: u(0.9), ...text(u, 3.2, 600) }} data-key={k}>
<Icon style={{ width: u(3), height: u(3), flexShrink: 0 }} aria-hidden="true" />{v}
</span>
)
})}
</div>
)
}
/** The weather: now or a day of the forecast (today, tomorrow, the day after), and the next days; /** The weather: now or a day of the forecast (today, tomorrow, the day after), and the next days;
* its picture and degrees, only the picture or only the degrees (2026-11-21). */ * its picture and degrees, only the picture or only the degrees (2026-11-21). */
function weatherBody(w, wx, unit, text, formatDate) { function weatherBody(w, wx, unit, text, formatDate) {
+87 -1
View File
@@ -275,7 +275,7 @@ export function visibleGroups(groups) {
/** Widgets whose box, placed by hand, is exactly their content (owner review 6): its height (× the /** Widgets whose box, placed by hand, is exactly their content (owner review 6): its height (× the
* widget's text size) sets the size, its width follows. A menu or a stack fills its box. */ * widget's text size) sets the size, its width follows. A menu or a stack fills its box. */
export const TIGHT = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather'] export const TIGHT = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'countdown', 'hours', 'wifi', 'contact']
/** The slide kinds that carry widgets. */ /** The slide kinds that carry widgets. */
export const WIDGET_HOSTS = ['text', 'menu', 'blank'] export const WIDGET_HOSTS = ['text', 'menu', 'blank']
@@ -519,3 +519,89 @@ export function wifiQr(wifi) {
const pw = sec !== 'nopass' && wifi.password ? `P:${esc(wifi.password)};` : '' const pw = sec !== 'nopass' && wifi.password ? `P:${esc(wifi.password)};` : ''
return `WIFI:T:${sec};S:${esc(wifi.ssid)};${pw}${wifi.hidden ? 'H:true;' : ''};` return `WIFI:T:${sec};S:${esc(wifi.ssid)};${pw}${wifi.hidden ? 'H:true;' : ''};`
} }
// ── widgets of 6R.15: countdown, opening hours, shapes ───────────────────────
const minOf = hhmm => { const [h, m] = hhmm.split(':').map(Number); return h * 60 + m }
const dayNo = date => Date.UTC(+date.slice(0, 4), +date.slice(5, 7) - 1, +date.slice(8, 10)) / 86_400_000
/** A countdown's moment ("HH:MM" = that time today; "YYYY-MM-DDTHH:MM") in minutes from the venue's local midnight today. */
function momentMin(when, local) {
if (!when) return null
if (when.length === 5) return minOf(when)
return (dayNo(when.slice(0, 10)) - dayNo(local.date)) * 1440 + minOf(when.slice(11))
}
/**
* Where a countdown stands (6R.15) at venue time `local` ({ date, minutes }) and `seconds` past the
* minute: 'none' (no end set), 'waiting' (before it starts: `left` = its whole span), 'running'
* (`left` = seconds to the end), 'done' (the end has passed, today or for good).
*/
export function countdownState(w, local, seconds = 0) {
const end = momentMin(w?.countdown_to, local)
if (end == null) return { state: 'none', left: 0 }
const nowS = local.minutes * 60 + seconds
const endS = end * 60
let startS = null
if (w.countdown_start === 'before') startS = endS - (w.countdown_before || 120) * 60
else if (w.countdown_start === 'at') {
const at = momentMin(w.countdown_at, local)
if (at != null) startS = at * 60
}
if (nowS >= endS) return { state: 'done', left: 0 }
if (startS != null && nowS < startS) return { state: 'waiting', left: endS - startS }
return { state: 'running', left: endS - nowS }
}
/** Seconds as "1:30:00", "05:09" under an hour, "3d 04:10:00" over a day. */
export function countdownText(left) {
const s = Math.max(0, Math.floor(left))
const d = Math.floor(s / 86400)
const h = Math.floor((s % 86400) / 3600)
const m = Math.floor((s % 3600) / 60)
const two = n => String(n).padStart(2, '0')
if (d) return `${d}d ${two(h)}:${two(m)}:${two(s % 60)}`
return h ? `${h}:${two(m)}:${two(s % 60)}` : `${two(m)}:${two(s % 60)}`
}
/**
* The opening hours as lines (6R.15): [{ days: [0…6] (Monday 0), spans: [{from, to}] ([] closed),
* today }]; with `group`, days next to each other with the same hours share a line ("Mon–Fri").
* `only`: one weekday (the "today" style).
*/
export function hoursRows(hours, { group = true, today = -1, only = null } = {}) {
const days = hours?.days || []
if (days.length !== 7) return []
const key = i => JSON.stringify(days[i] || [])
const rows = []
for (let i = 0; i < 7; i++) {
if (only != null && i !== only) continue
const last = rows[rows.length - 1]
if (group && only == null && last && key(last.days[last.days.length - 1]) === key(i) && last.days[last.days.length - 1] === i - 1) last.days.push(i)
else rows.push({ days: [i], spans: days[i] || [] })
}
return rows.map(r => ({ ...r, today: r.days.includes(today) }))
}
/** A shape's corners as SVG points in a 100 × 100 box (polygon, star, triangle, custom "x,y x,y"); null for rectangle / circle. */
export function shapePoints(w) {
const kind = w?.shape || 'rectangle'
const ring = (n, r, turn = 0) => Array.from({ length: n }, (_, i) => {
const a = -Math.PI / 2 + turn + (i * 2 * Math.PI) / n
return [50 + r * Math.cos(a), 50 + r * Math.sin(a)]
})
let pts = null
if (kind === 'triangle') pts = [[50, 0], [100, 100], [0, 100]]
else if (kind === 'polygon') pts = ring(w.shape_sides || 6, 50)
else if (kind === 'star') {
const n = w.shape_sides || 5
const outer = ring(n, 50)
const inner = ring(n, 50 * (w.shape_inner || 45) / 100, Math.PI / n)
pts = outer.flatMap((p, i) => [p, inner[i]])
} else if (kind === 'custom') {
pts = String(w.shape_points || '').trim().split(/\s+/).map(p => p.split(',').map(Number))
.filter(p => p.length === 2 && p.every(Number.isFinite)).map(([x, y]) => [Math.min(100, Math.max(0, x)), Math.min(100, Math.max(0, y))])
if (pts.length < 3) pts = null
}
return pts ? pts.map(([x, y]) => `${+x.toFixed(2)},${+y.toFixed(2)}`).join(' ') : null
}
+38
View File
@@ -277,3 +277,41 @@ test('a Wi-Fi QR code: escaped, open networks without a password, hidden ones (6
assert.equal(wifiQr({ ssid: 'Open', password: 'x', security: 'nopass', hidden: true }), 'WIFI:T:nopass;S:Open;H:true;;') assert.equal(wifiQr({ ssid: 'Open', password: 'x', security: 'nopass', hidden: true }), 'WIFI:T:nopass;S:Open;H:true;;')
assert.equal(wifiQr({ password: 'x' }), '') assert.equal(wifiQr({ password: 'x' }), '')
}) })
test('a countdown: from a span before, waiting, running, done; a date; the text (6R.15)', async () => {
const { countdownState, countdownText } = await import('../src/logic.js')
const w = { countdown_to: '17:00', countdown_start: 'before', countdown_before: 120 }
const at = (hhmm, date = '2026-11-22') => ({ date, minutes: Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3)) })
// the owner's case: ends at 5, starts 2 h before, the slide shows at 3:30 → 1:30:00 left
assert.deepEqual(countdownState(w, at('15:30')), { state: 'running', left: 5400 })
assert.equal(countdownText(5400), '1:30:00')
assert.deepEqual(countdownState(w, at('14:00')), { state: 'waiting', left: 7200 })
assert.equal(countdownState(w, at('17:00')).state, 'done')
assert.equal(countdownState({ countdown_to: '17:00' }, at('09:00')).left, 8 * 3600)
assert.equal(countdownState({ countdown_to: '17:00', countdown_start: 'at', countdown_at: '16:00' }, at('15:00')).state, 'waiting')
const ny = countdownState({ countdown_to: '2026-12-31T23:59' }, at('23:59', '2026-12-30'), 30)
assert.equal(ny.left, 86400 - 30)
assert.equal(countdownText(ny.left), '23:59:30')
assert.equal(countdownText(2 * 86400 + 61), '2d 00:01:01')
assert.equal(countdownText(309), '05:09')
assert.equal(countdownState({}, at('10:00')).state, 'none')
})
test('opening hours in lines: same hours grouped, today marked; shapes as points (6R.15)', async () => {
const { hoursRows, shapePoints } = await import('../src/logic.js')
const lunch = [{ from: '12:00', to: '23:00' }]
const hours = { days: [lunch, lunch, lunch, lunch, [{ from: '12:00', to: '01:00' }], [], lunch] }
const rows = hoursRows(hours, { today: 1 })
assert.deepEqual(rows.map(r => r.days), [[0, 1, 2, 3], [4], [5], [6]])
assert.equal(rows[0].today, true)
assert.deepEqual(rows[2].spans, [])
assert.equal(hoursRows(hours, { group: false }).length, 7)
assert.deepEqual(hoursRows(hours, { only: 5 }).map(r => r.days), [[5]])
assert.deepEqual(hoursRows({ days: [] }), [])
assert.equal(shapePoints({ shape: 'triangle' }), '50,0 100,100 0,100')
assert.equal(shapePoints({ shape: 'star', shape_sides: 5 }).split(' ').length, 10)
assert.equal(shapePoints({ shape: 'polygon', shape_sides: 6 }).split(' ').length, 6)
assert.equal(shapePoints({ shape: 'custom', shape_points: '0,0 100,0 50,120' }), '0,0 100,0 50,100')
assert.equal(shapePoints({ shape: 'custom', shape_points: '1,1' }), null)
assert.equal(shapePoints({ shape: 'rectangle' }), null)
})
+20
View File
@@ -577,6 +577,26 @@ try {
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { area_left: 0, area_top: 0, area_right: 0, area_bottom: 0 } }) await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { area_left: 0, area_top: 0, area_right: 0, area_bottom: 0 } })
await tv.setViewportSize({ width: 1280, height: 720 }) await tv.setViewportSize({ width: 1280, height: 720 })
// ── 6R.14 / 6R.15: the identity and opening hours feed the new widgets on the TV ──
const ident = await api('GET', '/api/identity', { token: boss })
await api('PUT', '/api/identity', { token: boss, body: { name: ident.name || 'Taverna', wifi: { ssid: 'Xenia Guests', password: 'kalimera', security: 'WPA' },
contact: { phone: '2310 123456', instagram: '@xenia' } } })
await api('PUT', '/api/identity/hours', { token: boss, body: { days: [[{ from: '12:00', to: '23:00' }], [], [], [], [], [], []] } })
const wl = await api('POST', '/api/signage/playlists', { token: boss, body: { name: 'New widgets', orientation: 'landscape' } })
await api('POST', `/api/signage/playlists/${wl.id}/slides`, { token: boss, body: { kind: 'blank', duration_s: 60, content: { widgets: [
{ kind: 'shape', position: 'custom', box: { x: 2, y: 2, w: 10, h: 15 }, shape: 'star' },
{ kind: 'countdown', position: 'top-center', countdown_to: '2099-01-01T00:00', text: 'Opening in' },
{ kind: 'hours', position: 'top-left' }, { kind: 'wifi', position: 'bottom-right' }, { kind: 'contact', position: 'bottom-left' },
{ kind: 'ticker', position: 'top-bar', text: 'Fresh fish today' }] } } })
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: wl.id } })
const widgetsOn = async () => (await Promise.all(['shape', 'countdown', 'hours', 'wifi', 'contact', 'ticker'].map(k => tv.getByTestId(`signage-w-${k}`).count()))).every(n => n === 1)
r.check('6R.15: a shape, a countdown, the opening hours, Wi-Fi (from the identity), contact details and a scrolling text on the TV',
await waitFor(async () => (await widgetsOn()) || null, 15_000, 300) === true)
r.check('6R.15: the Wi-Fi widget carries the code that joins the network', (await tv.getByTestId('signage-w-wifi').textContent()).includes('Xenia Guests')
&& await tv.getByTestId('signage-w-wifi').locator('svg').count() > 0)
r.check('6R.15: the countdown runs (days left to 2099)', /^\d+d \d\d:\d\d:\d\d$/.test((await tv.getByTestId('signage-w-countdown').textContent()).replace('Opening in', '').trim()))
await tv.screenshot({ path: path.join(OUT, 'signage-new-widgets.png') })
await mgr.context().close() await mgr.context().close()
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } }) await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } })
await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300) await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300)