feat(backend): live connection and per-device settings for paired screens (platform-v2 3.1a)
- WebSocket: credentials may come in the first frame ({cursor, token?, device?}).
A device token alone connects a paired screen (login-none apps get every event, a
sign-in app only events addressed to it); a terminal session's JWT needs its own
device, as over HTTP. Refusals send {type: refused, data: {code}} + close 4001/4003.
- ws_bus: registry of open sockets by user, session and device. Ending a session
closes its sockets (session.ended); revoke/reassign close the device's sockets
(device.revoked / device.updated); edits and module on/off send device.updated.
Events can target devices (device_ids=..., sync_events.target_device_ids, rev 0014).
Pushes go through each socket's own loop (call_soon_threadsafe).
- Device config: DeviceApp.config = typed ConfigFields, validated on pair/edit/
reassign (validation.device_config), effective values (defaults filled) in both
device views and the module catalogue. First field: auto_sign_out_minutes (KDS, POS).
- Manager: DeviceConfigFields renders an app's fields in the pair and edit dialogs.
- @xenia/api createLiveClient: `credentials` and `onRefused` options.
- Tests: tests/test_live.py (11), module texts for config fields, live client,
devices logic, manager.mjs device setting + live socket checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+3
-2
@@ -68,6 +68,7 @@ A v1 database (tables, no `alembic_version`) is refused at startup; v1 data come
|
|||||||
**CS-2. New real-time events need both ends.**
|
**CS-2. New real-time events need both ends.**
|
||||||
If the backend emits a new event type, handle it in `waiter_pwa/src/context/SSEContext.jsx` (and in the manager, if relevant), or state explicitly that it's ignored.
|
If the backend emits a new event type, handle it in `waiter_pwa/src/context/SSEContext.jsx` (and in the manager, if relevant), or state explicitly that it's ignored.
|
||||||
Events carry IDs; clients re-fetch the full object (`/api/orders/{id}`) instead of trusting partial payloads.
|
Events carry IDs; clients re-fetch the full object (`/api/orders/{id}`) instead of trusting partial payloads.
|
||||||
|
Control frames from `routers/ws.py` (3.1a) are not stored and have no seq: `device.updated` (a paired screen re-reads `GET /api/devices/me`), and just before the server closes a socket `session.ended` (4001) or `device.revoked` / `device.updated` (4003). The waiter and the manager ignore them (their next request gets the 401 that signs them out); the terminal acts on them. Events for one device: `ws_bus.broadcast_sync(type, data, device_ids=[…])`.
|
||||||
|
|
||||||
**CS-3. The waiter app must survive bad networks.**
|
**CS-3. The waiter app must survive bad networks.**
|
||||||
Waiters walk in and out of WiFi range and phones sleep. Any new waiter flow must:
|
Waiters walk in and out of WiFi range and phones sleep. Any new waiter flow must:
|
||||||
@@ -162,7 +163,7 @@ Routers are mounted from the module manifests (`local_backend/modules/<key>/mani
|
|||||||
|
|
||||||
**CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17).
|
**CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17).
|
||||||
Use `core.access.deps.require("<module>.<area>.<action>")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans are gone (step 2.99): `UserOut` carries only `permissions` (keys).
|
Use `core.access.deps.require("<module>.<area>.<action>")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans are gone (step 2.99): `UserOut` carries only `permissions` (keys).
|
||||||
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>`; a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
|
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>` (on the WebSocket: `device` in the first frame); a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Per-device settings are `ConfigField`s in `DeviceApp.config` (validated by `core/modules/device_config.py`, rendered by the manager's `DeviceConfigFields`), each with texts `modules:<app>.config.<key>.label` (+ `.choices.<value>`), never free JSON. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
|
||||||
Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent).
|
Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent).
|
||||||
|
|
||||||
**CS-16. Shared UI lives in `packages/ui` and never restyles an app** (branch `platform-v2`, D-15, §9).
|
**CS-16. Shared UI lives in `packages/ui` and never restyles an app** (branch `platform-v2`, D-15, §9).
|
||||||
@@ -172,7 +173,7 @@ Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`),
|
|||||||
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. Module names, their limits and **every permission key** have texts in `modules.json` (`modules:<module>.name`, `.limits.<key>`, `.permissions.<rest of the key, nested by its dots>`); `tests/test_module_texts.py` fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
|
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. Module names, their limits and **every permission key** have texts in `modules.json` (`modules:<module>.name`, `.limits.<key>`, `.permissions.<rest of the key, nested by its dots>`); `tests/test_module_texts.py` fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
|
||||||
|
|
||||||
**CS-18. Frontends talk to the backend through `@xenia/api` and read access from bootstrap** (branch `platform-v2`, D-7, D-10, §9).
|
**CS-18. Frontends talk to the backend through `@xenia/api` and read access from bootstrap** (branch `platform-v2`, D-7, D-10, §9).
|
||||||
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). In the manager there is one connection, `live/LiveProvider.jsx` (opened with the signed-in shell); components listen with `useLiveEvent(type, handler)` (`'ready'` fires after each reconnect: refetch then).
|
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). A paired device passes `credentials: () => ({ device, token })` (sent in the first frame, never in the URL) and `onRefused(code)`. In the manager there is one connection, `live/LiveProvider.jsx` (opened with the signed-in shell); components listen with `useLiveEvent(type, handler)` (`'ready'` fires after each reconnect: refetch then).
|
||||||
|
|
||||||
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
|
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
|
||||||
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
|
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
|
||||||
|
|||||||
@@ -17,8 +17,9 @@ Agent notes:
|
|||||||
- last_seen_at is written at most every LAST_SEEN_EVERY_S.
|
- last_seen_at is written at most every LAST_SEEN_EVERY_S.
|
||||||
- A user session started on a device (client "terminal") is bound to it: routers.deps.
|
- A user session started on a device (client "terminal") is bound to it: routers.deps.
|
||||||
get_current_user refuses it without that device's header (device.required), so scope
|
get_current_user refuses it without that device's header (device.required), so scope
|
||||||
can't be escaped by dropping the header. SSE/WebSocket (token in the query, browsers
|
can't be escaped by dropping the header. The WebSocket (routers/ws.py, 3.1a) applies the
|
||||||
can't set headers there) only stream events and are not bound; revisit in phase 3.
|
same rule with the device token in its first frame; the legacy SSE stream doesn't (it
|
||||||
|
goes in phase 4).
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
||||||
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
|
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
|
||||||
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
|
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
|
||||||
|
"validation.device_config": (422, "This device setting is not valid: {key}."),
|
||||||
# server
|
# server
|
||||||
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
||||||
# domain
|
# domain
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ from pydantic import BaseModel
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from core import i18n, timeutil
|
from core import i18n, timeutil
|
||||||
from core.modules import entitlements, state
|
from core.modules import device_config, entitlements, state
|
||||||
from core.modules.registry import all_permissions, registry
|
from core.modules.registry import all_permissions, registry
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from core.access.deps import require
|
from core.access.deps import require
|
||||||
@@ -70,7 +70,8 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict:
|
|||||||
"value": ent.limit(m.key, lim.key)} for lim in m.limits],
|
"value": ent.limit(m.key, lim.key)} for lim in m.limits],
|
||||||
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
|
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
|
||||||
for sd in m.settings],
|
for sd in m.settings],
|
||||||
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope)}
|
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope),
|
||||||
|
"config": device_config.describe(m.device_app.config)}
|
||||||
if m.device_app else None),
|
if m.device_app else None),
|
||||||
"workers": len(m.workers),
|
"workers": len(m.workers),
|
||||||
}
|
}
|
||||||
@@ -141,5 +142,7 @@ class ModuleToggle(BaseModel):
|
|||||||
def set_module(key: str, body: ModuleToggle, db: Session = Depends(get_db),
|
def set_module(key: str, body: ModuleToggle, db: Session = Depends(get_db),
|
||||||
user=Depends(require("core.modules.manage"))):
|
user=Depends(require("core.modules.manage"))):
|
||||||
effective = state.set_enabled(db, key, body.enabled, user_id=getattr(user, "id", None) or None)
|
effective = state.set_enabled(db, key, body.enabled, user_id=getattr(user, "id", None) or None)
|
||||||
|
from services import ws_bus
|
||||||
|
ws_bus.notify_device(every_device=True) # paired screens re-read their app_status (3.1a)
|
||||||
enabled = state.enabled_map(db)
|
enabled = state.enabled_map(db)
|
||||||
return _module_out(registry()[key], enabled, effective)
|
return _module_out(registry()[key], enabled, effective)
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""Per-device settings of an app (plan step 3.1a): what the manager may store in
|
||||||
|
devices.config and what the device reads back.
|
||||||
|
|
||||||
|
- validate(fields, config, db) -> dict | None: the cleaned config to store. Unknown keys,
|
||||||
|
wrong types, values outside choices/min/max and refs to missing rows raise
|
||||||
|
validation.device_config {key}. None/{} -> None (all defaults).
|
||||||
|
- effective(fields, stored, db=None) -> dict: every field, its stored value when still
|
||||||
|
valid, else its default. What GET /api/devices/me returns, so a screen never handles
|
||||||
|
a missing or stale value (an old free-form config, a prep zone that was deleted).
|
||||||
|
- for_app(app_key) -> the app's ConfigFields (from its manifest's DeviceApp.config).
|
||||||
|
|
||||||
|
Agent notes:
|
||||||
|
- Fields are declared in the app's manifest (core/modules/model.py ConfigField). A new
|
||||||
|
field needs its label in packages/i18n/locales/{en,el}/modules.json
|
||||||
|
(`<app>.config.<key>.label`, plus `.choices.<value>` per choice); test_module_texts fails
|
||||||
|
otherwise. The manager renders the fields generically (DeviceConfigFields.jsx).
|
||||||
|
- `ref` sources: "prep_zones" (PrepZone ids), "devices:<app_key>" (live devices of that app).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from core.errors import XeniaError
|
||||||
|
|
||||||
|
MAX_STR = 200
|
||||||
|
|
||||||
|
|
||||||
|
def for_app(app_key: str) -> tuple:
|
||||||
|
from core.access.context import device_app
|
||||||
|
da = device_app(app_key)
|
||||||
|
return tuple(da.config) if da else ()
|
||||||
|
|
||||||
|
|
||||||
|
def _bad(key: str):
|
||||||
|
return XeniaError("validation.device_config", key=key)
|
||||||
|
|
||||||
|
|
||||||
|
def _ref_exists(source: str, value: int, db) -> bool:
|
||||||
|
if source == "prep_zones":
|
||||||
|
from models.prep_zone import PrepZone
|
||||||
|
return db.get(PrepZone, value) is not None
|
||||||
|
if source.startswith("devices:"):
|
||||||
|
from models.device import Device
|
||||||
|
d = db.get(Device, value)
|
||||||
|
return d is not None and d.revoked_at is None and d.app_key == source.split(":", 1)[1]
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(f, value, db, *, strict: bool):
|
||||||
|
"""The value as stored, or raise (strict) / return the default (not strict)."""
|
||||||
|
def bad():
|
||||||
|
if strict:
|
||||||
|
raise _bad(f.key)
|
||||||
|
return f.default
|
||||||
|
if f.type == "bool":
|
||||||
|
return value if isinstance(value, bool) else bad()
|
||||||
|
if f.type == "int":
|
||||||
|
if isinstance(value, bool) or not isinstance(value, int):
|
||||||
|
return bad()
|
||||||
|
if (f.choices and value not in f.choices) or (f.min is not None and value < f.min) \
|
||||||
|
or (f.max is not None and value > f.max):
|
||||||
|
return bad()
|
||||||
|
return value
|
||||||
|
if f.type == "str":
|
||||||
|
return value.strip() if isinstance(value, str) and len(value) <= MAX_STR else bad()
|
||||||
|
if f.type == "enum":
|
||||||
|
return value if value in f.choices else bad()
|
||||||
|
if f.type == "ref":
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, bool) or not isinstance(value, int):
|
||||||
|
return bad()
|
||||||
|
if db is not None and not _ref_exists(f.choices_from or "", value, db):
|
||||||
|
return bad()
|
||||||
|
return value
|
||||||
|
return bad()
|
||||||
|
|
||||||
|
|
||||||
|
def validate(fields, config, db) -> dict | None:
|
||||||
|
if config is None:
|
||||||
|
return None
|
||||||
|
if not isinstance(config, dict):
|
||||||
|
raise _bad("config")
|
||||||
|
by_key = {f.key: f for f in fields}
|
||||||
|
out = {}
|
||||||
|
for key, value in config.items():
|
||||||
|
f = by_key.get(key)
|
||||||
|
if f is None:
|
||||||
|
raise _bad(key)
|
||||||
|
out[key] = _clean(f, value, db, strict=True)
|
||||||
|
return out or None
|
||||||
|
|
||||||
|
|
||||||
|
def effective(fields, stored, db=None) -> dict:
|
||||||
|
stored = stored if isinstance(stored, dict) else {}
|
||||||
|
return {f.key: (_clean(f, stored[f.key], db, strict=False) if f.key in stored else f.default) for f in fields}
|
||||||
|
|
||||||
|
|
||||||
|
def describe(fields) -> list[dict]:
|
||||||
|
"""The fields for the manager (module catalogue)."""
|
||||||
|
return [{"key": f.key, "type": f.type, "default": f.default, "choices": list(f.choices),
|
||||||
|
"min": f.min, "max": f.max, "choices_from": f.choices_from} for f in fields]
|
||||||
@@ -54,11 +54,30 @@ class SettingDef:
|
|||||||
choices: tuple[str, ...] = () # for type "enum"
|
choices: tuple[str, ...] = () # for type "enum"
|
||||||
|
|
||||||
|
|
||||||
|
ConfigType = Literal["bool", "int", "str", "enum", "ref"]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ConfigField:
|
||||||
|
"""One setting of a device running an app (plan step 3.1a). Stored in devices.config,
|
||||||
|
validated by core/modules/device_config.py, edited in the manager's pair/edit dialogs.
|
||||||
|
Texts: modules:<app>.config.<key>.label (+ .hint optional, + .choices.<value> for each
|
||||||
|
choice), checked by tests/test_module_texts.py."""
|
||||||
|
key: str
|
||||||
|
type: ConfigType
|
||||||
|
default: object = None
|
||||||
|
choices: tuple = () # enum, or int limited to these values
|
||||||
|
min: Optional[int] = None # int
|
||||||
|
max: Optional[int] = None # int
|
||||||
|
choices_from: Optional[str] = None # ref: "prep_zones" | "devices:<app_key>"; value = id or None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class DeviceApp:
|
class DeviceApp:
|
||||||
"""For kind="app" modules that run on a paired device (step 1.8, D-8)."""
|
"""For kind="app" modules that run on a paired device (step 1.8, D-8)."""
|
||||||
login_modes: tuple[str, ...] = ("pin", "tap", "password")
|
login_modes: tuple[str, ...] = ("pin", "tap", "password")
|
||||||
scope: tuple[str, ...] = () # permission-key patterns the device token may use
|
scope: tuple[str, ...] = () # permission-key patterns the device token may use
|
||||||
|
config: tuple[ConfigField, ...] = () # per-device settings (3.1a)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ Agent notes:
|
|||||||
device_id binds it to that device, and a new login on the device replaces the old one),
|
device_id binds it to that device, and a new login on the device replaces the old one),
|
||||||
"support" (1.10).
|
"support" (1.10).
|
||||||
- Never trust a JWT alone: always go through validate().
|
- Never trust a JWT alone: always go through validate().
|
||||||
|
- Ending a session also closes its live sockets (services.ws_bus.end_session, plan 3.1a).
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -100,6 +101,8 @@ def _end_row(row, reason: str) -> None:
|
|||||||
row.end_reason = reason
|
row.end_reason = reason
|
||||||
with _lock:
|
with _lock:
|
||||||
_cache.pop(row.id, None)
|
_cache.pop(row.id, None)
|
||||||
|
from services import ws_bus
|
||||||
|
ws_bus.end_session(row.id, reason) # its open sockets get session.ended and close (3.1a)
|
||||||
logger.info("session.ended sid=%s user=%s client=%s reason=%s", row.id[:8], row.user_id, row.client, reason)
|
logger.info("session.ended sid=%s user=%s client=%s reason=%s", row.id[:8], row.user_id, row.client, reason)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""sync_events.target_device_ids: live events addressed to paired devices (plan step 3.1a)
|
||||||
|
|
||||||
|
Revision ID: 0014_sync_event_devices
|
||||||
|
Revises: 0013_product_categories
|
||||||
|
Create Date: 2026-11-14 18:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = '0014_sync_event_devices'
|
||||||
|
down_revision = '0013_product_categories'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('sync_events', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('target_device_ids', sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('sync_events', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('target_device_ids')
|
||||||
@@ -19,5 +19,6 @@ class SyncEvent(Base):
|
|||||||
id = Column(Integer, primary_key=True)
|
id = Column(Integer, primary_key=True)
|
||||||
event_type = Column(String, nullable=False)
|
event_type = Column(String, nullable=False)
|
||||||
payload = Column(Text, nullable=False)
|
payload = Column(Text, nullable=False)
|
||||||
target_user_ids = Column(Text, nullable=True)
|
target_user_ids = Column(Text, nullable=True) # JSON list; NULL = not addressed to users
|
||||||
|
target_device_ids = Column(Text, nullable=True) # JSON list of devices (plan 3.1a); NULL = none
|
||||||
created_at = Column(UTCDateTime, nullable=False, index=True)
|
created_at = Column(UTCDateTime, nullable=False, index=True)
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import DeviceApp, Limit, Module, Mount, Perm
|
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
|
||||||
|
|
||||||
|
# Back to the sign-in screen after this many idle minutes (shared screens; 0 = never). Used by
|
||||||
|
# the terminal from step 3.1c.
|
||||||
|
AUTO_SIGN_OUT = ConfigField('auto_sign_out_minutes', 'int', default=0, choices=(0, 2, 5, 10, 30, 60))
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='kds',
|
key='kds',
|
||||||
@@ -14,7 +18,8 @@ MODULE = Module(
|
|||||||
limits=(
|
limits=(
|
||||||
Limit('devices', 'Number of kitchen screens', free=0, licensed_default=1),
|
Limit('devices', 'Number of kitchen screens', free=0, licensed_default=1),
|
||||||
),
|
),
|
||||||
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('kds.*',)),
|
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('kds.*',),
|
||||||
|
config=(AUTO_SIGN_OUT,)),
|
||||||
routers=(
|
routers=(
|
||||||
Mount('routers.kds', '/api/kds'),
|
Mount('routers.kds', '/api/kds'),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import DeviceApp, Limit, Module, Perm
|
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Perm
|
||||||
|
|
||||||
|
# Back to the sign-in screen after this many idle minutes (shared screens; 0 = never). Used by
|
||||||
|
# the terminal from step 3.1c.
|
||||||
|
AUTO_SIGN_OUT = ConfigField('auto_sign_out_minutes', 'int', default=0, choices=(0, 2, 5, 10, 30, 60))
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='pos_counter',
|
key='pos_counter',
|
||||||
@@ -13,5 +17,6 @@ MODULE = Module(
|
|||||||
limits=(
|
limits=(
|
||||||
Limit('devices', 'Number of counter terminals', free=0, licensed_default=1),
|
Limit('devices', 'Number of counter terminals', free=0, licensed_default=1),
|
||||||
),
|
),
|
||||||
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*')),
|
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('pos_counter.*', 'ordering.*'),
|
||||||
|
config=(AUTO_SIGN_OUT,)),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -19,6 +19,11 @@ Agent notes:
|
|||||||
sessions ended). Rows are never deleted.
|
sessions ended). Rows are never deleted.
|
||||||
- Login on a device: POST /api/auth/login {client: "terminal", ...} with the device header
|
- Login on a device: POST /api/auth/login {client: "terminal", ...} with the device header
|
||||||
(routers/auth.py). The login mode is effective_login_mode(); tap/none exist only here.
|
(routers/auth.py). The login mode is effective_login_mode(); tap/none exist only here.
|
||||||
|
- `config` is validated against the app's ConfigFields (core/modules/device_config.py,
|
||||||
|
3.1a); both views return the effective config (every field, defaults filled).
|
||||||
|
- Live (3.1a): an edit sends `device.updated` to the device's open sockets; reassign sends
|
||||||
|
`device.updated` and closes them; revoke sends `device.revoked` and closes them
|
||||||
|
(services/ws_bus.py). The screen re-reads GET /me or goes back to pairing.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -36,12 +41,14 @@ from sqlalchemy.orm import Session
|
|||||||
|
|
||||||
from core import sessions
|
from core import sessions
|
||||||
from core.access.context import hash_token
|
from core.access.context import hash_token
|
||||||
|
from core.modules import device_config
|
||||||
from core.access.deps import public, require, require_device
|
from core.access.deps import public, require, require_device
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
from core.modules.registry import registry
|
from core.modules.registry import registry
|
||||||
from core.timeutil import iso_z, utcnow
|
from core.timeutil import iso_z, utcnow
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from models.device import Device, DevicePairRequest
|
from models.device import Device, DevicePairRequest
|
||||||
|
from services import ws_bus
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@@ -143,6 +150,14 @@ def effective_login_mode(db, device) -> str:
|
|||||||
return mode if mode in modes else modes[0]
|
return mode if mode in modes else modes[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _config(app_key: str, config, db) -> dict | None:
|
||||||
|
return device_config.validate(device_config.for_app(app_key), config, db)
|
||||||
|
|
||||||
|
|
||||||
|
def _effective_config(d: Device, db) -> dict:
|
||||||
|
return device_config.effective(device_config.for_app(d.app_key), d.config, db)
|
||||||
|
|
||||||
|
|
||||||
def _get(db, device_id: int) -> Device:
|
def _get(db, device_id: int) -> Device:
|
||||||
d = db.get(Device, device_id)
|
d = db.get(Device, device_id)
|
||||||
if d is None:
|
if d is None:
|
||||||
@@ -153,7 +168,8 @@ def _get(db, device_id: int) -> Device:
|
|||||||
def _out(d: Device, db) -> dict:
|
def _out(d: Device, db) -> dict:
|
||||||
"""Manager view of a device."""
|
"""Manager view of a device."""
|
||||||
return {
|
return {
|
||||||
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": d.config,
|
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key,
|
||||||
|
"config": _effective_config(d, db) if d.app_key in registry() else {},
|
||||||
"login_mode": d.login_mode,
|
"login_mode": d.login_mode,
|
||||||
"effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None,
|
"effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None,
|
||||||
"linked_device_id": d.linked_device_id, "user_agent": d.user_agent,
|
"linked_device_id": d.linked_device_id, "user_agent": d.user_agent,
|
||||||
@@ -169,7 +185,7 @@ def _self_out(d: Device, db) -> dict:
|
|||||||
linked = db.get(Device, d.linked_device_id) if d.linked_device_id else None
|
linked = db.get(Device, d.linked_device_id) if d.linked_device_id else None
|
||||||
status = "ok" if is_effective(d.app_key, db) else blocked_error(d.app_key, db).code
|
status = "ok" if is_effective(d.app_key, db) else blocked_error(d.app_key, db).code
|
||||||
return {
|
return {
|
||||||
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": d.config,
|
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db),
|
||||||
"login_mode": effective_login_mode(db, d),
|
"login_mode": effective_login_mode(db, d),
|
||||||
"linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key}
|
"linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key}
|
||||||
if linked is not None and linked.revoked_at is None else None),
|
if linked is not None and linked.revoked_at is None else None),
|
||||||
@@ -262,7 +278,8 @@ def approve_device(body: PairApprove, db: Session = Depends(get_db), user=Depend
|
|||||||
_app(body.app_key)
|
_app(body.app_key)
|
||||||
_require_effective(body.app_key, db)
|
_require_effective(body.app_key, db)
|
||||||
_check_limit(db, body.app_key)
|
_check_limit(db, body.app_key)
|
||||||
d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key, config=body.config,
|
d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key,
|
||||||
|
config=_config(body.app_key, body.config, db),
|
||||||
login_mode=_check_mode(body.app_key, body.login_mode),
|
login_mode=_check_mode(body.app_key, body.login_mode),
|
||||||
linked_device_id=_check_link(db, None, body.linked_device_id),
|
linked_device_id=_check_link(db, None, body.linked_device_id),
|
||||||
user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None)
|
user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None)
|
||||||
@@ -308,12 +325,13 @@ def update_device(device_id: int, body: DevicePatch, db: Session = Depends(get_d
|
|||||||
if "name" in sent and body.name:
|
if "name" in sent and body.name:
|
||||||
d.name = body.name.strip()
|
d.name = body.name.strip()
|
||||||
if "config" in sent:
|
if "config" in sent:
|
||||||
d.config = body.config
|
d.config = _config(d.app_key, body.config, db)
|
||||||
if "login_mode" in sent:
|
if "login_mode" in sent:
|
||||||
d.login_mode = _check_mode(d.app_key, body.login_mode)
|
d.login_mode = _check_mode(d.app_key, body.login_mode)
|
||||||
if "linked_device_id" in sent:
|
if "linked_device_id" in sent:
|
||||||
d.linked_device_id = _check_link(db, d.id, body.linked_device_id)
|
d.linked_device_id = _check_link(db, d.id, body.linked_device_id)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
ws_bus.notify_device([d.id])
|
||||||
return _out(d, db)
|
return _out(d, db)
|
||||||
|
|
||||||
|
|
||||||
@@ -328,11 +346,12 @@ def reassign_device(device_id: int, body: DeviceReassign, db: Session = Depends(
|
|||||||
_require_effective(body.app_key, db)
|
_require_effective(body.app_key, db)
|
||||||
if body.app_key != d.app_key:
|
if body.app_key != d.app_key:
|
||||||
_check_limit(db, body.app_key, exclude_id=d.id)
|
_check_limit(db, body.app_key, exclude_id=d.id)
|
||||||
|
d.config = _config(body.app_key, body.config, db)
|
||||||
d.app_key = body.app_key
|
d.app_key = body.app_key
|
||||||
d.config = body.config
|
|
||||||
if d.login_mode and d.login_mode not in _app(body.app_key).device_app.login_modes:
|
if d.login_mode and d.login_mode not in _app(body.app_key).device_app.login_modes:
|
||||||
d.login_mode = None
|
d.login_mode = None
|
||||||
db.commit()
|
db.commit()
|
||||||
|
ws_bus.end_device(d.id, "device.updated", {"app_key": d.app_key}) # before the session's own close
|
||||||
sessions.end_for_device(db, d.id, "device_reassigned")
|
sessions.end_for_device(db, d.id, "device_reassigned")
|
||||||
return _out(d, db)
|
return _out(d, db)
|
||||||
|
|
||||||
@@ -347,5 +366,6 @@ def revoke_device(device_id: int, db: Session = Depends(get_db), user=Depends(re
|
|||||||
db.query(Device).filter(Device.linked_device_id == d.id).update({Device.linked_device_id: None})
|
db.query(Device).filter(Device.linked_device_id == d.id).update({Device.linked_device_id: None})
|
||||||
db.query(DevicePairRequest).filter(DevicePairRequest.device_id == d.id).delete()
|
db.query(DevicePairRequest).filter(DevicePairRequest.device_id == d.id).delete()
|
||||||
db.commit()
|
db.commit()
|
||||||
|
ws_bus.end_device(d.id, "device.revoked")
|
||||||
sessions.end_for_device(db, d.id, "device_revoked")
|
sessions.end_for_device(db, d.id, "device_revoked")
|
||||||
return _out(d, db)
|
return _out(d, db)
|
||||||
|
|||||||
+121
-45
@@ -1,19 +1,36 @@
|
|||||||
"""
|
"""
|
||||||
WebSocket endpoint — one persistent connection per connected client (waiter PWA, KDS).
|
WebSocket endpoint — one persistent connection per client (waiter app, manager, terminal).
|
||||||
|
|
||||||
Authentication: JWT token passed as query param ?token=<jwt>
|
|
||||||
(Same pattern as SSE — browser WebSocket API also cannot set custom headers.)
|
|
||||||
|
|
||||||
Protocol:
|
Protocol:
|
||||||
1. Client connects: ws://host/api/ws?token=<jwt>
|
1. Client connects: ws://host/api/ws/connect (terminal: no query)
|
||||||
2. Client immediately sends: { "cursor": <last_seq_id> }
|
or: ws://host/api/ws/connect?token=<jwt> (waiter, manager)
|
||||||
(0 = first connect / no history; any positive int = resume from that point)
|
2. Client immediately sends its first frame:
|
||||||
3. Server replays all missed events (seq > cursor) as individual frames
|
{ "cursor": <last_seq_id>, "token"?: <jwt>, "device"?: <device token> }
|
||||||
4. Server sends { "type": "ready" } to signal end of replay / start of live stream
|
(cursor 0 = first connect / no history). Credentials in the frame stay out of URLs
|
||||||
5. Live events arrive as: { "seq": 123, "type": "...", "data": { ... } }
|
and proxy logs; the terminal always sends them there.
|
||||||
6. Every 25s server sends: { "type": "ping" }
|
3. Server checks who it is (below). Refused → { "type": "refused", "data": {code} }
|
||||||
7. Client may respond: { "type": "pong" } (ignored if not sent)
|
and close code 4001 (sign in again) or 4003 (device problem).
|
||||||
8. On disconnect/error the client reconnects and repeats from step 2
|
4. Server replays missed events the socket may see (seq > cursor) as individual frames
|
||||||
|
5. Server sends { "type": "ready" } to signal end of replay / start of live stream
|
||||||
|
6. Live events arrive as: { "seq": 123, "type": "...", "data": { ... } }
|
||||||
|
7. Every 25s server sends: { "type": "ping" }; the client may answer { "type": "pong" }
|
||||||
|
8. Control frames (no seq): `device.updated` (re-read /api/devices/me); and before the
|
||||||
|
server closes the socket itself: `session.ended` (4001), `device.revoked` or
|
||||||
|
`device.updated` after an app change (4003).
|
||||||
|
9. On disconnect/error the client reconnects and repeats from step 2
|
||||||
|
|
||||||
|
Who may connect (plan step 3.1a, D-8):
|
||||||
|
- a user session JWT alone (manager, waiter). A terminal session's JWT (bound to a device)
|
||||||
|
only together with that device's token, like routers.deps.user_from_token over HTTP.
|
||||||
|
- a device token alone: a paired screen without a signed-in user. If its app signs nobody
|
||||||
|
in (login mode `none`: customer display, signage, menu tablet) it gets every event;
|
||||||
|
otherwise (a KDS on its sign-in screen) only events addressed to the device.
|
||||||
|
- a device token + a terminal JWT of that device: everything a user socket gets.
|
||||||
|
|
||||||
|
Agent notes:
|
||||||
|
- Auth uses a short-lived DB session (the app's get_db, so tests' override applies) that
|
||||||
|
is closed before streaming starts: an open socket holds no DB connection.
|
||||||
|
- Never log tokens.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from core.access.deps import public
|
from core.access.deps import public
|
||||||
@@ -24,44 +41,99 @@ import logging
|
|||||||
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect, Query
|
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect, Query
|
||||||
from starlette.websockets import WebSocketState
|
from starlette.websockets import WebSocketState
|
||||||
|
|
||||||
from routers.deps import decode_token
|
from core.errors import XeniaError
|
||||||
from services.ws_bus import connect, disconnect, get_events_since
|
from database import get_db
|
||||||
|
from services import ws_bus
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
KEEPALIVE_INTERVAL = 25 # seconds
|
KEEPALIVE_INTERVAL = 25 # seconds
|
||||||
|
FIRST_FRAME_TIMEOUT = 10.0
|
||||||
|
|
||||||
|
|
||||||
|
class Refused(Exception):
|
||||||
|
def __init__(self, code: str, close: int):
|
||||||
|
super().__init__(code)
|
||||||
|
self.code, self.close = code, close
|
||||||
|
|
||||||
|
|
||||||
|
def _with_db(app, fn):
|
||||||
|
"""Run fn(db) with a DB session from the app's get_db (honours dependency overrides)."""
|
||||||
|
gen = app.dependency_overrides.get(get_db, get_db)()
|
||||||
|
db = next(gen)
|
||||||
|
try:
|
||||||
|
return fn(db)
|
||||||
|
finally:
|
||||||
|
gen.close()
|
||||||
|
|
||||||
|
|
||||||
|
def authenticate(db, token: str | None, device_token: str | None) -> dict:
|
||||||
|
"""-> kwargs for ws_bus.connect(). Raises Refused."""
|
||||||
|
from core.access.context import lookup_device
|
||||||
|
from routers.deps import decode_session
|
||||||
|
device = None
|
||||||
|
if device_token:
|
||||||
|
try:
|
||||||
|
device = lookup_device(db, device_token)
|
||||||
|
except XeniaError as e:
|
||||||
|
raise Refused(e.code, ws_bus.CLOSE_DEVICE)
|
||||||
|
if token:
|
||||||
|
try:
|
||||||
|
payload, info = decode_session(token, db)
|
||||||
|
except XeniaError as e:
|
||||||
|
raise Refused(e.code, ws_bus.CLOSE_SESSION)
|
||||||
|
except Exception:
|
||||||
|
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
|
||||||
|
if info.device_id is not None and (device is None or device.id != info.device_id):
|
||||||
|
raise Refused("device.required", ws_bus.CLOSE_DEVICE)
|
||||||
|
user_id = info.user_id if info.user_id is not None else 0 # 0 = the support account
|
||||||
|
if info.user_id is not None:
|
||||||
|
from models.user import User
|
||||||
|
if db.query(User.id).filter(User.id == info.user_id, User.is_active == True).first() is None: # noqa: E712
|
||||||
|
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
|
||||||
|
return {"user_id": user_id, "sid": payload.get("sid"),
|
||||||
|
"device_id": device.id if device else None, "app_key": device.app_key if device else None}
|
||||||
|
if device is None:
|
||||||
|
raise Refused("auth.session_ended", ws_bus.CLOSE_SESSION)
|
||||||
|
from routers.devices import effective_login_mode
|
||||||
|
signs_nobody_in = effective_login_mode(db, device) == "none"
|
||||||
|
return {"device_id": device.id, "app_key": device.app_key, "all_events": signs_nobody_in}
|
||||||
|
|
||||||
|
|
||||||
@router.websocket("/connect", dependencies=[Depends(public())])
|
@router.websocket("/connect", dependencies=[Depends(public())])
|
||||||
async def ws_endpoint(websocket: WebSocket, token: str = Query(...)):
|
async def ws_endpoint(websocket: WebSocket, token: str | None = Query(None)):
|
||||||
# ── Auth ──────────────────────────────────────────────────────────────────
|
|
||||||
try:
|
|
||||||
payload = decode_token(token)
|
|
||||||
user_id: int = int(payload["sub"])
|
|
||||||
except Exception:
|
|
||||||
await websocket.close(code=4001)
|
|
||||||
return
|
|
||||||
|
|
||||||
await websocket.accept()
|
await websocket.accept()
|
||||||
|
|
||||||
# ── Wait for cursor frame ─────────────────────────────────────────────────
|
# ── First frame: cursor (+ credentials) ───────────────────────────────────
|
||||||
cursor = 0
|
cursor, device_token = 0, None
|
||||||
try:
|
try:
|
||||||
raw = await asyncio.wait_for(websocket.receive_text(), timeout=10.0)
|
msg = json.loads(await asyncio.wait_for(websocket.receive_text(), timeout=FIRST_FRAME_TIMEOUT))
|
||||||
msg = json.loads(raw)
|
if isinstance(msg, dict):
|
||||||
cursor = int(msg.get("cursor", 0))
|
cursor = int(msg.get("cursor") or 0)
|
||||||
except (asyncio.TimeoutError, Exception):
|
token = msg.get("token") or token
|
||||||
pass # no cursor sent — treat as fresh connect (cursor=0)
|
device_token = msg.get("device") or None
|
||||||
|
except WebSocketDisconnect:
|
||||||
|
return
|
||||||
|
except Exception:
|
||||||
|
pass # no (valid) first frame: fresh connect, credentials from the query only
|
||||||
|
|
||||||
# ── Register this connection ──────────────────────────────────────────────
|
# ── Auth ──────────────────────────────────────────────────────────────────
|
||||||
q = await connect(user_id)
|
try:
|
||||||
|
who = await asyncio.to_thread(_with_db, websocket.app, lambda db: authenticate(db, token, device_token))
|
||||||
|
except Refused as r:
|
||||||
|
try:
|
||||||
|
await websocket.send_text(json.dumps({"type": "refused", "data": {"code": r.code}}))
|
||||||
|
await websocket.close(code=r.close)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return
|
||||||
|
|
||||||
|
conn = await ws_bus.connect(**who)
|
||||||
try:
|
try:
|
||||||
# ── Replay missed events ──────────────────────────────────────────────
|
# ── Replay missed events ──────────────────────────────────────────────
|
||||||
if cursor > 0:
|
if cursor > 0:
|
||||||
missed = get_events_since(cursor, user_id)
|
for event in await asyncio.to_thread(ws_bus.get_events_since, cursor, conn):
|
||||||
for event in missed:
|
|
||||||
await websocket.send_text(json.dumps(event))
|
await websocket.send_text(json.dumps(event))
|
||||||
|
|
||||||
# Signal end of replay / start of live stream
|
# Signal end of replay / start of live stream
|
||||||
@@ -69,20 +141,24 @@ async def ws_endpoint(websocket: WebSocket, token: str = Query(...)):
|
|||||||
|
|
||||||
# ── Live stream loop ──────────────────────────────────────────────────
|
# ── Live stream loop ──────────────────────────────────────────────────
|
||||||
while True:
|
while True:
|
||||||
|
if conn.closing is not None:
|
||||||
|
frame, code = conn.closing
|
||||||
|
await websocket.send_text(frame)
|
||||||
|
await websocket.close(code=code)
|
||||||
|
break
|
||||||
try:
|
try:
|
||||||
frame = await asyncio.wait_for(q.get(), timeout=KEEPALIVE_INTERVAL)
|
frame = await asyncio.wait_for(conn.queue.get(), timeout=KEEPALIVE_INTERVAL)
|
||||||
if websocket.client_state == WebSocketState.CONNECTED:
|
|
||||||
await websocket.send_text(frame)
|
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
# Send keepalive ping
|
frame = json.dumps({"type": "ping"})
|
||||||
if websocket.client_state == WebSocketState.CONNECTED:
|
if frame is None or conn.closing is not None:
|
||||||
await websocket.send_text(json.dumps({"type": "ping"}))
|
continue # a wake-up: the loop head sends the closing frame
|
||||||
else:
|
if websocket.client_state != WebSocketState.CONNECTED:
|
||||||
break
|
break
|
||||||
|
await websocket.send_text(frame)
|
||||||
|
|
||||||
except WebSocketDisconnect:
|
except WebSocketDisconnect:
|
||||||
pass
|
pass
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug("ws_endpoint: connection closed for user %s: %s", user_id, e)
|
logger.debug("ws_endpoint: connection closed (user %s, device %s): %s", conn.user_id, conn.device_id, e)
|
||||||
finally:
|
finally:
|
||||||
await disconnect(user_id, q)
|
await ws_bus.disconnect(conn)
|
||||||
|
|||||||
@@ -1,32 +1,55 @@
|
|||||||
"""
|
"""
|
||||||
WebSocket Event Bus — replaces sse_bus.py for real-time communication.
|
WebSocket Event Bus — replaces sse_bus.py for real-time communication.
|
||||||
|
|
||||||
Drop-in replacement: all routers continue calling broadcast_sync() unchanged.
|
Routers keep calling sse_bus.broadcast_sync() (which calls broadcast_sync() here).
|
||||||
The WS endpoint uses connect()/disconnect()/replay_missed() to manage clients.
|
The WS endpoint (routers/ws.py) registers each open socket with connect()/disconnect().
|
||||||
|
|
||||||
Protocol (JSON frames):
|
Protocol (JSON frames):
|
||||||
Server → Client: { "seq": 123, "type": "order_updated", "data": { ... } }
|
Server → Client: { "seq": 123, "type": "order_updated", "data": { ... } }
|
||||||
Client → Server: { "cursor": 120 } (sent immediately after connect)
|
Client → Server: { "cursor": 120, ... } (sent immediately after connect)
|
||||||
Server → Client: { "type": "ping" } (every 25s keepalive)
|
Server → Client: { "type": "ping" } (every 25s keepalive)
|
||||||
Client → Server: { "type": "pong" } (optional, ignored if not sent)
|
Client → Server: { "type": "pong" } (optional, ignored if not sent)
|
||||||
|
|
||||||
On connect the client sends its last known seq. The server replays everything
|
On connect the client sends its last known seq. The server replays everything
|
||||||
it has stored since that seq, then switches to live streaming. Events are stored
|
it has stored since that seq, then switches to live streaming. Events are stored
|
||||||
in the sync_events SQLite table (written here, pruned on startup).
|
in the sync_events SQLite table (written here, pruned on startup).
|
||||||
|
|
||||||
|
Who gets what (plan step 3.1a):
|
||||||
|
- Each socket is a Conn: a user (user_id + session sid) and/or a paired device
|
||||||
|
(device_id + app_key). `all_events` is False only for a device socket without a user
|
||||||
|
whose app needs a sign-in (a KDS on its sign-in screen): it gets only events
|
||||||
|
addressed to its device.
|
||||||
|
- broadcast_sync(type, data) every socket with all_events
|
||||||
|
- broadcast_sync(..., user_ids=[...]) sockets of those users
|
||||||
|
- broadcast_sync(..., device_ids=[...]) sockets of those devices (3.4: a POS
|
||||||
|
pushes to its own customer display)
|
||||||
|
(both lists given: either matches)
|
||||||
|
- Control frames, not stored, no seq: notify_device() sends `device.updated`;
|
||||||
|
end_session() / end_device() send `session.ended` / `device.revoked` / `device.updated`
|
||||||
|
and close the socket (routers/ws.py closes with code 4001/4003). They are called by
|
||||||
|
core.sessions when a session ends and by routers/devices.py on revoke/reassign/edit.
|
||||||
|
|
||||||
|
Agent notes:
|
||||||
|
- Each Conn keeps the event loop it runs on; every push goes through
|
||||||
|
loop.call_soon_threadsafe, so broadcast_sync works from sync routes (thread pool), from
|
||||||
|
async code and from the TestClient's per-connection loops alike.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from typing import Dict, Set
|
import threading
|
||||||
from core.timeutil import to_db_str, utcnow
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import timedelta
|
||||||
|
from typing import Iterable, Optional
|
||||||
|
|
||||||
from fastapi import WebSocket
|
from core.timeutil import to_db_str, utcnow
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# ── Event loop (captured once at startup) ────────────────────────────────────
|
QUEUE_SIZE = 512
|
||||||
|
|
||||||
|
# ── Event loop (captured once at startup; kept for callers that still read it) ─
|
||||||
|
|
||||||
_main_loop: asyncio.AbstractEventLoop | None = None
|
_main_loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
|
||||||
@@ -36,24 +59,100 @@ def init_loop(loop: asyncio.AbstractEventLoop) -> None:
|
|||||||
_main_loop = loop
|
_main_loop = loop
|
||||||
|
|
||||||
|
|
||||||
# ── Connected clients: user_id → set of asyncio.Queue ────────────────────────
|
# ── Connected sockets ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
_connections: Dict[int, Set[asyncio.Queue]] = {}
|
@dataclass(eq=False)
|
||||||
|
class Conn:
|
||||||
|
user_id: Optional[int] = None
|
||||||
|
sid: Optional[str] = None
|
||||||
|
device_id: Optional[int] = None
|
||||||
|
app_key: Optional[str] = None
|
||||||
|
all_events: bool = True
|
||||||
|
loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
queue: asyncio.Queue = field(default_factory=lambda: asyncio.Queue(maxsize=QUEUE_SIZE))
|
||||||
|
closing: Optional[tuple[str, int]] = None # (last frame, close code) once it must close
|
||||||
|
|
||||||
|
def sees(self, user_ids: Optional[list[int]], device_ids: Optional[list[int]]) -> bool:
|
||||||
|
if user_ids is None and device_ids is None:
|
||||||
|
return self.all_events
|
||||||
|
return ((user_ids is not None and self.user_id is not None and self.user_id in user_ids)
|
||||||
|
or (device_ids is not None and self.device_id is not None and self.device_id in device_ids))
|
||||||
|
|
||||||
|
|
||||||
async def connect(user_id: int) -> asyncio.Queue:
|
_conns: set[Conn] = set()
|
||||||
q: asyncio.Queue = asyncio.Queue(maxsize=512)
|
_lock = threading.Lock()
|
||||||
if user_id not in _connections:
|
|
||||||
_connections[user_id] = set()
|
|
||||||
_connections[user_id].add(q)
|
|
||||||
return q
|
|
||||||
|
|
||||||
|
|
||||||
async def disconnect(user_id: int, q: asyncio.Queue) -> None:
|
async def connect(user_id: Optional[int] = None, *, sid: str | None = None, device_id: int | None = None,
|
||||||
if user_id in _connections:
|
app_key: str | None = None, all_events: bool = True) -> Conn:
|
||||||
_connections[user_id].discard(q)
|
conn = Conn(user_id=user_id, sid=sid, device_id=device_id, app_key=app_key, all_events=all_events,
|
||||||
if not _connections[user_id]:
|
loop=asyncio.get_running_loop())
|
||||||
del _connections[user_id]
|
with _lock:
|
||||||
|
_conns.add(conn)
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
async def disconnect(conn: Conn) -> None:
|
||||||
|
with _lock:
|
||||||
|
_conns.discard(conn)
|
||||||
|
|
||||||
|
|
||||||
|
def _matching(pred) -> list[Conn]:
|
||||||
|
with _lock:
|
||||||
|
return [c for c in _conns if pred(c)]
|
||||||
|
|
||||||
|
|
||||||
|
def _offer(q: asyncio.Queue, item) -> None:
|
||||||
|
try:
|
||||||
|
q.put_nowait(item)
|
||||||
|
except asyncio.QueueFull:
|
||||||
|
pass # slow client: drop the live frame; it replays on reconnect
|
||||||
|
|
||||||
|
|
||||||
|
def _push(conn: Conn, item) -> None:
|
||||||
|
try:
|
||||||
|
conn.loop.call_soon_threadsafe(_offer, conn.queue, item)
|
||||||
|
except RuntimeError:
|
||||||
|
pass # its loop is gone: the socket is closing anyway
|
||||||
|
|
||||||
|
|
||||||
|
def _close(conns: Iterable[Conn], frame: dict, code: int) -> int:
|
||||||
|
text = json.dumps(frame)
|
||||||
|
n = 0
|
||||||
|
for c in conns:
|
||||||
|
if c.closing is None:
|
||||||
|
c.closing = (text, code)
|
||||||
|
_push(c, None) # wake the socket's loop; it sees `closing` and ends
|
||||||
|
n += 1
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
CLOSE_SESSION = 4001 # session ended / not signed in: sign in again
|
||||||
|
CLOSE_DEVICE = 4003 # device removed / not paired / changed: re-read /api/devices/me
|
||||||
|
|
||||||
|
|
||||||
|
def end_session(sid: str, reason: str) -> int:
|
||||||
|
"""A session ended (core.sessions): its sockets get `session.ended` and close."""
|
||||||
|
return _close(_matching(lambda c: c.sid == sid), {"type": "session.ended", "data": {"reason": reason}},
|
||||||
|
CLOSE_SESSION)
|
||||||
|
|
||||||
|
|
||||||
|
def end_device(device_id: int, event: str = "device.revoked", data: dict | None = None) -> int:
|
||||||
|
"""A device was removed (`device.revoked`) or now runs another app (`device.updated`):
|
||||||
|
every socket of the device gets the event and closes."""
|
||||||
|
return _close(_matching(lambda c: c.device_id == device_id),
|
||||||
|
{"type": event, "data": {"device_id": device_id, **(data or {})}}, CLOSE_DEVICE)
|
||||||
|
|
||||||
|
|
||||||
|
def notify_device(device_ids: Iterable[int] | None = None, *, every_device: bool = False,
|
||||||
|
data: dict | None = None) -> int:
|
||||||
|
"""`device.updated` to the sockets of these devices (or of every paired device): the screen
|
||||||
|
re-reads GET /api/devices/me (config, login mode, app on/off). Not stored."""
|
||||||
|
ids = set(device_ids or ())
|
||||||
|
conns = _matching(lambda c: c.device_id is not None and (every_device or c.device_id in ids))
|
||||||
|
for c in conns:
|
||||||
|
_push(c, json.dumps({"type": "device.updated", "data": {"device_id": c.device_id, **(data or {})}}))
|
||||||
|
return len(conns)
|
||||||
|
|
||||||
|
|
||||||
# ── Persistence helpers ───────────────────────────────────────────────────────
|
# ── Persistence helpers ───────────────────────────────────────────────────────
|
||||||
@@ -63,20 +162,22 @@ def _get_db():
|
|||||||
return SessionLocal()
|
return SessionLocal()
|
||||||
|
|
||||||
|
|
||||||
def _persist_event(event_type: str, data: dict, user_ids: list[int] | None) -> int:
|
def _persist_event(event_type: str, data: dict, user_ids: list[int] | None,
|
||||||
|
device_ids: list[int] | None = None) -> int:
|
||||||
"""Write event to sync_events table, return the new seq_id."""
|
"""Write event to sync_events table, return the new seq_id."""
|
||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
db = _get_db()
|
db = _get_db()
|
||||||
try:
|
try:
|
||||||
result = db.execute(
|
result = db.execute(
|
||||||
text(
|
text(
|
||||||
"INSERT INTO sync_events (event_type, payload, target_user_ids, created_at) "
|
"INSERT INTO sync_events (event_type, payload, target_user_ids, target_device_ids, created_at) "
|
||||||
"VALUES (:et, :payload, :uids, :now)"
|
"VALUES (:et, :payload, :uids, :dids, :now)"
|
||||||
),
|
),
|
||||||
{
|
{
|
||||||
"et": event_type,
|
"et": event_type,
|
||||||
"payload": json.dumps(data),
|
"payload": json.dumps(data),
|
||||||
"uids": json.dumps(user_ids) if user_ids is not None else None,
|
"uids": json.dumps(user_ids) if user_ids is not None else None,
|
||||||
|
"dids": json.dumps(device_ids) if device_ids is not None else None,
|
||||||
"now": to_db_str(utcnow()), # same text format as UTCDateTime
|
"now": to_db_str(utcnow()), # same text format as UTCDateTime
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -86,14 +187,14 @@ def _persist_event(event_type: str, data: dict, user_ids: list[int] | None) -> i
|
|||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
def get_events_since(cursor: int, user_id: int) -> list[dict]:
|
def get_events_since(cursor: int, conn: Conn) -> list[dict]:
|
||||||
"""Return all events with seq_id > cursor that are visible to user_id."""
|
"""All stored events with seq_id > cursor that this socket may see."""
|
||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
db = _get_db()
|
db = _get_db()
|
||||||
try:
|
try:
|
||||||
rows = db.execute(
|
rows = db.execute(
|
||||||
text(
|
text(
|
||||||
"SELECT id, event_type, payload, target_user_ids FROM sync_events "
|
"SELECT id, event_type, payload, target_user_ids, target_device_ids FROM sync_events "
|
||||||
"WHERE id > :cursor ORDER BY id ASC LIMIT 500"
|
"WHERE id > :cursor ORDER BY id ASC LIMIT 500"
|
||||||
),
|
),
|
||||||
{"cursor": cursor},
|
{"cursor": cursor},
|
||||||
@@ -103,13 +204,10 @@ def get_events_since(cursor: int, user_id: int) -> list[dict]:
|
|||||||
|
|
||||||
events = []
|
events = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
target_user_ids = json.loads(row[3]) if row[3] else None
|
uids = json.loads(row[3]) if row[3] else None
|
||||||
if target_user_ids is None or user_id in target_user_ids:
|
dids = json.loads(row[4]) if row[4] else None
|
||||||
events.append({
|
if conn.sees(uids, dids):
|
||||||
"seq": row[0],
|
events.append({"seq": row[0], "type": row[1], "data": json.loads(row[2])})
|
||||||
"type": row[1],
|
|
||||||
"data": json.loads(row[2]),
|
|
||||||
})
|
|
||||||
return events
|
return events
|
||||||
|
|
||||||
|
|
||||||
@@ -131,41 +229,17 @@ def prune_old_events(hours: int = 24) -> int:
|
|||||||
|
|
||||||
# ── Broadcast ─────────────────────────────────────────────────────────────────
|
# ── Broadcast ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def broadcast_sync(event_type: str, data: dict, *, user_ids: list[int] | None = None) -> None:
|
def broadcast_sync(event_type: str, data: dict, *, user_ids: list[int] | None = None,
|
||||||
|
device_ids: list[int] | None = None) -> None:
|
||||||
"""
|
"""
|
||||||
Called from sync route thread-pool workers.
|
Persists the event (so reconnecting clients can replay it), then pushes it to every
|
||||||
Persists the event to DB (so reconnecting clients can replay it),
|
open socket that may see it. Safe from sync routes, async code and any thread.
|
||||||
then schedules an async push to all currently connected sockets.
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
seq_id = _persist_event(event_type, data, user_ids)
|
seq_id = _persist_event(event_type, data, user_ids, device_ids)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("ws_bus: failed to persist event %s", event_type)
|
logger.exception("ws_bus: failed to persist event %s", event_type)
|
||||||
seq_id = 0
|
seq_id = 0
|
||||||
|
|
||||||
if _main_loop is None:
|
|
||||||
return
|
|
||||||
_main_loop.call_soon_threadsafe(
|
|
||||||
_main_loop.create_task,
|
|
||||||
_broadcast_live(seq_id, event_type, data, user_ids),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def _broadcast_live(
|
|
||||||
seq_id: int,
|
|
||||||
event_type: str,
|
|
||||||
data: dict,
|
|
||||||
user_ids: list[int] | None,
|
|
||||||
) -> None:
|
|
||||||
frame = json.dumps({"seq": seq_id, "type": event_type, "data": data})
|
frame = json.dumps({"seq": seq_id, "type": event_type, "data": data})
|
||||||
targets = (
|
for c in _matching(lambda c: c.sees(user_ids, device_ids)):
|
||||||
{uid: qs for uid, qs in _connections.items() if uid in user_ids}
|
_push(c, frame)
|
||||||
if user_ids is not None
|
|
||||||
else dict(_connections)
|
|
||||||
)
|
|
||||||
for qs in targets.values():
|
|
||||||
for q in list(qs):
|
|
||||||
try:
|
|
||||||
q.put_nowait(frame)
|
|
||||||
except asyncio.QueueFull:
|
|
||||||
pass # slow client — drop live frame; they'll replay on reconnect
|
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ def test_pairing_flow(client, owner_h):
|
|||||||
# the manager types the code (case and dashes don't matter)
|
# the manager types the code (case and dashes don't matter)
|
||||||
typed = f"{code[:3].lower()}-{code[3:]}"
|
typed = f"{code[:3].lower()}-{code[3:]}"
|
||||||
r = client.post("/api/devices", headers=owner_h,
|
r = client.post("/api/devices", headers=owner_h,
|
||||||
json={"code": typed, "app_key": "kds", "name": "Bar KDS", "config": {"prep_zone_id": 2}})
|
json={"code": typed, "app_key": "kds", "name": "Bar KDS", "config": {"auto_sign_out_minutes": 5}})
|
||||||
assert r.status_code == 201, r.text
|
assert r.status_code == 201, r.text
|
||||||
d = r.json()
|
d = r.json()
|
||||||
assert d["claimed"] is False and d["user_agent"] == "KDS-Box" and d["effective_login_mode"] == "pin"
|
assert d["claimed"] is False and d["user_agent"] == "KDS-Box" and d["effective_login_mode"] == "pin"
|
||||||
@@ -74,7 +74,7 @@ def test_pairing_flow(client, owner_h):
|
|||||||
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
|
poll = client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})
|
||||||
assert poll.status_code == 200
|
assert poll.status_code == 200
|
||||||
token = poll.json()["device_token"]
|
token = poll.json()["device_token"]
|
||||||
assert poll.json()["device"]["config"] == {"prep_zone_id": 2} and poll.json()["device"]["app_status"] == "ok"
|
assert poll.json()["device"]["config"] == {"auto_sign_out_minutes": 5} and poll.json()["device"]["app_status"] == "ok"
|
||||||
# the token is handed out exactly once
|
# the token is handed out exactly once
|
||||||
assert err(client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})) \
|
assert err(client.get(f"/api/devices/pair-request/{code}", headers={"X-Xenia-Pair-Secret": secret})) \
|
||||||
== "device.pair_code_invalid"
|
== "device.pair_code_invalid"
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
"""Live connection for users and paired devices, device config (plan step 3.1a)."""
|
||||||
|
import pytest
|
||||||
|
from starlette.websockets import WebSocketDisconnect
|
||||||
|
|
||||||
|
from conftest import TEST_PIN
|
||||||
|
from core.modules import device_config
|
||||||
|
from core.modules.model import ConfigField
|
||||||
|
from services import ws_bus
|
||||||
|
|
||||||
|
WS = "/api/ws/connect"
|
||||||
|
|
||||||
|
|
||||||
|
def err(r):
|
||||||
|
return r.json()["error"]["code"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def owner_h(make_user, login):
|
||||||
|
return login(make_user(role="owner"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def pair(client, owner_h):
|
||||||
|
def _pair(app_key, name=None, **fields):
|
||||||
|
req = client.post("/api/devices/pair-request").json()
|
||||||
|
r = client.post("/api/devices", headers=owner_h,
|
||||||
|
json={"code": req["code"], "app_key": app_key, "name": name or f"{app_key} screen", **fields})
|
||||||
|
if r.status_code != 201:
|
||||||
|
return None, r
|
||||||
|
poll = client.get(f"/api/devices/pair-request/{req['code']}", headers={"X-Xenia-Pair-Secret": req["secret"]})
|
||||||
|
return poll.json()["device_token"], r
|
||||||
|
return _pair
|
||||||
|
|
||||||
|
|
||||||
|
def terminal_login(client, token, user):
|
||||||
|
r = client.post("/api/auth/login", headers={"X-Xenia-Device": token},
|
||||||
|
json={"client": "terminal", "user_id": user.id, "pin": TEST_PIN})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
return r.json()["access_token"]
|
||||||
|
|
||||||
|
|
||||||
|
def open_ws(client, **first):
|
||||||
|
ws = client.websocket_connect(WS)
|
||||||
|
sock = ws.__enter__()
|
||||||
|
sock.send_json({"cursor": 0, **first})
|
||||||
|
return ws, sock
|
||||||
|
|
||||||
|
|
||||||
|
def expect_ready(sock):
|
||||||
|
assert sock.receive_json() == {"type": "ready"}
|
||||||
|
|
||||||
|
|
||||||
|
def expect_refused(client, code, close, **first):
|
||||||
|
ws, sock = open_ws(client, **first)
|
||||||
|
try:
|
||||||
|
assert sock.receive_json() == {"type": "refused", "data": {"code": code}}
|
||||||
|
with pytest.raises(WebSocketDisconnect) as e:
|
||||||
|
sock.receive_json()
|
||||||
|
assert e.value.code == close
|
||||||
|
finally:
|
||||||
|
ws.__exit__(None, None, None)
|
||||||
|
|
||||||
|
|
||||||
|
def expect_closed(sock, close):
|
||||||
|
with pytest.raises(WebSocketDisconnect) as e:
|
||||||
|
sock.receive_json()
|
||||||
|
assert e.value.code == close
|
||||||
|
|
||||||
|
|
||||||
|
# ── who may connect ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_user_token_in_query_still_works(client, make_user, login):
|
||||||
|
h = login(make_user(role="waiter"), "waiter")
|
||||||
|
with client.websocket_connect(f"{WS}?token={h['Authorization'][7:]}") as sock:
|
||||||
|
sock.send_json({"cursor": 0})
|
||||||
|
expect_ready(sock)
|
||||||
|
ws_bus.broadcast_sync("order_updated", {"order_id": 1})
|
||||||
|
assert sock.receive_json() == {"seq": 0, "type": "order_updated", "data": {"order_id": 1}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_nothing_or_garbage_is_refused(client):
|
||||||
|
expect_refused(client, "auth.session_ended", 4001)
|
||||||
|
expect_refused(client, "auth.session_ended", 4001, token="nope")
|
||||||
|
expect_refused(client, "device.not_paired", 4003, device="nope")
|
||||||
|
|
||||||
|
|
||||||
|
def test_device_only_socket_of_a_login_none_app_gets_events(client, pair): # "done when" 1
|
||||||
|
token, _ = pair("customer_display")
|
||||||
|
ws, sock = open_ws(client, device=token)
|
||||||
|
try:
|
||||||
|
expect_ready(sock)
|
||||||
|
ws_bus.broadcast_sync("product_updated", {"id": 7})
|
||||||
|
assert sock.receive_json()["type"] == "product_updated"
|
||||||
|
finally:
|
||||||
|
ws.__exit__(None, None, None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_device_only_socket_of_a_sign_in_app_gets_only_its_own_events(client, pair):
|
||||||
|
token, r = pair("kds")
|
||||||
|
dev_id = r.json()["id"]
|
||||||
|
other, r2 = pair("kds", "other")
|
||||||
|
ws, sock = open_ws(client, device=token)
|
||||||
|
try:
|
||||||
|
expect_ready(sock)
|
||||||
|
ws_bus.broadcast_sync("order_updated", {"order_id": 1}) # needs a signed-in chef
|
||||||
|
ws_bus.broadcast_sync("for_other", {}, device_ids=[r2.json()["id"]])
|
||||||
|
ws_bus.broadcast_sync("display", {"n": 1}, device_ids=[dev_id])
|
||||||
|
assert sock.receive_json() == {"seq": 0, "type": "display", "data": {"n": 1}}
|
||||||
|
finally:
|
||||||
|
ws.__exit__(None, None, None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_terminal_jwt_needs_its_device(client, pair, make_user): # "done when" 2
|
||||||
|
token, _ = pair("kds")
|
||||||
|
other, _ = pair("kds", "other")
|
||||||
|
jwt = terminal_login(client, token, make_user(role="chef"))
|
||||||
|
expect_refused(client, "device.required", 4003, token=jwt)
|
||||||
|
expect_refused(client, "device.required", 4003, token=jwt, device=other)
|
||||||
|
ws, sock = open_ws(client, token=jwt, device=token)
|
||||||
|
try:
|
||||||
|
expect_ready(sock)
|
||||||
|
ws_bus.broadcast_sync("order_updated", {"order_id": 2}) # a chef sees everything
|
||||||
|
assert sock.receive_json()["type"] == "order_updated"
|
||||||
|
finally:
|
||||||
|
ws.__exit__(None, None, None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_revoking_a_device_closes_its_sockets(client, pair, owner_h, make_user): # "done when" 3
|
||||||
|
token, r = pair("kds")
|
||||||
|
dev_id = r.json()["id"]
|
||||||
|
jwt = terminal_login(client, token, make_user(role="chef"))
|
||||||
|
ws1, user_sock = open_ws(client, token=jwt, device=token)
|
||||||
|
ws2, dev_sock = open_ws(client, device=token)
|
||||||
|
try:
|
||||||
|
expect_ready(user_sock)
|
||||||
|
expect_ready(dev_sock)
|
||||||
|
assert client.post(f"/api/devices/{dev_id}/revoke", headers=owner_h).status_code == 200
|
||||||
|
for sock in (user_sock, dev_sock):
|
||||||
|
assert sock.receive_json() == {"type": "device.revoked", "data": {"device_id": dev_id}}
|
||||||
|
expect_closed(sock, 4003)
|
||||||
|
finally:
|
||||||
|
ws1.__exit__(None, None, None)
|
||||||
|
ws2.__exit__(None, None, None)
|
||||||
|
expect_refused(client, "device.revoked", 4003, device=token)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ending_a_session_closes_its_socket(client, make_user, login, owner_h):
|
||||||
|
w = make_user(role="waiter")
|
||||||
|
h = login(w, "waiter")
|
||||||
|
ws, sock = open_ws(client, token=h["Authorization"][7:])
|
||||||
|
try:
|
||||||
|
expect_ready(sock)
|
||||||
|
sid = next(s for s in client.get("/api/auth/sessions", headers=owner_h).json() if s["user_id"] == w.id)["id"]
|
||||||
|
assert client.post(f"/api/auth/sessions/{sid}/end", headers=owner_h).status_code == 200
|
||||||
|
msg = sock.receive_json()
|
||||||
|
assert msg["type"] == "session.ended" and msg["data"]["reason"]
|
||||||
|
expect_closed(sock, 4001)
|
||||||
|
finally:
|
||||||
|
ws.__exit__(None, None, None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_reassign_and_edit_tell_the_device(client, pair, owner_h):
|
||||||
|
token, r = pair("kds")
|
||||||
|
dev_id = r.json()["id"]
|
||||||
|
ws, sock = open_ws(client, device=token)
|
||||||
|
try:
|
||||||
|
expect_ready(sock)
|
||||||
|
assert client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"name": "Grill"}).status_code == 200
|
||||||
|
assert sock.receive_json() == {"type": "device.updated", "data": {"device_id": dev_id}}
|
||||||
|
assert client.put("/api/platform/modules/tabs", headers=owner_h, json={"enabled": False}).status_code == 200
|
||||||
|
assert sock.receive_json()["type"] == "device.updated"
|
||||||
|
assert client.post(f"/api/devices/{dev_id}/reassign", headers=owner_h,
|
||||||
|
json={"app_key": "pos_counter"}).status_code == 200
|
||||||
|
assert sock.receive_json() == {"type": "device.updated", "data": {"device_id": dev_id, "app_key": "pos_counter"}}
|
||||||
|
expect_closed(sock, 4003)
|
||||||
|
finally:
|
||||||
|
ws.__exit__(None, None, None)
|
||||||
|
|
||||||
|
|
||||||
|
# ── device config ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_config_validated_and_effective(client, pair, owner_h): # "done when" 4
|
||||||
|
_, r = pair("kds", config={"auto_sign_out_minutes": 7})
|
||||||
|
assert r.status_code == 422 and err(r) == "validation.device_config"
|
||||||
|
assert r.json()["error"]["params"] == {"key": "auto_sign_out_minutes"}
|
||||||
|
_, r = pair("kds", config={"colour": "red"})
|
||||||
|
assert err(r) == "validation.device_config"
|
||||||
|
|
||||||
|
token, r = pair("kds")
|
||||||
|
assert r.json()["config"] == {"auto_sign_out_minutes": 0} # defaults filled
|
||||||
|
dev_id = r.json()["id"]
|
||||||
|
r = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"config": {"auto_sign_out_minutes": 5}})
|
||||||
|
assert r.status_code == 200 and r.json()["config"] == {"auto_sign_out_minutes": 5}
|
||||||
|
assert client.get("/api/devices/me", headers={"X-Xenia-Device": token}).json()["config"] \
|
||||||
|
== {"auto_sign_out_minutes": 5}
|
||||||
|
assert err(client.patch(f"/api/devices/{dev_id}", headers=owner_h,
|
||||||
|
json={"config": {"auto_sign_out_minutes": True}})) == "validation.device_config"
|
||||||
|
# an app without config fields refuses any key
|
||||||
|
r = client.post(f"/api/devices/{dev_id}/reassign", headers=owner_h,
|
||||||
|
json={"app_key": "customer_display", "config": {"auto_sign_out_minutes": 5}})
|
||||||
|
assert err(r) == "validation.device_config"
|
||||||
|
|
||||||
|
|
||||||
|
def test_module_catalogue_describes_config(client, owner_h):
|
||||||
|
mods = {m["key"]: m for m in client.get("/api/platform/modules", headers=owner_h).json()["modules"]}
|
||||||
|
assert mods["kds"]["device_app"]["config"] == [{"key": "auto_sign_out_minutes", "type": "int", "default": 0,
|
||||||
|
"choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None,
|
||||||
|
"choices_from": None}]
|
||||||
|
assert mods["customer_display"]["device_app"]["config"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_field_types(db, pair):
|
||||||
|
from models.prep_zone import PrepZone
|
||||||
|
zone = PrepZone(name="Grill")
|
||||||
|
db.add(zone)
|
||||||
|
db.commit()
|
||||||
|
_, r = pair("pos_counter")
|
||||||
|
pos_id = r.json()["id"]
|
||||||
|
fields = (ConfigField("zone", "ref", choices_from="prep_zones"),
|
||||||
|
ConfigField("pos", "ref", choices_from="devices:pos_counter"),
|
||||||
|
ConfigField("sound", "bool", default=True),
|
||||||
|
ConfigField("layout", "enum", default="grid", choices=("grid", "list")),
|
||||||
|
ConfigField("scale", "int", default=100, min=50, max=200),
|
||||||
|
ConfigField("title", "str", default=""))
|
||||||
|
ok = {"zone": zone.id, "pos": pos_id, "sound": False, "layout": "list", "scale": 150, "title": " Bar "}
|
||||||
|
assert device_config.validate(fields, ok, db) == {**ok, "title": "Bar"}
|
||||||
|
assert device_config.validate(fields, {}, db) is None
|
||||||
|
for bad in ({"zone": 99999}, {"pos": zone.id + 99999}, {"sound": "yes"}, {"layout": "tiles"},
|
||||||
|
{"scale": 10}, {"scale": 1.5}, {"title": 5}):
|
||||||
|
with pytest.raises(Exception) as e:
|
||||||
|
device_config.validate(fields, bad, db)
|
||||||
|
assert e.value.code == "validation.device_config"
|
||||||
|
# stale stored values fall back to the default; missing keys get theirs
|
||||||
|
eff = device_config.effective(fields, {"zone": 99999, "layout": "tiles", "scale": 120}, db)
|
||||||
|
assert eff == {"zone": None, "pos": None, "sound": True, "layout": "grid", "scale": 120, "title": ""}
|
||||||
|
assert device_config.effective(fields, "junk") == {f.key: f.default for f in fields}
|
||||||
@@ -46,3 +46,22 @@ def test_every_permission_has_a_label(lang):
|
|||||||
yield from (leaves(f"{prefix}.{k}", v) if isinstance(v, dict) else [f"{prefix}.{k}"])
|
yield from (leaves(f"{prefix}.{k}", v) if isinstance(v, dict) else [f"{prefix}.{k}"])
|
||||||
labelled = {k for mod, t in texts.items() for k in leaves(mod, t.get("permissions", {}))}
|
labelled = {k for mod, t in texts.items() for k in leaves(mod, t.get("permissions", {}))}
|
||||||
assert labelled - known == set(), "labels for permissions that don't exist"
|
assert labelled - known == set(), "labels for permissions that don't exist"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("lang", ["en", "el"])
|
||||||
|
def test_every_device_config_field_has_texts(lang):
|
||||||
|
"""modules:<app>.config.<key>.label, and .choices.<value> for every choice (plan step 3.1a)."""
|
||||||
|
texts = json.loads((LOCALES / lang / "modules.json").read_text(encoding="utf-8"))
|
||||||
|
missing, known = [], set()
|
||||||
|
for m in registry().values():
|
||||||
|
for f in (m.device_app.config if m.device_app else ()):
|
||||||
|
t = texts.get(m.key, {}).get("config", {}).get(f.key, {})
|
||||||
|
if not t.get("label"):
|
||||||
|
missing.append(f"{m.key}.config.{f.key}.label")
|
||||||
|
for c in f.choices:
|
||||||
|
if not t.get("choices", {}).get(str(c)):
|
||||||
|
missing.append(f"{m.key}.config.{f.key}.choices.{c}")
|
||||||
|
known.add((m.key, f.key))
|
||||||
|
assert missing == []
|
||||||
|
extra = {(mod, k) for mod, t in texts.items() for k in t.get("config", {})} - known
|
||||||
|
assert extra == set(), "texts for device settings that don't exist"
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
// Per-device settings of an app, rendered from its manifest (plan step 3.1a): the
|
||||||
|
// fields come from GET /api/platform/modules → device_app.config, the texts from
|
||||||
|
// modules:<app>.config.<key>.{label,hint,choices.<value>}. The backend validates them
|
||||||
|
// (validation.device_config). Used by the pair and edit dialogs of DevicesPage.
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { useTranslation } from '@xenia/i18n'
|
||||||
|
import { Field, Input, Select, Switch } from '@xenia/ui'
|
||||||
|
import client from '../../api/client'
|
||||||
|
import { configValue, refOptions } from './devicesLogic'
|
||||||
|
|
||||||
|
export default function DeviceConfigFields({ appKey, fields = [], value, onChange, devices = [], selfId = null }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const needsZones = fields.some(f => f.choices_from === 'prep_zones')
|
||||||
|
const [zones, setZones] = useState([])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!needsZones) return undefined
|
||||||
|
let alive = true
|
||||||
|
client.get('/api/prep-zones').then(r => { if (alive) setZones(r.data) }).catch(() => {})
|
||||||
|
return () => { alive = false }
|
||||||
|
}, [needsZones])
|
||||||
|
|
||||||
|
if (!fields.length) return null
|
||||||
|
const base = key => `modules:${appKey}.config.${key}`
|
||||||
|
const set = (f, raw) => onChange({ ...value, [f.key]: configValue(f, raw) })
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid gap-4" data-testid="device-config">
|
||||||
|
{fields.map(f => {
|
||||||
|
const label = t(`${base(f.key)}.label`, { defaultValue: f.key })
|
||||||
|
const hint = t(`${base(f.key)}.hint`, { defaultValue: '' }) || undefined
|
||||||
|
const v = value?.[f.key]
|
||||||
|
if (f.type === 'bool') {
|
||||||
|
return <Switch key={f.key} checked={!!v} onChange={on => set(f, on)} label={label} description={hint} data-config={f.key} />
|
||||||
|
}
|
||||||
|
if (f.choices?.length) {
|
||||||
|
return (
|
||||||
|
<Field key={f.key} label={label} hint={hint}>
|
||||||
|
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
|
||||||
|
options={f.choices.map(c => ({ value: String(c), label: t(`${base(f.key)}.choices.${c}`, { defaultValue: String(c) }) }))} />
|
||||||
|
</Field>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (f.type === 'ref') {
|
||||||
|
return (
|
||||||
|
<Field key={f.key} label={label} hint={hint}>
|
||||||
|
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
|
||||||
|
options={[{ value: '', label: t('devices.form.none') }, ...refOptions(f, { zones, devices, selfId })]} />
|
||||||
|
</Field>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Field key={f.key} label={label} hint={hint}>
|
||||||
|
<Input type={f.type === 'int' ? 'number' : 'text'} value={v ?? ''} min={f.min ?? undefined} max={f.max ?? undefined}
|
||||||
|
onChange={e => set(f, e.target.value)} data-config={f.key} />
|
||||||
|
</Field>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -6,7 +6,8 @@
|
|||||||
// (license.limit_reached).
|
// (license.limit_reached).
|
||||||
// - Edit (name, sign-in mode, link) → PATCH; change app → POST /reassign (signs out whoever
|
// - Edit (name, sign-in mode, link) → PATCH; change app → POST /reassign (signs out whoever
|
||||||
// is on it); remove → POST /revoke (the device goes back to its pairing screen).
|
// is on it); remove → POST /revoke (the device goes back to its pairing screen).
|
||||||
// Per-app settings (e.g. a KDS's prep zone) arrive with the apps themselves in phase 3.
|
// - Per-app settings (3.1a): each app's device_app.config fields are rendered by
|
||||||
|
// DeviceConfigFields in the pair and edit dialogs and sent as `config`.
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
import toast from 'react-hot-toast'
|
import toast from 'react-hot-toast'
|
||||||
import { MonitorSmartphone, Plus } from 'lucide-react'
|
import { MonitorSmartphone, Plus } from 'lucide-react'
|
||||||
@@ -14,7 +15,8 @@ import { errorMessage, parseError } from '@xenia/api'
|
|||||||
import { useTranslation, useFormat } from '@xenia/i18n'
|
import { useTranslation, useFormat } from '@xenia/i18n'
|
||||||
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner } from '@xenia/ui'
|
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner } from '@xenia/ui'
|
||||||
import client from '../../api/client'
|
import client from '../../api/client'
|
||||||
import { deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from './devicesLogic'
|
import DeviceConfigFields from './DeviceConfigFields'
|
||||||
|
import { configInitial, deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from './devicesLogic'
|
||||||
|
|
||||||
const STATUS_TONE = {
|
const STATUS_TONE = {
|
||||||
online: 'bg-success-soft text-success-ink',
|
online: 'bg-success-soft text-success-ink',
|
||||||
@@ -206,8 +208,10 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, onClose, onPair
|
|||||||
const [name, setName] = useState('')
|
const [name, setName] = useState('')
|
||||||
const [mode, setMode] = useState('')
|
const [mode, setMode] = useState('')
|
||||||
const [link, setLink] = useState('')
|
const [link, setLink] = useState('')
|
||||||
const { busy, error, run } = useSubmit(onPair)
|
|
||||||
const app = apps.find(a => a.key === appKey)
|
const app = apps.find(a => a.key === appKey)
|
||||||
|
const fields = app?.device_app?.config || []
|
||||||
|
const [config, setConfig] = useState(() => configInitial(fields))
|
||||||
|
const { busy, error, run } = useSubmit(onPair)
|
||||||
const full = appKey && !hasRoom(usage, appKey)
|
const full = appKey && !hasRoom(usage, appKey)
|
||||||
const modes = loginModeOptions(app, t)
|
const modes = loginModeOptions(app, t)
|
||||||
const ready = code.length === 6 && appKey && name.trim() && !full
|
const ready = code.length === 6 && appKey && name.trim() && !full
|
||||||
@@ -215,7 +219,8 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, onClose, onPair
|
|||||||
const submit = e => {
|
const submit = e => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
if (!ready || busy) return
|
if (!ready || busy) return
|
||||||
run({ code, app_key: appKey, name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null })
|
run({ code, app_key: appKey, name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null,
|
||||||
|
config: fields.length ? config : null })
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -230,7 +235,11 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, onClose, onPair
|
|||||||
className="font-mono tracking-[0.3em] text-center uppercase" autoFocus />
|
className="font-mono tracking-[0.3em] text-center uppercase" autoFocus />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: limitLabel(appKey), max: usage[appKey].max }) : undefined}>
|
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: limitLabel(appKey), max: usage[appKey].max }) : undefined}>
|
||||||
<Select value={appKey} onChange={e => { setAppKey(e.target.value); setMode('') }}
|
<Select value={appKey} onChange={e => {
|
||||||
|
const next = e.target.value
|
||||||
|
setAppKey(next); setMode('')
|
||||||
|
setConfig(configInitial(apps.find(a => a.key === next)?.device_app?.config))
|
||||||
|
}}
|
||||||
options={usable.map(a => ({ value: a.key, label: appName(a.key) }))} />
|
options={usable.map(a => ({ value: a.key, label: appName(a.key) }))} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label={t('devices.form.name')}>
|
<Field label={t('devices.form.name')}>
|
||||||
@@ -247,6 +256,7 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, onClose, onPair
|
|||||||
options={[{ value: '', label: t('devices.form.noLink') }, ...linkTargets(devices).map(d => ({ value: String(d.id), label: d.name }))]} />
|
options={[{ value: '', label: t('devices.form.noLink') }, ...linkTargets(devices).map(d => ({ value: String(d.id), label: d.name }))]} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
|
<DeviceConfigFields appKey={appKey} fields={fields} value={config} onChange={setConfig} devices={devices} />
|
||||||
{error && <p className="text-label text-danger-ink" role="alert" data-testid="pair-error">{error}</p>}
|
{error && <p className="text-label text-danger-ink" role="alert" data-testid="pair-error">{error}</p>}
|
||||||
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
|
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
|
||||||
</form>
|
</form>
|
||||||
@@ -260,14 +270,18 @@ function EditDialog({ device, apps, devices, onClose, onSave }) {
|
|||||||
const [name, setName] = useState(device.name)
|
const [name, setName] = useState(device.name)
|
||||||
const [mode, setMode] = useState(device.login_mode || '')
|
const [mode, setMode] = useState(device.login_mode || '')
|
||||||
const [link, setLink] = useState(device.linked_device_id ? String(device.linked_device_id) : '')
|
const [link, setLink] = useState(device.linked_device_id ? String(device.linked_device_id) : '')
|
||||||
|
const app = apps.find(a => a.key === device.app_key)
|
||||||
|
const fields = app?.device_app?.config || []
|
||||||
|
const [config, setConfig] = useState(() => configInitial(fields, device.config))
|
||||||
const { busy, error, run } = useSubmit(onSave)
|
const { busy, error, run } = useSubmit(onSave)
|
||||||
const modes = loginModeOptions(apps.find(a => a.key === device.app_key), t)
|
const modes = loginModeOptions(app, t)
|
||||||
const targets = linkTargets(devices, device.id)
|
const targets = linkTargets(devices, device.id)
|
||||||
|
|
||||||
const submit = e => {
|
const submit = e => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
if (!name.trim() || busy) return
|
if (!name.trim() || busy) return
|
||||||
run({ name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null })
|
run({ name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null,
|
||||||
|
...(fields.length ? { config } : {}) })
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -288,6 +302,7 @@ function EditDialog({ device, apps, devices, onClose, onSave }) {
|
|||||||
options={[{ value: '', label: t('devices.form.noLink') }, ...targets.map(d => ({ value: String(d.id), label: d.name }))]} />
|
options={[{ value: '', label: t('devices.form.noLink') }, ...targets.map(d => ({ value: String(d.id), label: d.name }))]} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
|
<DeviceConfigFields appKey={device.app_key} fields={fields} value={config} onChange={setConfig} devices={devices} selfId={device.id} />
|
||||||
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
|
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
|
||||||
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
|
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -53,3 +53,31 @@ export function hasRoom(usage, appKey, { moving = false } = {}) {
|
|||||||
export function linkTargets(devices, selfId = null) {
|
export function linkTargets(devices, selfId = null) {
|
||||||
return devices.filter(d => !d.revoked_at && d.id !== selfId)
|
return devices.filter(d => !d.revoked_at && d.id !== selfId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── per-device settings (plan step 3.1a) ────────────────────────────────────
|
||||||
|
// `fields` = the app's device_app.config from GET /api/platform/modules:
|
||||||
|
// [{ key, type: 'bool'|'int'|'str'|'enum'|'ref', default, choices, min, max, choices_from }]
|
||||||
|
|
||||||
|
/** The form's starting values: the device's config (already effective) or the defaults. */
|
||||||
|
export function configInitial(fields = [], current = null) {
|
||||||
|
return Object.fromEntries(fields.map(f => [f.key, current && f.key in current ? current[f.key] : f.default]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A form control's raw value → the value sent to the API (selects and inputs give strings). */
|
||||||
|
export function configValue(field, raw) {
|
||||||
|
if (field.type === 'bool') return !!raw
|
||||||
|
if (field.type === 'int') return raw === '' || raw == null ? null : Number(raw)
|
||||||
|
if (field.type === 'ref') return raw === '' || raw == null ? null : Number(raw)
|
||||||
|
if (field.type === 'enum') return raw
|
||||||
|
return raw == null ? '' : String(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Options of a `ref` field: prep zones, or live devices of one app ("devices:<app>"). */
|
||||||
|
export function refOptions(field, { zones = [], devices = [], selfId = null } = {}) {
|
||||||
|
if (field.choices_from === 'prep_zones') return zones.map(z => ({ value: String(z.id), label: z.name }))
|
||||||
|
if (field.choices_from?.startsWith('devices:')) {
|
||||||
|
const app = field.choices_from.slice('devices:'.length)
|
||||||
|
return devices.filter(d => !d.revoked_at && d.app_key === app && d.id !== selfId).map(d => ({ value: String(d.id), label: d.name }))
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// Pure logic of the platform pages (plan steps 2.6c, 2.6d, 2.6e).
|
// Pure logic of the platform pages (plan steps 2.6c, 2.6d, 2.6e).
|
||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { test } from 'node:test'
|
import { test } from 'node:test'
|
||||||
import { deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from '../src/pages/platform/devicesLogic.js'
|
import { configInitial, configValue, deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode, refOptions } from '../src/pages/platform/devicesLogic.js'
|
||||||
import { moduleState, stoppedBy } from '../src/pages/platform/modulesLogic.js'
|
import { moduleState, stoppedBy } from '../src/pages/platform/modulesLogic.js'
|
||||||
import {
|
import {
|
||||||
approvalState, approvalTarget, canEndSession, canGive, diff, differsFromRole, editorGroups, permLabelKey, resetToRole,
|
approvalState, approvalTarget, canEndSession, canGive, diff, differsFromRole, editorGroups, permLabelKey, resetToRole,
|
||||||
@@ -116,3 +116,23 @@ test('approvals and sessions', () => {
|
|||||||
assert.equal(canEndSession({ ...s, client: 'support' }), false)
|
assert.equal(canEndSession({ ...s, client: 'support' }), false)
|
||||||
assert.equal(canEndSession({ ...s, client: 'support' }, { actorIsSuperadmin: true }), true)
|
assert.equal(canEndSession({ ...s, client: 'support' }, { actorIsSuperadmin: true }), true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('device settings: starting values, typed values, ref options (3.1a)', () => {
|
||||||
|
const fields = [
|
||||||
|
{ key: 'auto_sign_out_minutes', type: 'int', default: 0, choices: [0, 5] },
|
||||||
|
{ key: 'zone', type: 'ref', default: null, choices_from: 'prep_zones' },
|
||||||
|
{ key: 'pos', type: 'ref', default: null, choices_from: 'devices:pos_counter' },
|
||||||
|
{ key: 'sound', type: 'bool', default: true },
|
||||||
|
]
|
||||||
|
assert.deepEqual(configInitial(fields), { auto_sign_out_minutes: 0, zone: null, pos: null, sound: true })
|
||||||
|
assert.deepEqual(configInitial(fields, { auto_sign_out_minutes: 5, sound: false }), { auto_sign_out_minutes: 5, zone: null, pos: null, sound: false })
|
||||||
|
assert.equal(configValue(fields[0], '5'), 5)
|
||||||
|
assert.equal(configValue(fields[1], ''), null)
|
||||||
|
assert.equal(configValue(fields[1], '3'), 3)
|
||||||
|
assert.equal(configValue(fields[3], false), false)
|
||||||
|
assert.deepEqual(refOptions(fields[1], { zones: [{ id: 2, name: 'Grill' }] }), [{ value: '2', label: 'Grill' }])
|
||||||
|
const devices = [{ id: 1, app_key: 'pos_counter', name: 'Till' }, { id: 2, app_key: 'kds', name: 'KDS' },
|
||||||
|
{ id: 3, app_key: 'pos_counter', name: 'Old', revoked_at: 'x' }]
|
||||||
|
assert.deepEqual(refOptions(fields[2], { devices }), [{ value: '1', label: 'Till' }])
|
||||||
|
assert.deepEqual(refOptions(fields[2], { devices, selfId: 1 }), [])
|
||||||
|
})
|
||||||
|
|||||||
@@ -3,10 +3,12 @@
|
|||||||
// hook is now a thin wrapper around this. No React.
|
// hook is now a thin wrapper around this. No React.
|
||||||
//
|
//
|
||||||
// Protocol (local_backend/routers/ws.py):
|
// Protocol (local_backend/routers/ws.py):
|
||||||
// 1. connect to ws[s]://host/api/ws/connect?token=<jwt>
|
// 1. connect to ws[s]://host/api/ws/connect?token=<jwt> (or no query, see `credentials`)
|
||||||
// 2. send { cursor: <last seq> } at once (0 = first connect / no history)
|
// 2. send { cursor: <last seq>, ...credentials() } at once (0 = first connect / no history)
|
||||||
// 3. the server replays missed events, then sends { type: "ready" }
|
// 3. the server replays missed events, then sends { type: "ready" }
|
||||||
// 4. live events: { seq, type, data }
|
// — or { type: "refused", data: { code } } and closes (4001 sign in again, 4003 device)
|
||||||
|
// 4. live events: { seq, type, data }; control events without seq: `device.updated`, and
|
||||||
|
// before the server closes: `session.ended`, `device.revoked` (plan step 3.1a)
|
||||||
// 5. keepalive: { type: "ping" } every 25 s (no answer needed)
|
// 5. keepalive: { type: "ping" } every 25 s (no answer needed)
|
||||||
// On close: reconnect after 2 s, then ×1.5 each time up to 30 s; a successful open resets
|
// On close: reconnect after 2 s, then ×1.5 each time up to 30 s; a successful open resets
|
||||||
// it. The browser's `online` event reconnects at once. The cursor survives reloads through
|
// it. The browser's `online` event reconnects at once. The cursor survives reloads through
|
||||||
@@ -16,6 +18,9 @@
|
|||||||
// url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`),
|
// url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`),
|
||||||
// cursor: { load: async () => seq, save: seq => … },
|
// cursor: { load: async () => seq, save: seq => … },
|
||||||
// onEvent: (type, data) => …, onReady: () => …, onDisconnect: () => …,
|
// onEvent: (type, data) => …, onReady: () => …, onDisconnect: () => …,
|
||||||
|
// // terminal (paired device): credentials go in the first frame, never in the URL
|
||||||
|
// credentials: () => ({ device: deviceToken, token: sessionToken }),
|
||||||
|
// onRefused: code => …, // e.g. 'device.revoked', 'auth.session_ended'; it keeps retrying
|
||||||
// })
|
// })
|
||||||
// live.start(); …; live.reconnect(); …; live.stop()
|
// live.start(); …; live.reconnect(); …; live.stop()
|
||||||
|
|
||||||
@@ -31,7 +36,7 @@ export function wsUrlFor(path, baseURL = '') {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function createLiveClient({
|
export function createLiveClient({
|
||||||
url, cursor, onEvent, onReady, onDisconnect,
|
url, cursor, onEvent, onReady, onDisconnect, credentials, onRefused,
|
||||||
WebSocketImpl = globalThis.WebSocket,
|
WebSocketImpl = globalThis.WebSocket,
|
||||||
windowTarget = typeof window !== 'undefined' ? window : null,
|
windowTarget = typeof window !== 'undefined' ? window : null,
|
||||||
timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id) },
|
timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id) },
|
||||||
@@ -54,7 +59,8 @@ export function createLiveClient({
|
|||||||
|
|
||||||
socket.onopen = () => {
|
socket.onopen = () => {
|
||||||
reconnectDelay = INITIAL_RECONNECT_DELAY
|
reconnectDelay = INITIAL_RECONNECT_DELAY
|
||||||
socket.send(JSON.stringify({ cursor: lastSeq })) // the server replays what we missed
|
const extra = Object.fromEntries(Object.entries(credentials?.() || {}).filter(([, v]) => v != null && v !== ''))
|
||||||
|
socket.send(JSON.stringify({ cursor: lastSeq, ...extra })) // the server replays what we missed
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.onmessage = e => {
|
socket.onmessage = e => {
|
||||||
@@ -62,6 +68,7 @@ export function createLiveClient({
|
|||||||
try { msg = JSON.parse(e.data) } catch { return }
|
try { msg = JSON.parse(e.data) } catch { return }
|
||||||
if (msg.type === 'ping') return
|
if (msg.type === 'ping') return
|
||||||
if (msg.type === 'ready') { onReady?.(); return }
|
if (msg.type === 'ready') { onReady?.(); return }
|
||||||
|
if (msg.type === 'refused') { onRefused?.(msg.data?.code); return }
|
||||||
if (msg.seq && msg.seq > lastSeq) {
|
if (msg.seq && msg.seq > lastSeq) {
|
||||||
lastSeq = msg.seq
|
lastSeq = msg.seq
|
||||||
cursor?.save?.(msg.seq)
|
cursor?.save?.(msg.seq)
|
||||||
|
|||||||
@@ -157,3 +157,26 @@ test('wsUrlFor', () => {
|
|||||||
assert.equal(wsUrlFor('/api/ws/connect?token=a', 'https://10.0.2.2:18443'), 'wss://10.0.2.2:18443/api/ws/connect?token=a')
|
assert.equal(wsUrlFor('/api/ws/connect?token=a', 'https://10.0.2.2:18443'), 'wss://10.0.2.2:18443/api/ws/connect?token=a')
|
||||||
assert.equal(wsUrlFor('/api/ws/connect', 'http://192.168.1.5'), 'ws://192.168.1.5/api/ws/connect')
|
assert.equal(wsUrlFor('/api/ws/connect', 'http://192.168.1.5'), 'ws://192.168.1.5/api/ws/connect')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('credentials go in the first frame (empty ones left out); refusals reach onRefused', async () => {
|
||||||
|
FakeWS.all = []
|
||||||
|
const refused = []
|
||||||
|
const events = []
|
||||||
|
const live = createLiveClient({
|
||||||
|
url: 'ws://venue/api/ws/connect',
|
||||||
|
credentials: () => ({ device: 'dev-token', token: null }),
|
||||||
|
onEvent: (type, data) => events.push([type, data]),
|
||||||
|
onRefused: code => refused.push(code),
|
||||||
|
WebSocketImpl: FakeWS, windowTarget: new FakeWindow(), timers: fakeTimers(),
|
||||||
|
})
|
||||||
|
await live.start()
|
||||||
|
const ws = FakeWS.all.at(-1)
|
||||||
|
assert.equal(ws.url, 'ws://venue/api/ws/connect')
|
||||||
|
ws.open()
|
||||||
|
assert.deepEqual(ws.sent, [{ cursor: 0, device: 'dev-token' }])
|
||||||
|
ws.msg({ type: 'refused', data: { code: 'device.revoked' } })
|
||||||
|
ws.msg({ type: 'device.updated', data: { device_id: 3 } })
|
||||||
|
assert.deepEqual(refused, ['device.revoked'])
|
||||||
|
assert.deepEqual(events, [['device.updated', { device_id: 3 }]])
|
||||||
|
live.stop()
|
||||||
|
})
|
||||||
|
|||||||
@@ -54,7 +54,8 @@
|
|||||||
"invalid": "Κάποια πεδία δεν είναι σωστά.",
|
"invalid": "Κάποια πεδία δεν είναι σωστά.",
|
||||||
"unknown_language": "Μη υποστηριζόμενη γλώσσα: {{language}}.",
|
"unknown_language": "Μη υποστηριζόμενη γλώσσα: {{language}}.",
|
||||||
"unknown_timezone": "Άγνωστη ζώνη ώρας: {{timezone}}.",
|
"unknown_timezone": "Άγνωστη ζώνη ώρας: {{timezone}}.",
|
||||||
"setting_value": "Η ρύθμιση {{key}} δεν μπορεί να πάρει την τιμή «{{value}}»."
|
"setting_value": "Η ρύθμιση {{key}} δεν μπορεί να πάρει την τιμή «{{value}}».",
|
||||||
|
"device_config": "Αυτή η ρύθμιση συσκευής δεν είναι έγκυρη: {{key}}."
|
||||||
},
|
},
|
||||||
"internal": {
|
"internal": {
|
||||||
"error": "Κάτι πήγε στραβά στον διακομιστή (αίτημα {{request_id}})."
|
"error": "Κάτι πήγε στραβά στον διακομιστή (αίτημα {{request_id}})."
|
||||||
|
|||||||
@@ -172,6 +172,7 @@
|
|||||||
"signIn": "Πώς συνδέεται το προσωπικό",
|
"signIn": "Πώς συνδέεται το προσωπικό",
|
||||||
"link": "Συνδεδεμένη συσκευή",
|
"link": "Συνδεδεμένη συσκευή",
|
||||||
"noLink": "Καμία",
|
"noLink": "Καμία",
|
||||||
|
"none": "Κανένα",
|
||||||
"linkHint": "Για παράδειγμα μια οθόνη πελάτη που δείχνει την παραγγελία ενός ταμείου πάγκου.",
|
"linkHint": "Για παράδειγμα μια οθόνη πελάτη που δείχνει την παραγγελία ενός ταμείου πάγκου.",
|
||||||
"full": "{{label}}: η άδεια επιτρέπει {{max}} και χρησιμοποιούνται όλα. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια.",
|
"full": "{{label}}: η άδεια επιτρέπει {{max}} και χρησιμοποιούνται όλα. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια.",
|
||||||
"noApps": "Καμία εφαρμογή συσκευών δεν είναι ενεργή. Ενεργοποιήστε μία πρώτα από τις Εφαρμογές."
|
"noApps": "Καμία εφαρμογή συσκευών δεν είναι ενεργή. Ενεργοποιήστε μία πρώτα από τις Εφαρμογές."
|
||||||
|
|||||||
@@ -125,6 +125,20 @@
|
|||||||
"permissions": {
|
"permissions": {
|
||||||
"access": "Χρήση της οθόνης κουζίνας",
|
"access": "Χρήση της οθόνης κουζίνας",
|
||||||
"bump": "Σήμανση πιάτων ως έτοιμων"
|
"bump": "Σήμανση πιάτων ως έτοιμων"
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"auto_sign_out_minutes": {
|
||||||
|
"label": "Αποσύνδεση μετά από",
|
||||||
|
"hint": "Επιστροφή στην οθόνη σύνδεσης όταν κανείς δεν έχει χρησιμοποιήσει την οθόνη για τόσο χρόνο.",
|
||||||
|
"choices": {
|
||||||
|
"0": "Ποτέ",
|
||||||
|
"2": "2 λεπτά",
|
||||||
|
"5": "5 λεπτά",
|
||||||
|
"10": "10 λεπτά",
|
||||||
|
"30": "30 λεπτά",
|
||||||
|
"60": "1 ώρα"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"menu_tablet": {
|
"menu_tablet": {
|
||||||
@@ -169,6 +183,20 @@
|
|||||||
},
|
},
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"access": "Χρήση του ταμείου πάγκου"
|
"access": "Χρήση του ταμείου πάγκου"
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"auto_sign_out_minutes": {
|
||||||
|
"label": "Αποσύνδεση μετά από",
|
||||||
|
"hint": "Επιστροφή στην οθόνη σύνδεσης όταν κανείς δεν έχει χρησιμοποιήσει την οθόνη για τόσο χρόνο.",
|
||||||
|
"choices": {
|
||||||
|
"0": "Ποτέ",
|
||||||
|
"2": "2 λεπτά",
|
||||||
|
"5": "5 λεπτά",
|
||||||
|
"10": "10 λεπτά",
|
||||||
|
"30": "30 λεπτά",
|
||||||
|
"60": "1 ώρα"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pricing": {
|
"pricing": {
|
||||||
|
|||||||
@@ -54,7 +54,8 @@
|
|||||||
"invalid": "Some fields are invalid.",
|
"invalid": "Some fields are invalid.",
|
||||||
"unknown_language": "Unsupported language: {{language}}.",
|
"unknown_language": "Unsupported language: {{language}}.",
|
||||||
"unknown_timezone": "Unknown time zone: {{timezone}}.",
|
"unknown_timezone": "Unknown time zone: {{timezone}}.",
|
||||||
"setting_value": "{{key}} can't be set to \"{{value}}\"."
|
"setting_value": "{{key}} can't be set to \"{{value}}\".",
|
||||||
|
"device_config": "This device setting is not valid: {{key}}."
|
||||||
},
|
},
|
||||||
"internal": {
|
"internal": {
|
||||||
"error": "Something went wrong on the server (request {{request_id}})."
|
"error": "Something went wrong on the server (request {{request_id}})."
|
||||||
|
|||||||
@@ -172,6 +172,7 @@
|
|||||||
"signIn": "How staff sign in",
|
"signIn": "How staff sign in",
|
||||||
"link": "Linked device",
|
"link": "Linked device",
|
||||||
"noLink": "None",
|
"noLink": "None",
|
||||||
|
"none": "None",
|
||||||
"linkHint": "For example a customer display that shows a counter POS's order.",
|
"linkHint": "For example a customer display that shows a counter POS's order.",
|
||||||
"full": "{{label}}: the license allows {{max}}, all in use. Remove one or ask for a bigger license.",
|
"full": "{{label}}: the license allows {{max}}, all in use. Remove one or ask for a bigger license.",
|
||||||
"noApps": "No device app is turned on. Turn one on in Apps first."
|
"noApps": "No device app is turned on. Turn one on in Apps first."
|
||||||
|
|||||||
@@ -125,6 +125,20 @@
|
|||||||
"permissions": {
|
"permissions": {
|
||||||
"access": "Use the kitchen display",
|
"access": "Use the kitchen display",
|
||||||
"bump": "Mark items ready"
|
"bump": "Mark items ready"
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"auto_sign_out_minutes": {
|
||||||
|
"label": "Sign out after",
|
||||||
|
"hint": "Back to the sign-in screen when nobody has used the screen for this long.",
|
||||||
|
"choices": {
|
||||||
|
"0": "Never",
|
||||||
|
"2": "2 minutes",
|
||||||
|
"5": "5 minutes",
|
||||||
|
"10": "10 minutes",
|
||||||
|
"30": "30 minutes",
|
||||||
|
"60": "1 hour"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"menu_tablet": {
|
"menu_tablet": {
|
||||||
@@ -169,6 +183,20 @@
|
|||||||
},
|
},
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"access": "Use the counter POS"
|
"access": "Use the counter POS"
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"auto_sign_out_minutes": {
|
||||||
|
"label": "Sign out after",
|
||||||
|
"hint": "Back to the sign-in screen when nobody has used the screen for this long.",
|
||||||
|
"choices": {
|
||||||
|
"0": "Never",
|
||||||
|
"2": "2 minutes",
|
||||||
|
"5": "5 minutes",
|
||||||
|
"10": "10 minutes",
|
||||||
|
"30": "30 minutes",
|
||||||
|
"60": "1 hour"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pricing": {
|
"pricing": {
|
||||||
|
|||||||
+1
-1
@@ -42,7 +42,7 @@ Or run one suite at a time:
|
|||||||
| `node install.mjs` | `install.sh`: VPN-safe `HOST_IP` detection (simulated WireGuard/WiFi hosts); fresh install, upgrade, re-run; proxy config identical to `nginx-proxy/nginx.conf` | Docker | ~1 min |
|
| `node install.mjs` | `install.sh`: VPN-safe `HOST_IP` detection (simulated WireGuard/WiFi hosts); fresh install, upgrade, re-run; proxy config identical to `nginx-proxy/nginx.conf` | Docker | ~1 min |
|
||||||
| `python license_e2e.py` | Offline licensing with a real cloud + site process: 400 days offline, tampered file, clock set back, expiry deferred to workday close, renewal, remote lock | Python deps of both backends | ~2 min |
|
| `python license_e2e.py` | Offline licensing with a real cloud + site process: 400 days offline, tampered file, clock set back, expiry deferred to workday close, renewal, remote lock | Python deps of both backends | ~2 min |
|
||||||
| `node ui.mjs` | `@xenia/ui` components on the dev-only gallery (`/ui-gallery`, manager Vite :5185): dialog focus/Escape/backdrop, sheet, toasts, field wiring, switch, InfoTip, PinPad, themes; `@xenia/i18n` on `/i18n-sample` with the browser in New York: venue time, live language switch, el/en money and numbers, price input, translated component labels | Edge | ~40 s |
|
| `node ui.mjs` | `@xenia/ui` components on the dev-only gallery (`/ui-gallery`, manager Vite :5185): dialog focus/Escape/backdrop, sheet, toasts, field wiring, switch, InfoTip, PinPad, themes; `@xenia/i18n` on `/i18n-sample` with the browser in New York: venue time, live language switch, el/en money and numbers, price input, translated component labels | Edge | ~40 s |
|
||||||
| `node manager.mjs` | Manager on `@xenia/api`/`@xenia/access` (backend :8057 on a demo DB, manager Vite :5186): bootstrap before/after login, wrong password and wrong lock PIN stay on screen, sidebar from keys, KDS module off → "turned off" screen, session ended elsewhere → /login, a waiter's cancel approved by a manager PIN (wrong PIN first) and audited; Apps, Integrations, License, Devices (pairing played through the API); the approvals log, "Signed in now" + end session, the staff permission editor (give, reset to role, a staff manager can't give what they lack); the notification bell (live, read, read all), sign-in/venue/print settings, log download; the **owner flow** (sign in → turn on KDS → pair a screen → give a chef the kitchen permissions → the chef signs in on that screen) | Edge | ~1 min |
|
| `node manager.mjs` | Manager on `@xenia/api`/`@xenia/access` (backend :8057 on a demo DB, manager Vite :5186): bootstrap before/after login, wrong password and wrong lock PIN stay on screen, sidebar from keys, KDS module off → "turned off" screen, session ended elsewhere → /login, a waiter's cancel approved by a manager PIN (wrong PIN first) and audited; Apps, Integrations, License, Devices (pairing played through the API, a device setting chosen when pairing and edited, the screen's live connection told of the edit and closed on app change and removal); the approvals log, "Signed in now" + end session, the staff permission editor (give, reset to role, a staff manager can't give what they lack); the notification bell (live, read, read all), sign-in/venue/print settings, log download; the **owner flow** (sign in → turn on KDS → pair a screen → give a chef the kitchen permissions → the chef signs in on that screen) | Edge | ~1 min |
|
||||||
| `node browser.mjs` | Waiter web modes (same-origin, plain HTTP by LAN IP, venue mode), install dialog + drawer entry (Android / iPhone / desktop / no APK) | Docker, Edge | ~2 min |
|
| `node browser.mjs` | Waiter web modes (same-origin, plain HTTP by LAN IP, venue mode), install dialog + drawer entry (Android / iPhone / desktop / no APK) | Docker, Edge | ~2 min |
|
||||||
| `node android.mjs basics` | Pairing, wrong address / other venue's QR, login + live WS, back button, restart, two venues, camera permission | Android emulator | ~5 min |
|
| `node android.mjs basics` | Pairing, wrong address / other venue's QR, login + live WS, back button, restart, two venues, camera permission | Android emulator | ~5 min |
|
||||||
| `node android.mjs rediscovery` | Server IP change (logged in / out), server down + manual search, cold start while offline | Android emulator | ~4 min |
|
| `node android.mjs rediscovery` | Server IP change (logged in / out), server down + manual search, cold start while offline | Android emulator | ~4 min |
|
||||||
|
|||||||
+28
-1
@@ -43,6 +43,19 @@ async function devicePicksUpToken(req) {
|
|||||||
const res = await fetch(`${backend.url}/api/devices/pair-request/${req.code}`, { headers: { 'X-Xenia-Pair-Secret': req.secret } })
|
const res = await fetch(`${backend.url}/api/devices/pair-request/${req.code}`, { headers: { 'X-Xenia-Pair-Secret': req.secret } })
|
||||||
return (await res.json()).device_token
|
return (await res.json()).device_token
|
||||||
}
|
}
|
||||||
|
// A paired screen's live connection (plan 3.1a): the device token goes in the first frame.
|
||||||
|
function deviceSocket(token) {
|
||||||
|
const ws = new WebSocket(`${backend.url.replace(/^http/, 'ws')}/api/ws/connect`)
|
||||||
|
const s = { messages: [], closeCode: null }
|
||||||
|
s.ready = new Promise(resolve => {
|
||||||
|
ws.onopen = () => ws.send(JSON.stringify({ cursor: 0, device: token }))
|
||||||
|
ws.onmessage = e => { const m = JSON.parse(e.data); s.messages.push(m); if (m.type === 'ready') resolve(true) }
|
||||||
|
ws.onclose = e => { s.closeCode = e.code; resolve(false) }
|
||||||
|
})
|
||||||
|
s.closed = () => new Promise(resolve => { const t = setInterval(() => { if (s.closeCode != null) { clearInterval(t); resolve(s.closeCode) } }, 50); setTimeout(() => { clearInterval(t); resolve(s.closeCode) }, 8000) })
|
||||||
|
s.close = () => ws.close()
|
||||||
|
return s
|
||||||
|
}
|
||||||
const asDevice = (token, url) => fetch(`${backend.url}${url}`, { headers: { 'X-Xenia-Device': token } })
|
const asDevice = (token, url) => fetch(`${backend.url}${url}`, { headers: { 'X-Xenia-Device': token } })
|
||||||
const loginApi = (username, secret) => api('POST', '/api/auth/login', { body: { client: 'manager', username, ...secret } }).then(d => d.access_token)
|
const loginApi = (username, secret) => api('POST', '/api/auth/login', { body: { client: 'manager', username, ...secret } }).then(d => d.access_token)
|
||||||
|
|
||||||
@@ -171,6 +184,7 @@ try {
|
|||||||
await dlg.getByLabel('Code shown on the device').fill(typed)
|
await dlg.getByLabel('Code shown on the device').fill(typed)
|
||||||
r.check('devices: the code is normalized as typed (lower case, dash)', await dlg.getByLabel('Code shown on the device').inputValue() === req.code)
|
r.check('devices: the code is normalized as typed (lower case, dash)', await dlg.getByLabel('Code shown on the device').inputValue() === req.code)
|
||||||
await dlg.getByLabel('How staff sign in').selectOption('pin')
|
await dlg.getByLabel('How staff sign in').selectOption('pin')
|
||||||
|
await dlg.getByLabel('Sign out after').selectOption('10')
|
||||||
await dlg.getByRole('button', { name: 'Pair a device' }).click()
|
await dlg.getByRole('button', { name: 'Pair a device' }).click()
|
||||||
await page.waitForFunction(() => document.querySelectorAll('[data-testid^="device-"][data-status]').length === 1, null, { timeout: 8000 }).catch(() => {})
|
await page.waitForFunction(() => document.querySelectorAll('[data-testid^="device-"][data-status]').length === 1, null, { timeout: 8000 }).catch(() => {})
|
||||||
const row = page.locator('[data-testid^="device-"][data-status]').first()
|
const row = page.locator('[data-testid^="device-"][data-status]').first()
|
||||||
@@ -178,23 +192,34 @@ try {
|
|||||||
const deviceToken = await devicePicksUpToken(req)
|
const deviceToken = await devicePicksUpToken(req)
|
||||||
const me = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
|
const me = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
|
||||||
r.check('devices: the device got its token and runs the kitchen display', me.app_key === 'kds' && me.name === 'Kitchen' && me.login_mode === 'pin', JSON.stringify(me))
|
r.check('devices: the device got its token and runs the kitchen display', me.app_key === 'kds' && me.name === 'Kitchen' && me.login_mode === 'pin', JSON.stringify(me))
|
||||||
|
r.check('devices: the app setting chosen when pairing reaches the device (3.1a)', me.config?.auto_sign_out_minutes === 10, JSON.stringify(me.config))
|
||||||
await page.reload()
|
await page.reload()
|
||||||
await row.waitFor({ timeout: 10_000 })
|
await row.waitFor({ timeout: 10_000 })
|
||||||
r.check('devices: after it connected → "Online", sign-in PIN', await row.getAttribute('data-status') === 'online' && (await row.textContent()).includes('PIN'))
|
r.check('devices: after it connected → "Online", sign-in PIN', await row.getAttribute('data-status') === 'online' && (await row.textContent()).includes('PIN'))
|
||||||
r.check('devices: usage shows kitchen screens in use', (await page.getByTestId('device-usage').textContent()).includes('Kitchen screens: 1'))
|
r.check('devices: usage shows kitchen screens in use', (await page.getByTestId('device-usage').textContent()).includes('Kitchen screens: 1'))
|
||||||
|
|
||||||
|
const sock = deviceSocket(deviceToken)
|
||||||
|
r.check('devices: the screen opens a live connection with its device token alone (3.1a)', await sock.ready)
|
||||||
await row.getByRole('button', { name: 'Edit' }).click()
|
await row.getByRole('button', { name: 'Edit' }).click()
|
||||||
|
r.check('devices: the edit dialog shows the device setting', await dlg.getByLabel('Sign out after').inputValue() === '10')
|
||||||
await dlg.getByLabel('Name').fill('Kitchen 1')
|
await dlg.getByLabel('Name').fill('Kitchen 1')
|
||||||
|
await dlg.getByLabel('Sign out after').selectOption('5')
|
||||||
await dlg.getByRole('button', { name: 'Save' }).click()
|
await dlg.getByRole('button', { name: 'Save' }).click()
|
||||||
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Kitchen 1'), null, { timeout: 8000 }).catch(() => {})
|
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Kitchen 1'), null, { timeout: 8000 }).catch(() => {})
|
||||||
r.check('devices: renamed', (await row.textContent()).includes('Kitchen 1') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).name === 'Kitchen 1')
|
const me2 = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
|
||||||
|
r.check('devices: renamed, setting changed', (await row.textContent()).includes('Kitchen 1') && me2.name === 'Kitchen 1' && me2.config?.auto_sign_out_minutes === 5, JSON.stringify(me2))
|
||||||
|
await sleep(300)
|
||||||
|
r.check('devices: the screen is told at once (device.updated)', sock.messages.some(m => m.type === 'device.updated'), JSON.stringify(sock.messages))
|
||||||
|
|
||||||
await row.getByRole('button', { name: 'Change app' }).click()
|
await row.getByRole('button', { name: 'Change app' }).click()
|
||||||
await dlg.getByLabel('App to run').selectOption('pos_counter')
|
await dlg.getByLabel('App to run').selectOption('pos_counter')
|
||||||
await dlg.getByRole('button', { name: 'Save' }).click()
|
await dlg.getByRole('button', { name: 'Save' }).click()
|
||||||
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Counter POS'), null, { timeout: 8000 }).catch(() => {})
|
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Counter POS'), null, { timeout: 8000 }).catch(() => {})
|
||||||
r.check('devices: app changed to Counter POS (the device follows)', (await row.textContent()).includes('Counter POS') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).app_key === 'pos_counter')
|
r.check('devices: app changed to Counter POS (the device follows)', (await row.textContent()).includes('Counter POS') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).app_key === 'pos_counter')
|
||||||
|
r.check('devices: changing the app closes the screen connection (4003)', await sock.closed() === 4003)
|
||||||
await page.screenshot({ path: path.join(OUT, 'manager-devices.png'), fullPage: true })
|
await page.screenshot({ path: path.join(OUT, 'manager-devices.png'), fullPage: true })
|
||||||
|
const sock2 = deviceSocket(deviceToken)
|
||||||
|
await sock2.ready
|
||||||
|
|
||||||
await row.getByRole('button', { name: 'Remove' }).click()
|
await row.getByRole('button', { name: 'Remove' }).click()
|
||||||
await dlg.getByRole('button', { name: 'Remove' }).click()
|
await dlg.getByRole('button', { name: 'Remove' }).click()
|
||||||
@@ -202,6 +227,8 @@ try {
|
|||||||
const after = await asDevice(deviceToken, '/api/devices/me')
|
const after = await asDevice(deviceToken, '/api/devices/me')
|
||||||
r.check('devices: removed → gone from the list, the device is refused (device.revoked)',
|
r.check('devices: removed → gone from the list, the device is refused (device.revoked)',
|
||||||
await page.getByText('No devices yet').count() === 1 && after.status === 401 && (await after.json()).error.code === 'device.revoked')
|
await page.getByText('No devices yet').count() === 1 && after.status === 401 && (await after.json()).error.code === 'device.revoked')
|
||||||
|
r.check('devices: removing it sends device.revoked and closes its connection',
|
||||||
|
await sock2.closed() === 4003 && sock2.messages.some(m => m.type === 'device.revoked'), JSON.stringify(sock2.messages))
|
||||||
await page.getByLabel('Show removed devices').check()
|
await page.getByLabel('Show removed devices').check()
|
||||||
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status="removed"]'), null, { timeout: 8000 }).catch(() => {})
|
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status="removed"]'), null, { timeout: 8000 }).catch(() => {})
|
||||||
r.check('devices: "show removed" lists it as removed', await page.locator('[data-status="removed"]').count() === 1)
|
r.check('devices: "show removed" lists it as removed', await page.locator('[data-status="removed"]').count() === 1)
|
||||||
|
|||||||
Reference in New Issue
Block a user