diff --git a/docs/README.md b/docs/README.md index 0f1e988..88445d1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -73,6 +73,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` | | `docs/DESIGN.md` | **The design language** (2026-11-20): the page rule (``: own scroll, fills 1080p, 16:9 and centred on ultrawides), toolbars, the one `Dropdown` (multi-select), tabs, type/spacing tokens, tables. Read before any UI work (CS-20) | | `packages/api/` | Shared HTTP client (`createApiClient`: session/device headers, `err.xenia` codes, the manager-approval retry) and the live WebSocket client with cursor replay (`createLiveClient`, used by the waiter's `useWebSocket`) (CS-18) | +| `routers/identity.py`; manager `pages/Settings/sections/IdentitySettings.jsx`, `shell/useIdentity.js`, `shell/VenueIdentity.jsx` | The venue's identity (6R.14): `GET/PUT /api/identity` = `venue.name` + the JSON setting `venue.identity` (slogan, up to 12 named colours, logos main / light / dark / icon as media ids — registered usage `identity` —, guest Wi-Fi, contact details). Signage gets it in `_venue()` (`identity`, plus the venue's `timezone`) and every screen is told on a change. The manager reads it once (`useIdentity`) and `VenueIdentity` feeds `VenueColoursProvider` (`@xenia/ui`): every `ColourField` offers the venue's colours first. `wifiQr()` (`@xenia/signage/logic`) writes the join-the-network QR text | | `packages/signage/` | `@xenia/signage` (5.6a): signage slides as the TVs draw them (`SlideView`, `TextSlide`, `MenuSlide`, `Widgets`) and the player's pure logic (schedule pick, slide windows, menu pages; tests in `tests/`), shared by the terminal's player and the manager's previews. Sizes are container units (`cqmin`): a slide needs a parent with `container-type: size` (`frameStyle()`; the manager's `SlidePreview` lays it out at 1920 × 1080 and scales it down, so previews match a TV). Both apps' Tailwind `content` include it | | `packages/access/` | `` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, ``, `` (CS-18); the fixed lists every app shares with the backend: sales points (`salesPoints.js` = `core/sales_points.py`) the 14 EU allergens (`allergens.js` = `core/allergens.py`, 6.3) and the menu's languages (`menuLanguages.js` = `core/menu_languages.py`, 6.4: el + en; a product's own name is its base text, translations in `products.translations` / `categories.translations` are for customer screens only; tests compare the lists), and `` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests | | `packages/i18n/` | Translations (`locales//.json`), language resolution, venue-time / money / number formatting, the comma-or-dot number parser, and the guard `scripts/check-i18n.mjs` (CS-17). Sample: `/i18n-sample` (dev) | diff --git a/local_backend/modules/core/manifest.py b/local_backend/modules/core/manifest.py index 3ac416b..33dba6a 100644 --- a/local_backend/modules/core/manifest.py +++ b/local_backend/modules/core/manifest.py @@ -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.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.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.type', '', 'Kind of venue (restaurant, cafe, bar...), chosen in the setup wizard.', type='str'), SettingDef('venue.currency', 'EUR', 'ISO 4217 currency of all prices.', type='str'), @@ -50,6 +51,7 @@ MODULE = Module( Mount('routers.access', '/api/access'), Mount('routers.notifications', '/api/platform/notifications'), Mount('routers.scenes', '/api/scenes'), + Mount('routers.identity', '/api/identity'), Mount('core.modules.api', '/api/platform'), ), ) diff --git a/local_backend/routers/identity.py b/local_backend/routers/identity.py new file mode 100644 index 0000000..129db7c --- /dev/null +++ b/local_backend/routers/identity.py @@ -0,0 +1,193 @@ +"""The venue's identity (6R.14, owner 2026-11-22): set once, used by every app that shows the venue. + + 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) + +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 +their venue (routers/signage._venue) and are told when it changes; the colours are offered first in +every colour field of signage. Other apps follow it in 6R.20. +""" +from __future__ import annotations + +import json +from typing import List, Literal, Optional + +from fastapi import APIRouter, Depends +from pydantic import BaseModel, ConfigDict, Field, field_validator +from sqlalchemy.orm import Session + +from core.access.deps import require +from core.errors import XeniaError +from database import get_db + +router = APIRouter() +KEY = "venue.identity" +HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$" +LOGOS = ("main", "light", "dark", "icon") + + +class _Strict(BaseModel): + model_config = ConfigDict(extra="forbid") + + +def _text(v, n): + v = " ".join(str(v or "").split())[:n] + return v or None + + +class Colour(_Strict): + """One of the venue's colours: a name people see ("Main", "Olive") and its colour.""" + name: str = Field(min_length=1, max_length=40) + colour: str = Field(pattern=HEX) + + @field_validator("name") + @classmethod + def _name(cls, v): + v = _text(v, 40) + if not v: + raise ValueError("a colour has a name") + return v + + @field_validator("colour") + @classmethod + def _lower(cls, v): + return v.lower() + + +class Logos(_Strict): + """Pictures of the media library: the main logo, one for dark backgrounds (light), one for light + backgrounds (dark), a small square icon.""" + main: Optional[int] = None + light: Optional[int] = None + dark: Optional[int] = None + icon: Optional[int] = None + + +class Wifi(_Strict): + ssid: Optional[str] = Field(default=None, max_length=32) + password: Optional[str] = Field(default=None, max_length=63) + security: Literal["WPA", "WEP", "nopass"] = "WPA" + hidden: bool = False + note: Optional[str] = Field(default=None, max_length=120) # "Ask us for the guest network" + + @field_validator("ssid", "note") + @classmethod + def _trim(cls, v): + return (v or "").strip() or None + + @field_validator("password") + @classmethod + def _pw(cls, v): + return v or None # spaces count in a password + + +class Contact(_Strict): + phone: Optional[str] = Field(default=None, max_length=40) + phone2: Optional[str] = Field(default=None, max_length=40) + email: Optional[str] = Field(default=None, max_length=120) + address: Optional[str] = Field(default=None, max_length=200) + website: Optional[str] = Field(default=None, max_length=200) + facebook: Optional[str] = Field(default=None, max_length=200) + instagram: Optional[str] = Field(default=None, max_length=200) + tiktok: Optional[str] = Field(default=None, max_length=200) + tripadvisor: Optional[str] = Field(default=None, max_length=200) + google: Optional[str] = Field(default=None, max_length=300) # its Google Maps / reviews link + whatsapp: Optional[str] = Field(default=None, max_length=40) + viber: Optional[str] = Field(default=None, max_length=40) + + @field_validator("*") + @classmethod + def _trim(cls, v): + return (v or "").strip() or None if isinstance(v, str) or v is None else v + + +class Identity(_Strict): + slogan: Optional[str] = Field(default=None, max_length=120) + colours: List[Colour] = Field(default_factory=list, max_length=12) + logos: Logos = Field(default_factory=Logos) + wifi: Wifi = Field(default_factory=Wifi) + contact: Contact = Field(default_factory=Contact) + + @field_validator("slogan") + @classmethod + def _slogan(cls, v): + return _text(v, 120) + + +class IdentityBody(Identity): + name: Optional[str] = Field(default=None, max_length=80) + + +def _setting(db, key: str) -> str: + from models.settings import PosSettings + row = db.query(PosSettings).filter(PosSettings.key == key).first() + return row.value if row and row.value is not None else "" + + +def _save(db, key: str, value: str) -> None: + from models.settings import PosSettings + row = db.query(PosSettings).filter(PosSettings.key == key).first() + if row is None: + db.add(PosSettings(key=key, value=value)) + else: + row.value = value + + +def stored(db) -> Identity: + """The identity as stored (an old or broken value reads as empty, never an error).""" + try: + return Identity(**json.loads(_setting(db, KEY) or "{}")) + except Exception: + return Identity() + + +def identity_out(db) -> dict: + """The identity for an app: the logos as pictures ({id, name, thumb, card, full} or None).""" + from models.media import Media + from services.media import image_of + ident = stored(db).model_dump() + ident["logos"] = {k: image_of(db.get(Media, v)) if v else None for k, v in ident["logos"].items()} + return {"name": _setting(db, "venue.name") or None, **ident} + + +def _uses(db, media_id: int) -> list: + logos = stored(db).logos + return [{"id": 0, "name": f"identity.{k}"} for k in LOGOS if getattr(logos, k) == media_id] + + +def _register(): + from services import media as media_store + media_store.register_usage("identity", _uses) + + +_register() + + +@router.get("") +def get_identity(db: Session = Depends(get_db), user=Depends(require("core.dashboard.access"))): + return identity_out(db) + + +@router.put("") +def put_identity(body: IdentityBody, db: Session = Depends(get_db), user=Depends(require("core.settings.manage"))): + from models.media import Media + for k in LOGOS: + mid = getattr(body.logos, k) + if mid is None: + continue + m = db.get(Media, mid) + if m is None: + raise XeniaError("media.not_found", media_id=mid) + if m.kind != "image": + raise XeniaError("media.not_a_picture") + if "name" in body.model_fields_set: + _save(db, "venue.name", (body.name or "").strip()) + _save(db, KEY, json.dumps(Identity(**body.model_dump(exclude={"name"})).model_dump(), ensure_ascii=False)) + db.commit() + try: + from routers.signage import tell_all_screens + tell_all_screens(db) # the screens show the venue's name, logo, Wi-Fi… + except Exception: + pass # signage not installed / off: nothing to tell + return identity_out(db) diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py index d3b835b..11746cd 100644 --- a/local_backend/routers/signage.py +++ b/local_backend/routers/signage.py @@ -1488,10 +1488,15 @@ def preview_venue(db: Session = Depends(get_db), user=Depends(require(KEY))): def _venue(db) -> dict: """What the widgets need of the venue: its name, the message of the day, the weather (None = hide - it: no internet, no place, too old) and its badges (owner review 5).""" + 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.""" + from core.timeutil import venue_tz + from routers.identity import identity_out from services import signage_badges, weather + ident = identity_out(db) + ident.pop("name", None) return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, - "weather": weather.current(db), "badges": signage_badges.load(db)} + "weather": weather.current(db), "badges": signage_badges.load(db), "identity": ident, "timezone": venue_tz().key} class SlidePreviewBody(BaseModel): diff --git a/local_backend/tests/test_identity.py b/local_backend/tests/test_identity.py new file mode 100644 index 0000000..28c7f4a --- /dev/null +++ b/local_backend/tests/test_identity.py @@ -0,0 +1,47 @@ +"""The venue's identity (6R.14): name, slogan, colours, logos, Wi-Fi and contact saved together, +logos protected in the media library, signage screens told and given it with their venue.""" +from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures) +from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers) +from tests.test_signage import screens, sent # noqa: F401 (fixtures) + + +def test_empty_at_first(client, owner_h): + r = client.get("/api/identity", headers=owner_h) + assert r.status_code == 200 + j = r.json() + assert j["colours"] == [] and j["logos"] == {"main": None, "light": None, "dark": None, "icon": None} + assert j["wifi"]["security"] == "WPA" and j["contact"]["phone"] is None + + +def test_saved_together_and_shown_to_the_screens(client, owner_h, screens, sent, media_dir): + logo = up(client, owner_h, jpeg(400, 200)).json() + body = {"name": " Taverna Xenia ", "slogan": "Since 1987", "colours": [{"name": "Main", "colour": "#1E3A8A"}, {"name": "Olive", "colour": "#556b2f80"}], + "logos": {"main": logo["id"]}, "wifi": {"ssid": "Xenia Guests", "password": "kalimera 2026", "security": "WPA"}, + "contact": {"phone": " 2310 123456 ", "instagram": "@xenia"}} + sent.clear() + r = client.put("/api/identity", headers=owner_h, json=body) + assert r.status_code == 200, r.text + j = r.json() + assert j["name"] == "Taverna Xenia" and j["slogan"] == "Since 1987" + assert j["colours"] == [{"name": "Main", "colour": "#1e3a8a"}, {"name": "Olive", "colour": "#556b2f80"}] + assert j["logos"]["main"]["id"] == logo["id"] and j["logos"]["main"]["card"] + assert j["wifi"]["password"] == "kalimera 2026" and j["contact"]["phone"] == "2310 123456" + assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent + # the venue name is the one every app already reads + assert client.get("/api/settings/", headers=owner_h).json()["venue.name"]["value"] == "Taverna Xenia" + # the screens get it with their venue + venue = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"] + assert venue["name"] == "Taverna Xenia" and venue["identity"]["wifi"]["ssid"] == "Xenia Guests" + assert venue["identity"]["logos"]["main"]["id"] == logo["id"] + # a logo in use can't be deleted + assert err(client.delete(f"/api/media/{logo['id']}", headers=owner_h)) == "media.in_use" + + +def test_checked(client, owner_h): + assert client.put("/api/identity", headers=owner_h, json={"colours": [{"name": "", "colour": "#000000"}]}).status_code == 422 + assert client.put("/api/identity", headers=owner_h, json={"colours": [{"name": "x", "colour": "red"}]}).status_code == 422 + assert client.put("/api/identity", headers=owner_h, json={"wifi": {"security": "WPA9"}}).status_code == 422 + assert client.put("/api/identity", headers=owner_h, json={"nope": 1}).status_code == 422 + 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)] + assert client.put("/api/identity", headers=owner_h, json={"colours": too_many}).status_code == 422 diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 1d71054..f8ac485 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -6,6 +6,7 @@ import { lazy, Suspense } from 'react' import { useQuery } from '@tanstack/react-query' import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom' import { AccessProvider } from '@xenia/access' +import { VenueIdentity } from './shell/VenueIdentity' import { createI18n } from '@xenia/i18n' import { Spinner } from '@xenia/ui' import useAuthStore from './store/authStore' @@ -110,7 +111,7 @@ function ManagerRoot() { return ( }> - + ) diff --git a/manager_dashboard/src/pages/Settings/SettingsPage.jsx b/manager_dashboard/src/pages/Settings/SettingsPage.jsx index bbedc52..54302b6 100644 --- a/manager_dashboard/src/pages/Settings/SettingsPage.jsx +++ b/manager_dashboard/src/pages/Settings/SettingsPage.jsx @@ -16,10 +16,12 @@ import SecuritySettings from './sections/SecuritySettings' import SystemSettings from './sections/SystemSettings' import TableColours from './sections/TableColours' import VenueSettings from './sections/VenueSettings' +import IdentitySettings from './sections/IdentitySettings' const TABS = { 'app-info': () => , venue: () => , + identity: () => , 'customer-display': () => , 'menu-tablets': () => , security: () => , diff --git a/manager_dashboard/src/pages/Settings/sections/IdentitySettings.jsx b/manager_dashboard/src/pages/Settings/sections/IdentitySettings.jsx new file mode 100644 index 0000000..01cfbaa --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/IdentitySettings.jsx @@ -0,0 +1,146 @@ +// Settings → Identity (6R.14, owner 2026-11-22): the venue's name and slogan, its colours (named), +// logos, guest Wi-Fi and contact details, edited together and saved at once (PUT /api/identity). +// Signage offers the colours first in every colour field and its widgets read the rest; the other +// apps follow it (6R.20) unless they have their own look. +import { useMemo, useState } from 'react' +import toast from 'react-hot-toast' +import { useQueryClient } from '@tanstack/react-query' +import { QRCodeSVG } from 'qrcode.react' +import { Plus, Trash2 } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useCan } from '@xenia/access' +import { useTranslation } from '@xenia/i18n' +import { Button, ColourField, Dropdown, Field, IconButton, Input, Spinner, Switch } from '@xenia/ui' +import { wifiQr } from '@xenia/signage/logic' +import client from '../../../api/client' +import MediaField from '../../media/MediaField' +import { IDENTITY_KEY, useIdentity } from '../../../shell/useIdentity' +import { CONTACT, CONTACT_MAX, identityBody, LOGOS, MAX_COLOURS, newColour } from './identityLogic' +import { SettingsCard } from './SettingsCard' + +export default function IdentitySettings() { + const { data } = useIdentity() + if (!data) return
+ return +} + +function IdentityForm({ saved }) { + const { t } = useTranslation('manager') + const qc = useQueryClient() + const canEdit = useCan('core.settings.manage') + const [d, setD] = useState(() => structuredClone(saved)) + const [busy, setBusy] = useState(false) + const dirty = useMemo(() => JSON.stringify(identityBody(d)) !== JSON.stringify(identityBody(saved)), [d, saved]) + const set = patch => setD(x => ({ ...x, ...patch })) + const setIn = (part, patch) => setD(x => ({ ...x, [part]: { ...(x[part] || {}), ...patch } })) + const colours = d.colours || [] + const setColour = (i, patch) => set({ colours: colours.map((c, j) => (j === i ? { ...c, ...patch } : c)) }) + const bad = colours.some(c => !(c.name || '').trim()) + const save = async () => { + setBusy(true) + try { + const { data: out } = await client.put('/api/identity', identityBody(d)) + qc.setQueryData(IDENTITY_KEY, out) + qc.invalidateQueries({ queryKey: ['pos-settings'] }) + toast.success(t('identity.saved')) + } catch (err) { toast.error(errorMessage(err, t)) } + setBusy(false) + } + const wifi = d.wifi || {} + const qr = wifiQr(wifi) + + return ( +
+
+

{t('identity.intro')}

+ {dirty && {t('identity.unsaved')}} + + +
+ + +
+ + set({ name: e.target.value })} data-testid="identity-name-input" /> + + + set({ slogan: e.target.value })} data-testid="identity-slogan" /> + +
+
+ + +
+ {colours.length === 0 &&

{t('identity.colours.none')}

} + {colours.map((c, i) => ( +
+ + setColour(i, { name: e.target.value })} data-testid="identity-colour-name" /> + + setColour(i, { colour: v })} testId={`identity-colour-${i}`} /> + set({ colours: colours.filter((_, j) => j !== i) })}> + + +
+ ))} +
+ + {colours.length >= MAX_COLOURS && {t('identity.colours.max')}} +
+
+
+ + +
+ {LOGOS.map(k => ( + setIn('logos', { [k]: img })} testid={`identity-logo-${k}`} /> + ))} +
+
+ + +
+
+ + setIn('wifi', { ssid: e.target.value })} data-testid="identity-wifi-ssid" /> + + + setIn('wifi', { password: e.target.value })} data-testid="identity-wifi-password" /> + + + setIn('wifi', { security: v })} data-testid="identity-wifi-security" + options={['WPA', 'WEP', 'nopass'].map(v => ({ value: v, label: t(`identity.wifi.securities.${v}`) }))} /> + + + setIn('wifi', { note: e.target.value })} /> + +
+ setIn('wifi', { hidden: v })} label={t('identity.wifi.hidden')} description={t('identity.wifi.hiddenHint')} /> +
+
+ {qr && ( +
+
+
{t('identity.wifi.preview')}
+
+ )} +
+
+ + +
+ {CONTACT.map(k => ( + + setIn('contact', { [k]: e.target.value })} data-testid={`identity-contact-${k}`} /> + + ))} +
+
+
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/identityLogic.js b/manager_dashboard/src/pages/Settings/sections/identityLogic.js new file mode 100644 index 0000000..2c5bb7b --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/identityLogic.js @@ -0,0 +1,20 @@ +// The identity form's pure helpers (6R.14), unit-tested in tests/identity.test.mjs. The new +// colours' defaults are data (the venue's own colours), so this file is in the colour guard's DATA. + +export const LOGOS = ['main', 'light', 'dark', 'icon'] +export const CONTACT = ['phone', 'phone2', 'email', 'address', 'website', 'google', 'facebook', 'instagram', 'tiktok', 'tripadvisor', 'whatsapp', 'viber'] +export const CONTACT_MAX = { phone: 40, phone2: 40, whatsapp: 40, viber: 40, email: 120, google: 300 } // else 200 (routers/identity.py) +export const MAX_COLOURS = 12 +/** A new colour: the first a deep blue, the next ones white (the owner changes them). */ +export const newColour = (n, name) => ({ name, colour: n === 0 ? '#1e3a8a' : '#ffffff' }) + +/** The identity as PUT /api/identity takes it (logos as media ids, empty texts as null). */ +export function identityBody(d) { + return { + name: (d.name || '').trim(), slogan: (d.slogan || '').trim() || null, + colours: (d.colours || []).map(c => ({ name: (c.name || '').trim(), colour: c.colour })), + logos: Object.fromEntries(LOGOS.map(k => [k, d.logos?.[k]?.id ?? null])), + wifi: { ssid: d.wifi?.ssid || null, password: d.wifi?.password || null, security: d.wifi?.security || 'WPA', hidden: !!d.wifi?.hidden, note: d.wifi?.note || null }, + contact: Object.fromEntries(CONTACT.map(k => [k, (d.contact?.[k] || '').trim() || null])), + } +} diff --git a/manager_dashboard/src/shell/VenueIdentity.jsx b/manager_dashboard/src/shell/VenueIdentity.jsx new file mode 100644 index 0000000..dabc652 --- /dev/null +++ b/manager_dashboard/src/shell/VenueIdentity.jsx @@ -0,0 +1,9 @@ +// The venue's identity in the manager (6R.14): its colours offered first in every colour field +// (VenueColoursProvider of @xenia/ui). +import { VenueColoursProvider } from '@xenia/ui' +import { useIdentity } from './useIdentity' + +export function VenueIdentity({ children }) { + const { data } = useIdentity() + return {children} +} diff --git a/manager_dashboard/src/shell/useIdentity.js b/manager_dashboard/src/shell/useIdentity.js new file mode 100644 index 0000000..45a99cc --- /dev/null +++ b/manager_dashboard/src/shell/useIdentity.js @@ -0,0 +1,17 @@ +// One shared read of the venue's identity (6R.14): GET /api/identity. +import { useQuery } from '@tanstack/react-query' +import { useCan } from '@xenia/access' +import client from '../api/client' + +export const IDENTITY_KEY = ['identity'] + +/** The venue's identity ({ name, slogan, colours, logos, wifi, contact }); data undefined while it loads. */ +export function useIdentity() { + const can = useCan('core.dashboard.access') + return useQuery({ + queryKey: IDENTITY_KEY, + queryFn: () => client.get('/api/identity').then(r => r.data), + enabled: !!can, + staleTime: 60_000, + }) +} diff --git a/manager_dashboard/tests/identity.test.mjs b/manager_dashboard/tests/identity.test.mjs new file mode 100644 index 0000000..0284ad1 --- /dev/null +++ b/manager_dashboard/tests/identity.test.mjs @@ -0,0 +1,17 @@ +// The identity form (6R.14): what it sends. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { identityBody, newColour } from '../src/pages/Settings/sections/identityLogic.js' + +test('the identity as it is saved: logos as ids, empty texts as null, names trimmed', () => { + const body = identityBody({ name: ' Xenia ', slogan: ' ', colours: [{ name: ' Main ', colour: '#112233' }], logos: { main: { id: 4, card: '/x' } }, + wifi: { ssid: 'Guests', hidden: 1 }, contact: { phone: ' 123 ', email: '' } }) + assert.equal(body.name, 'Xenia') + assert.equal(body.slogan, null) + assert.deepEqual(body.colours, [{ name: 'Main', colour: '#112233' }]) + assert.deepEqual(body.logos, { main: 4, light: null, dark: null, icon: null }) + assert.deepEqual(body.wifi, { ssid: 'Guests', password: null, security: 'WPA', hidden: true, note: null }) + assert.equal(body.contact.phone, '123') + assert.equal(body.contact.email, null) + assert.equal(newColour(1, 'x').name, 'x') +}) diff --git a/manager_dashboard/tests/v2-guards.test.mjs b/manager_dashboard/tests/v2-guards.test.mjs index fa86b5c..94765a5 100644 --- a/manager_dashboard/tests/v2-guards.test.mjs +++ b/manager_dashboard/tests/v2-guards.test.mjs @@ -15,7 +15,7 @@ const v2 = JSON.parse(readFileSync(path.join(ROOT, 'v2.json'), 'utf8')) const DATA = new Set([ 'src/pages/signage/signageLogic.js', 'src/pages/signage/SignageFields.jsx', 'src/pages/signage/SlideEditor.jsx', 'src/pages/signage/MenuEditor.jsx', 'src/pages/platform/DeviceConfigFields.jsx', 'src/pages/products/categoryColours.js', - 'src/pages/Settings/sections/venueColours.js', + 'src/pages/Settings/sections/venueColours.js', 'src/pages/Settings/sections/identityLogic.js', ]) const GREEK = /[Ͱ-Ͽἀ-῿]/ const COLOUR = [ diff --git a/packages/i18n/locales/el/common.json b/packages/i18n/locales/el/common.json index 5afe797..46bad40 100644 --- a/packages/i18n/locales/el/common.json +++ b/packages/i18n/locales/el/common.json @@ -44,7 +44,8 @@ "colourOwn": "Δικό σας χρώμα", "colourCode": "Κωδικός χρώματος", "opacity": "Αδιαφάνεια", - "noIcon": "Χωρίς εικονίδιο" + "noIcon": "Χωρίς εικονίδιο", + "venueColours": "Τα χρώματα του καταστήματος" }, "override": { "title": "Έγκριση υπευθύνου", diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 90a1292..ea28bc0 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -375,7 +375,8 @@ "fiscal": "Ταμειακή", "development": "Developer", "customer-display": "Οθόνη πελάτη", - "menu-tablets": "Tablet μενού" + "menu-tablets": "Tablet μενού", + "identity": "Ταυτότητα" }, "mode": { "password": "Κωδικός", @@ -4343,5 +4344,72 @@ "deleted": "Η σκηνή διαγράφηκε.", "deleteTitle": "Διαγραφή «{{name}}»;", "deleteBody": "Οι κανόνες τιμών με αυτήν παύουν να ισχύουν· οι γραμμές οθονών που έπαιζαν μόνο σε αυτήν απενεργοποιούνται." + }, + "identity": { + "title": "Η ταυτότητα του καταστήματος", + "intro": "Ορίζεται μία φορά και χρησιμοποιείται παντού: η ψηφιακή σήμανση, το ταμείο, η οθόνη πελάτη και οι εφαρμογές του προσωπικού δείχνουν το όνομα, τα χρώματα και τα λογότυπα του καταστήματος, και τα widgets Wi-Fi και επικοινωνίας παίρνουν τα στοιχεία τους από εδώ. Κάθε εφαρμογή μπορεί να έχει και τα δικά της.", + "save": "Αποθήκευση", + "saved": "Η ταυτότητα αποθηκεύτηκε", + "unsaved": "Μη αποθηκευμένες αλλαγές", + "undo": "Αναίρεση", + "name": { + "title": "Όνομα", + "name": "Το όνομα του καταστήματος", + "nameHint": "Στις οθόνες, στα δελτία και στις εφαρμογές πελατών.", + "slogan": "Σύνθημα", + "sloganHint": "Μια σύντομη γραμμή κάτω από το όνομα (προαιρετικό)." + }, + "colours": { + "title": "Χρώματα", + "hint": "Τα χρώματα του καταστήματος, με ονόματα. Κάθε πεδίο χρώματος της ψηφιακής σήμανσης τα προτείνει πρώτα.", + "add": "Προσθήκη χρώματος", + "name": "Όνομα", + "colour": "Χρώμα", + "remove": "Αφαίρεση {{name}}", + "none": "Δεν υπάρχουν χρώματα ακόμη.", + "newName": "Χρώμα {{n}}", + "max": "Έως 12 χρώματα." + }, + "logos": { + "title": "Λογότυπα", + "hint": "Εικόνες από τη βιβλιοθήκη πολυμέσων.", + "main": "Κύριο λογότυπο", + "light": "Για σκούρο φόντο", + "dark": "Για ανοιχτό φόντο", + "icon": "Μικρό τετράγωνο εικονίδιο" + }, + "wifi": { + "title": "Wi-Fi για πελάτες", + "hint": "Εμφανίζεται από το widget Wi-Fi της ψηφιακής σήμανσης, με κωδικό που συνδέει στο δίκτυο.", + "ssid": "Όνομα δικτύου", + "password": "Κωδικός", + "security": "Ασφάλεια", + "securities": { + "WPA": "WPA / WPA2 / WPA3", + "WEP": "WEP (παλιό)", + "nopass": "Ανοιχτό (χωρίς κωδικό)" + }, + "hidden": "Κρυφό δίκτυο", + "hiddenHint": "Το δίκτυο δεν εμφανίζεται στη λίστα δικτύων.", + "note": "Σημείωση", + "noteHint": "Π.χ. «Ζητήστε μας τον κωδικό» (προαιρετικό).", + "preview": "Σαρώστε για σύνδεση" + }, + "contact": { + "title": "Στοιχεία επικοινωνίας", + "hint": "Εμφανίζονται από το widget επικοινωνίας. Τα κενά πεδία δεν εμφανίζονται.", + "phone": "Τηλέφωνο", + "phone2": "Δεύτερο τηλέφωνο", + "email": "Email", + "address": "Διεύθυνση", + "website": "Ιστότοπος", + "facebook": "Facebook", + "instagram": "Instagram", + "tiktok": "TikTok", + "tripadvisor": "Tripadvisor", + "google": "Σύνδεσμος Google Maps", + "whatsapp": "WhatsApp", + "viber": "Viber" + } } } diff --git a/packages/i18n/locales/en/common.json b/packages/i18n/locales/en/common.json index 4a0477d..e96e27f 100644 --- a/packages/i18n/locales/en/common.json +++ b/packages/i18n/locales/en/common.json @@ -44,7 +44,8 @@ "colourOwn": "Your own colour", "colourCode": "Colour code", "opacity": "Opacity", - "noIcon": "No icon" + "noIcon": "No icon", + "venueColours": "The venue's colours" }, "override": { "title": "Manager approval", diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 8aef354..7596238 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -375,7 +375,8 @@ "fiscal": "Fiscal device", "development": "Developer", "customer-display": "Customer display", - "menu-tablets": "Menu tablets" + "menu-tablets": "Menu tablets", + "identity": "Identity" }, "mode": { "password": "Password", @@ -4343,5 +4344,72 @@ "deleted": "Scene deleted.", "deleteTitle": "Delete \"{{name}}\"?", "deleteBody": "Price rules with it stop applying; signage lines that played only in it are turned off." + }, + "identity": { + "title": "The venue's identity", + "intro": "Set once, used everywhere: signage, the counter, the customer display and the staff apps show the venue's name, colours and logos, and the Wi-Fi and contact widgets read their details here. Each app can still use its own.", + "save": "Save", + "saved": "Identity saved", + "unsaved": "Unsaved changes", + "undo": "Undo", + "name": { + "title": "Name", + "name": "The venue's name", + "nameHint": "On screens, tickets and the customer apps.", + "slogan": "Slogan", + "sloganHint": "A short line under the name (optional)." + }, + "colours": { + "title": "Colours", + "hint": "The venue's colours, with names. Every colour field in signage offers them first.", + "add": "Add a colour", + "name": "Name", + "colour": "Colour", + "remove": "Remove {{name}}", + "none": "No colours yet.", + "newName": "Colour {{n}}", + "max": "Up to 12 colours." + }, + "logos": { + "title": "Logos", + "hint": "Pictures from the media library.", + "main": "Main logo", + "light": "For dark backgrounds", + "dark": "For light backgrounds", + "icon": "Small square icon" + }, + "wifi": { + "title": "Wi-Fi for guests", + "hint": "Shown by the Wi-Fi widget on signage, with a code that joins the network.", + "ssid": "Network name", + "password": "Password", + "security": "Security", + "securities": { + "WPA": "WPA / WPA2 / WPA3", + "WEP": "WEP (old)", + "nopass": "Open (no password)" + }, + "hidden": "Hidden network", + "hiddenHint": "The network doesn't show in the list of networks.", + "note": "A note", + "noteHint": "E.g. \"Ask us for the code\" (optional).", + "preview": "Scan to join" + }, + "contact": { + "title": "Contact details", + "hint": "Shown by the contact widget. Empty fields don't show.", + "phone": "Phone", + "phone2": "Second phone", + "email": "Email", + "address": "Address", + "website": "Website", + "facebook": "Facebook", + "instagram": "Instagram", + "tiktok": "TikTok", + "tripadvisor": "Tripadvisor", + "google": "Google Maps link", + "whatsapp": "WhatsApp", + "viber": "Viber" + } } } diff --git a/packages/i18n/src/hooks.js b/packages/i18n/src/hooks.js index b47cc92..1a5f9b3 100644 --- a/packages/i18n/src/hooks.js +++ b/packages/i18n/src/hooks.js @@ -45,6 +45,7 @@ export function useUiLabels() { selected: count => t('ui.selected', { count }), pinProgress: (count, total) => t('ui.pinProgress', { count, total }), colourOwn: t('ui.colourOwn'), + venueColours: t('ui.venueColours'), colourCode: t('ui.colourCode'), opacity: t('ui.opacity'), noIcon: t('ui.noIcon'), diff --git a/packages/signage/src/logic.js b/packages/signage/src/logic.js index 2e084b6..a1ec710 100644 --- a/packages/signage/src/logic.js +++ b/packages/signage/src/logic.js @@ -508,3 +508,14 @@ export function shapeName(w, h) { const d = g(Math.round(w), Math.round(h)) || 1 return `${Math.round(w) / d}:${Math.round(h) / d}` } + +// ── the venue's identity (6R.14) ────────────────────────────────────────────── + +/** The text of a QR code that joins a Wi-Fi network ("WIFI:T:WPA;S:…;P:…;;"), or '' without a network name. */ +export function wifiQr(wifi) { + if (!wifi?.ssid) return '' + const esc = v => String(v).replace(/([\;,:"])/g, '\$1') + const sec = wifi.security === 'nopass' ? 'nopass' : wifi.security === 'WEP' ? 'WEP' : 'WPA' + const pw = sec !== 'nopass' && wifi.password ? `P:${esc(wifi.password)};` : '' + return `WIFI:T:${sec};S:${esc(wifi.ssid)};${pw}${wifi.hidden ? 'H:true;' : ''};` +} diff --git a/packages/signage/tests/logic.test.mjs b/packages/signage/tests/logic.test.mjs index cf8f7ce..7a790f6 100644 --- a/packages/signage/tests/logic.test.mjs +++ b/packages/signage/tests/logic.test.mjs @@ -270,3 +270,10 @@ test('slide shapes: custom ratios, the canvas, the box a slide keeps on any scre assert.equal(shapeName(1920, 1200), '16:10') assert.equal(shapeName(1000, 300), '10:3') }) + +test('a Wi-Fi QR code: escaped, open networks without a password, hidden ones (6R.14)', async () => { + const { wifiQr } = await import('../src/logic.js') + assert.equal(wifiQr({ ssid: 'Xenia Guests', password: 'a;b:c', security: 'WPA' }), 'WIFI:T:WPA;S:Xenia Guests;P:a\;b\:c;;') + assert.equal(wifiQr({ ssid: 'Open', password: 'x', security: 'nopass', hidden: true }), 'WIFI:T:nopass;S:Open;H:true;;') + assert.equal(wifiQr({ password: 'x' }), '') +}) diff --git a/packages/ui/src/components.css b/packages/ui/src/components.css index 8ac3efc..e356803 100644 --- a/packages/ui/src/components.css +++ b/packages/ui/src/components.css @@ -527,6 +527,7 @@ } .x-colour__auto:hover { background: var(--x-surface-2); } .x-colour__auto--on { border-color: var(--x-accent); background: var(--x-accent-soft); color: var(--x-accent-ink); } +.x-colour__venue { display: grid; gap: var(--x-space-2); padding-bottom: var(--x-space-2); border-bottom: 1px solid var(--x-line); } .x-colour__presets { display: grid; grid-template-columns: repeat(6, 1fr); gap: var(--x-space-2); justify-items: center; } .x-colour__preset { padding: 0; border: 0; background: none; border-radius: 999px; cursor: pointer; transition: transform var(--x-duration-fast) var(--x-ease); } .x-colour__preset .x-swatch { width: 32px; height: 32px; } diff --git a/packages/ui/src/components/ColourField.jsx b/packages/ui/src/components/ColourField.jsx index 1470411..65ce744 100644 --- a/packages/ui/src/components/ColourField.jsx +++ b/packages/ui/src/components/ColourField.jsx @@ -4,6 +4,7 @@ import { Field, Input } from './Field.jsx' import { Popover } from './Popover.jsx' import { useLabels } from './labels.js' import { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } from './colour.js' +import { useVenueColours } from './venueColours.js' /** * The one colour field of the product (2026-11-21): its swatch and code, as tall as the fields @@ -13,9 +14,11 @@ import { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } from './colour.js' * auto: { label, on, pick } — a first choice that leaves the colour to something else ("Automatic", * "Each badge's own"); `on` shows it chosen (the field then reads its label). * opacity: false hides the opacity (a colour that can't be see-through). + * The venue's own colours (VenueColoursProvider, its identity: 6R.14) come first, with their names. */ export function ColourField({ label, hint, value, onChange, presets = COLOUR_PRESETS, auto, opacity = true, className, testId }) { const labels = useLabels() + const venue = useVenueColours() const [open, setOpen] = useState(false) const [typed, setTyped] = useState(null) const btn = useRef(null) @@ -36,6 +39,23 @@ export function ColourField({ label, hint, value, onChange, presets = COLOUR_PRE )} + {venue.length > 0 && ( +
+ {labels.venueColours} +
+ {venue.map(({ name, colour }) => { + const c = colour.toLowerCase() + const chosen = !auto?.on && (rgb === c.slice(0, 7)) + return ( + + ) + })} +
+
+ )}
{presets.map(c => { const chosen = !auto?.on && rgb === c.toLowerCase() diff --git a/packages/ui/src/components/labels.js b/packages/ui/src/components/labels.js index 3c1dfd8..474ee1f 100644 --- a/packages/ui/src/components/labels.js +++ b/packages/ui/src/components/labels.js @@ -22,6 +22,7 @@ export const DEFAULT_LABELS = { noOptions: 'Nothing found', selected: n => `${n} selected`, colourOwn: 'Your own colour', + venueColours: "The venue's colours", colourCode: 'Colour code', opacity: 'Opacity', noIcon: 'No icon', diff --git a/packages/ui/src/components/venueColours.js b/packages/ui/src/components/venueColours.js new file mode 100644 index 0000000..9212b57 --- /dev/null +++ b/packages/ui/src/components/venueColours.js @@ -0,0 +1,15 @@ +import { createContext, createElement, useContext } from 'react' + +// The venue's own colours (its identity, 6R.14): every ColourField offers them first. An app that +// knows them (the manager reads GET /api/identity) puts them at its root: +// +const VenueColoursContext = createContext([]) + +export function VenueColoursProvider({ colours, children }) { + return createElement(VenueColoursContext.Provider, { value: colours || [] }, children) +} + +/** The venue's colours in effect ([] when none are set). */ +export function useVenueColours() { + return useContext(VenueColoursContext) +} diff --git a/packages/ui/src/index.js b/packages/ui/src/index.js index 883cb15..77374fd 100644 --- a/packages/ui/src/index.js +++ b/packages/ui/src/index.js @@ -25,6 +25,7 @@ export { Dropdown } from './components/Dropdown.jsx' export { Popover } from './components/Popover.jsx' export { ColourField, Swatch } from './components/ColourField.jsx' export { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } from './components/colour.js' +export { VenueColoursProvider, useVenueColours } from './components/venueColours.js' export { FieldRow } from './components/FieldRow.jsx' export { Slider } from './components/Slider.jsx' export { NumberInput } from './components/NumberInput.jsx'