feat(api): @xenia/api + @xenia/access; the manager logs in and loads bootstrap through them

Platform-v2 step 2.5 (APPS_PLATFORM D-7, D-10, §9):
- @xenia/api: createApiClient (app passes its axios; session/device headers,
  err.xenia codes, 401/offline hooks, manager-override retry: ask PIN, grant,
  retry once with X-Xenia-Override); errorMessage; createLiveClient = the
  waiter's WebSocket logic (cursor replay, backoff, online) moved unchanged
- @xenia/access: AccessProvider (bootstrap per session token, language +
  venue formats, translated ui labels, approval dialog), useAccess/useCan/
  useModule, Can, RequireModule
- i18n: errors namespace for every backend code (en/el, test vs core/errors.py),
  override/access texts
- manager: client from createApiClient, AccessProvider in a layout route,
  /kds behind RequireModule, usePermissions from bootstrap keys; login and
  unlock no longer treat a wrong password/PIN as "session ended" (a wrong
  lock-screen PIN used to log the manager out)
- waiter: useWebSocket is a thin wrapper over createLiveClient
- tests: api/access unit tests; new e2e suite tests/e2e/manager.mjs; CS-18

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 20:38:31 +02:00
co-authored by Claude Opus 5.5
parent dbb8d5f0f4
commit 78c8824356
35 changed files with 1419 additions and 196 deletions
+7 -2
View File
@@ -43,13 +43,15 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below | | `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below |
| `waiter_pwa/src/native/pairing.js`, `src/pages/VenuesPage.jsx` | Pairing with a venue (QR / typed address) and the venue switcher | | `waiter_pwa/src/native/pairing.js`, `src/pages/VenuesPage.jsx` | Pairing with a venue (QR / typed address) and the venue switcher |
| `waiter_pwa/src/api/client.js` | axios instance: auth header, 401 → logout, network error → offline | | `waiter_pwa/src/api/client.js` | axios instance: auth header, 401 → logout, network error → offline |
| `waiter_pwa/src/context/SSEContext.jsx` | Real-time lifecycle, event → store/cache updates, visibility refresh | | `waiter_pwa/src/context/SSEContext.jsx`, `src/hooks/useWebSocket.js` | Real-time lifecycle, event → store/cache updates, visibility refresh; the socket itself is `createLiveClient` from `@xenia/api` |
| `waiter_pwa/src/db/posdb`, `src/services/offlineOrders` | Offline cache and queued orders | | `waiter_pwa/src/db/posdb`, `src/services/offlineOrders` | Offline cache and queued orders |
| `nginx-proxy/nginx.conf` | Proxy config used in dev / by hand | | `nginx-proxy/nginx.conf` | Proxy config used in dev / by hand |
| `install.sh` | Site installer. **Writes its own copy of the proxy config.** | | `install.sh` | Site installer. **Writes its own copy of the proxy config.** |
| `docker-compose.yml` / `docker-compose.dev.yml` | Prod (pull images) / dev override (build + expose ports) | | `docker-compose.yml` / `docker-compose.dev.yml` | Prod (pull images) / dev override (build + expose ports) |
| `package.json`, `package-lock.json`, `packages/` | **npm workspace** for the frontends (D-15): `waiter_pwa`, `manager_dashboard` and the shared `packages/{ui,i18n,api,access}` (imported from source, no build step). One lockfile at this root; the apps have none of their own. | | `package.json`, `package-lock.json`, `packages/` | **npm workspace** for the frontends (D-15): `waiter_pwa`, `manager_dashboard` and the shared `packages/{ui,i18n,api,access}` (imported from source, no build step). One lockfile at this root; the apps have none of their own. |
| `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` | | `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` |
| `packages/api/` | Shared HTTP client (`createApiClient`: session/device headers, `err.xenia` codes, the manager-approval retry) and the live WebSocket client with cursor replay (`createLiveClient`, used by the waiter's `useWebSocket`) (CS-18) |
| `packages/access/` | `<AccessProvider>` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, `<Can>`, `<RequireModule>` (CS-18) |
| `packages/i18n/` | Translations (`locales/<lang>/<ns>.json`), language resolution, venue-time / money / number formatting, the comma-or-dot number parser, and the guard `scripts/check-i18n.mjs` (CS-17). Sample: `/i18n-sample` (dev) | | `packages/i18n/` | Translations (`locales/<lang>/<ns>.json`), language resolution, venue-time / money / number formatting, the comma-or-dot number parser, and the guard `scripts/check-i18n.mjs` (CS-17). Sample: `/i18n-sample` (dev) |
| `.dockerignore` | The frontend images build with **`client-services/` as context** (`-f waiter_pwa/Dockerfile .`), so this file decides what Docker sees. The backend still builds from `local_backend/`. | | `.dockerignore` | The frontend images build with **`client-services/` as context** (`-f waiter_pwa/Dockerfile .`), so this file decides what Docker sees. The backend still builds from `local_backend/`. |
@@ -146,7 +148,7 @@ The native plugins (`@capacitor/*`, `@capgo/*`) are pinned to **exact** versions
## Testing ## Testing
Automated tests cover the native-app/LAN work and licensing. See **[tests/e2e/README.md](../tests/e2e/README.md)**. Automated tests cover the native-app/LAN work and licensing. See **[tests/e2e/README.md](../tests/e2e/README.md)**.
- **Unit (seconds):** `python -m pytest tests -q` in `local_backend/`, `npm test` in `waiter_pwa/`, and `npm test -w @xenia/ui` / `npm test -w @xenia/i18n` at the workspace root. - **Unit (seconds):** `python -m pytest tests -q` in `local_backend/`, `npm test` in `waiter_pwa/`, and `npm test -w @xenia/<ui|i18n|api|access>` at the workspace root.
- **End-to-end:** `node run-all.mjs` in `tests/e2e/`. That covers install.sh, licensing with a real cloud, browser modes, and the Android emulator suites. `--no-android` skips the emulator. - **End-to-end:** `node run-all.mjs` in `tests/e2e/`. That covers install.sh, licensing with a real cloud, browser modes, and the Android emulator suites. `--no-android` skips the emulator.
**CS-11. Tests follow the code.** When you change something a test covers (licensing, LAN IP, TLS, pairing, rediscovery, bundles, install.sh, the proxy config), run its suite and update the test in the same commit. Run `node run-all.mjs` before every release. **CS-11. Tests follow the code.** When you change something a test covers (licensing, LAN IP, TLS, pairing, rediscovery, bundles, install.sh, the proxy config), run its suite and update the test in the same commit. Run `node run-all.mjs` before every release.
@@ -168,6 +170,9 @@ Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`),
**CS-17. Frontend text is a key; dates are venue time** (branch `platform-v2`, D-11, D-12, §7.2, §8). **CS-17. Frontend text is a key; dates are venue time** (branch `platform-v2`, D-11, D-12, §7.2, §8).
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. 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. 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).
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 } }`. 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).
**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`).
+2
View File
@@ -10,6 +10,8 @@
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.62.0", "@tanstack/react-query": "^5.62.0",
"@xenia/access": "^0.0.0",
"@xenia/api": "^0.0.0",
"@xenia/i18n": "^0.0.0", "@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.7.9", "axios": "^1.7.9",
+24 -5
View File
@@ -1,5 +1,7 @@
import { lazy, Suspense, useEffect, useState } from 'react' import { lazy, Suspense, useEffect, useState } from 'react'
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom' import { BrowserRouter, Routes, Route, Navigate, Outlet, useNavigate } from 'react-router-dom'
import { AccessProvider, RequireModule } from '@xenia/access'
import { createI18n } from '@xenia/i18n'
import useAuthStore from './store/authStore' import useAuthStore from './store/authStore'
import AppLayout from './layouts/AppLayout' import AppLayout from './layouts/AppLayout'
import client from './api/client' import client from './api/client'
@@ -54,6 +56,10 @@ import SettingsPage from './pages/Settings/SettingsPage'
import NotesPage from './pages/NotesPage' import NotesPage from './pages/NotesPage'
import PermissionGuard from './components/PermissionGuard' import PermissionGuard from './components/PermissionGuard'
// Texts for the shared parts (approval dialog, "feature off" screens, component labels).
// The language follows bootstrap (user -> venue); the current pages are still Greek (phase 6).
const i18n = createI18n()
// Visual check pages for the shared packages, dev builds only (left out of production bundles) // Visual check pages for the shared packages, dev builds only (left out of production bundles)
const UiGallery = import.meta.env.DEV ? lazy(() => import('@xenia/ui/gallery')) : null const UiGallery = import.meta.env.DEV ? lazy(() => import('@xenia/ui/gallery')) : null
const I18nSample = import.meta.env.DEV ? lazy(() => import('@xenia/i18n/sample')) : null const I18nSample = import.meta.env.DEV ? lazy(() => import('@xenia/i18n/sample')) : null
@@ -107,16 +113,29 @@ function SetupGuard({ children }) {
return children return children
} }
// Platform bootstrap (modules, permission keys, venue, language) for every real page; it
// reloads when the session token changes (login, logout, unlock). @xenia/access, plan step 2.5.
function ManagerRoot() {
const token = useAuthStore(s => s.token)
return (
<AccessProvider client={client} token={token} i18n={i18n} loading={<Spinner />}>
<AuthRehydrator>
<Outlet />
</AuthRehydrator>
</AccessProvider>
)
}
export default function App() { export default function App() {
return ( return (
<BrowserRouter> <BrowserRouter>
<AuthRehydrator>
<Routes> <Routes>
<Route path="/setup" element={<SetupWizard />} />
{UiGallery && <Route path="/ui-gallery" element={<Suspense fallback={null}><UiGallery /></Suspense>} />} {UiGallery && <Route path="/ui-gallery" element={<Suspense fallback={null}><UiGallery /></Suspense>} />}
{I18nSample && <Route path="/i18n-sample" element={<Suspense fallback={null}><I18nSample /></Suspense>} />} {I18nSample && <Route path="/i18n-sample" element={<Suspense fallback={null}><I18nSample /></Suspense>} />}
<Route element={<ManagerRoot />}>
<Route path="/setup" element={<SetupWizard />} />
<Route path="/login" element={<SetupGuard><LoginPage /></SetupGuard>} /> <Route path="/login" element={<SetupGuard><LoginPage /></SetupGuard>} />
<Route path="/kds" element={<RequireAuth><KdsPage /></RequireAuth>} /> <Route path="/kds" element={<RequireAuth><RequireModule module="kds"><KdsPage /></RequireModule></RequireAuth>} />
<Route path="/" element={<RequireAuth><AppLayout /></RequireAuth>}> <Route path="/" element={<RequireAuth><AppLayout /></RequireAuth>}>
<Route index element={<Navigate to="/dashboard" replace />} /> <Route index element={<Navigate to="/dashboard" replace />} />
@@ -173,8 +192,8 @@ export default function App() {
<Route path="management" element={<Navigate to="/management/products" replace />} /> <Route path="management" element={<Navigate to="/management/products" replace />} />
<Route path="reports" element={<Navigate to="/reports/today" replace />} /> <Route path="reports" element={<Navigate to="/reports/today" replace />} />
</Route> </Route>
</Route>
</Routes> </Routes>
</AuthRehydrator>
</BrowserRouter> </BrowserRouter>
) )
} }
+16 -17
View File
@@ -1,26 +1,25 @@
import axios from 'axios' import axios from 'axios'
import { createApiClient } from '@xenia/api'
const client = axios.create({ baseURL: '' }) // The shared client (@xenia/api, plan step 2.5): session header, err.xenia on every error,
// and the manager-approval retry (the dialog is mounted by <AccessProvider>).
client.interceptors.request.use(config => { // Same origin: nginx (or Vite in dev) forwards /api to the backend.
const token = localStorage.getItem('manager_token') const client = createApiClient({
if (token) config.headers.Authorization = `Bearer ${token}` axios,
return config baseURL: '',
}) getToken: () => localStorage.getItem('manager_token'),
// A 401 on a normal request = the session ended (expired, logged out elsewhere, ended by
client.interceptors.response.use( // a manager): full logout. Login and unlock forms opt out with { xenia: { ignoreUnauthorized: true } }.
res => res, onUnauthorized: () => {
err => {
if (err.response?.status === 401) {
// On hard 401 (expired/invalid token) force a full logout
localStorage.removeItem('manager_token') localStorage.removeItem('manager_token')
localStorage.removeItem('manager_username') localStorage.removeItem('manager_username')
localStorage.removeItem('manager_lock_timeout') localStorage.removeItem('manager_lock_timeout')
window.location.href = '/login' window.location.href = '/login'
} },
return Promise.reject(err) })
}
) // Dev builds only: lets the e2e suite (tests/e2e/manager.mjs) drive requests through this client
if (import.meta.env.DEV) window.__xeniaClient = client
export default client export default client
+26 -24
View File
@@ -1,11 +1,30 @@
import useAuthStore from '../store/authStore' import { useAccess } from '@xenia/access'
// The current screens' permission names -> the v2 keys they stand for (the same pairs as
// local_backend/core/access/legacy.py). Removed when the pages use useCan(key) directly (phase 6).
const KEYS = {
accessDashboard: 'core.dashboard.access',
accessWaiterApp: 'waiter_app.access',
accessKds: 'kds.access',
cancelOrders: 'ordering.orders.cancel',
applyDiscounts: 'pricing.discounts.apply',
modifyPrices: 'ordering.prices.modify',
openOrders: 'ordering.orders.open',
closeOrders: 'ordering.orders.close',
viewReports: 'reports.view',
manageStaff: 'core.staff.manage',
manageTables: 'catalog.tables.manage',
manageMenu: 'catalog.menu.manage',
manageSettings: 'core.settings.manage',
}
/** /**
* Returns a permissions object derived from the logged-in user. * The signed-in user's permissions in the shape the current pages use, from the keys in
* Superadmin always has every permission regardless of stored flags. * the platform bootstrap (@xenia/access). A key whose module is off counts as not held.
* Superadmin holds every key (the backend sends them all).
*/ */
export default function usePermissions() { export default function usePermissions() {
const user = useAuthStore(s => s.user) const { user, permissions } = useAccess()
if (!user) { if (!user) {
return { return {
@@ -26,24 +45,7 @@ export default function usePermissions() {
} }
} }
const superadmin = user.role === 'superadmin' const out = { isSuperadmin: user.role === 'superadmin' }
for (const [name, key] of Object.entries(KEYS)) out[name] = permissions.has(key)
const p = (flag) => superadmin || !!user[flag] return out
return {
isSuperadmin: superadmin,
accessDashboard: p('perm_access_dashboard'),
accessWaiterApp: p('perm_access_waiter_app'),
accessKds: p('perm_access_kds'),
cancelOrders: p('perm_cancel_orders'),
applyDiscounts: p('perm_apply_discounts'),
modifyPrices: p('perm_modify_prices'),
openOrders: p('perm_open_orders'),
closeOrders: p('perm_close_orders'),
viewReports: p('perm_view_reports'),
manageStaff: p('perm_manage_staff'),
manageTables: p('perm_manage_tables'),
manageMenu: p('perm_manage_menu'),
manageSettings: p('perm_manage_settings'),
}
} }
+2 -1
View File
@@ -188,7 +188,8 @@ function LockScreen({ username, displayName, onUnlock, onLogout }) {
setError('') setError('')
setLoading(true) setLoading(true)
try { try {
const { data } = await client.post('/api/auth/login', { username, pin: usedPin }) // A wrong PIN is a 401: say "Wrong PIN" instead of the session-ended logout
const { data } = await client.post('/api/auth/login', { username, pin: usedPin }, { xenia: { ignoreUnauthorized: true } })
if (!data.user.perm_access_dashboard) { if (!data.user.perm_access_dashboard) {
setError('Not a manager account.') setError('Not a manager account.')
setPin('') setPin('')
+3 -2
View File
@@ -145,7 +145,7 @@ export default function LoginPage() {
async function handleAutoLogin(uname) { async function handleAutoLogin(uname) {
setLoading(true) setLoading(true)
try { try {
const { data } = await client.post('/api/auth/login-no-auth', { username: uname }) const { data } = await client.post('/api/auth/login-no-auth', { username: uname }, { xenia: { ignoreUnauthorized: true } })
if (!data.user.perm_access_dashboard) { setLoading(false); return } if (!data.user.perm_access_dashboard) { setLoading(false); return }
clearManualLogoutFlag() clearManualLogoutFlag()
login(data.user, data.access_token) login(data.user, data.access_token)
@@ -169,7 +169,8 @@ export default function LoginPage() {
if (loginMethod === 'password') body.password = password if (loginMethod === 'password') body.password = password
else if (loginMethod === 'pin') body.pin = pin else if (loginMethod === 'pin') body.pin = pin
const { data } = await client.post('/api/auth/login', body) // A wrong password is a 401: show it here instead of the session-ended logout
const { data } = await client.post('/api/auth/login', body, { xenia: { ignoreUnauthorized: true } })
if (!data.user.perm_access_dashboard) { if (!data.user.perm_access_dashboard) {
setError('This account does not have manager access.') setError('This account does not have manager access.')
setPin('') setPin('')
+7 -4
View File
@@ -1,6 +1,8 @@
import { defineConfig } from 'vite' import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
const BACKEND = process.env.XENIA_BACKEND || 'http://localhost:8000'
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
// npm workspace (D-15): shared packages are imported from source, so make // npm workspace (D-15): shared packages are imported from source, so make
@@ -12,11 +14,12 @@ export default defineConfig({
host: '0.0.0.0', host: '0.0.0.0',
port: 5174, port: 5174,
// Same as the waiter: the API is same-origin in production (nginx), so in // Same as the waiter: the API is same-origin in production (nginx), so in
// dev (and `vite preview`) forward it to the local backend. // dev (and `vite preview`) forward it to the local backend. XENIA_BACKEND picks
// another one (the e2e suite runs its own on :8056).
proxy: { proxy: {
'/api/ws': { target: 'ws://localhost:8000', ws: true, changeOrigin: true }, '/api/ws': { target: BACKEND.replace(/^http/, 'ws'), ws: true, changeOrigin: true },
'/api': { target: 'http://localhost:8000', changeOrigin: true }, '/api': { target: BACKEND, changeOrigin: true },
'/static': { target: 'http://localhost:8000', changeOrigin: true }, '/static': { target: BACKEND, changeOrigin: true },
}, },
}, },
}) })
+9 -1
View File
@@ -16,6 +16,8 @@
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.62.0", "@tanstack/react-query": "^5.62.0",
"@xenia/access": "^0.0.0",
"@xenia/api": "^0.0.0",
"@xenia/i18n": "^0.0.0", "@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.7.9", "axios": "^1.7.9",
@@ -2943,7 +2945,12 @@
}, },
"packages/access": { "packages/access": {
"name": "@xenia/access", "name": "@xenia/access",
"version": "0.0.0" "version": "0.0.0",
"dependencies": {
"@xenia/api": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0"
}
}, },
"packages/api": { "packages/api": {
"name": "@xenia/api", "name": "@xenia/api",
@@ -2976,6 +2983,7 @@
"@capacitor/core": "8.5.2", "@capacitor/core": "8.5.2",
"@capgo/capacitor-updater": "8.51.25", "@capgo/capacitor-updater": "8.51.25",
"@tanstack/react-query": "^5.100.11", "@tanstack/react-query": "^5.100.11",
"@xenia/api": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.15.1", "axios": "^1.15.1",
"dexie": "^4.4.2", "dexie": "^4.4.2",
+12 -1
View File
@@ -3,9 +3,20 @@
"version": "0.0.0", "version": "0.0.0",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "Bootstrap provider and module/permission hooks: useModule, useCan, <Can>, <RequireModule> (plan step 2.5).", "description": "Bootstrap provider, module/permission hooks and guards, and the manager-approval dialog (plan step 2.5).",
"main": "src/index.js", "main": "src/index.js",
"exports": { "exports": {
".": "./src/index.js" ".": "./src/index.js"
},
"dependencies": {
"@xenia/api": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0"
},
"scripts": {
"test": "node --test \"tests/*.test.mjs\""
},
"peerDependencies": {
"react": "^19.0.0"
} }
} }
+105
View File
@@ -0,0 +1,105 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { parseError } from '@xenia/api'
import { I18nProvider, resolveLanguage, useTranslation, useUiLabels } from '@xenia/i18n'
import { Button, EmptyState, Spinner, UiLabelsProvider } from '@xenia/ui'
import { AccessContext } from './context.js'
import { OverrideHost } from './OverrideHost.jsx'
/**
* The root of every app (plan step 2.5, APPS_PLATFORM §9):
*
* <AccessProvider client={client} token={token} i18n={i18n}>
* <App />
* </AccessProvider>
*
* - loads GET /api/platform/bootstrap (works signed in or not) and again whenever `token`
* changes (login, logout, unlock), so modules and permission keys always match the session
* - sets the language: user → device (`deviceLanguage`) → venue → en (D-12), and gives
* bootstrap.venue (time zone, currency) to the formatters (@xenia/i18n)
* - translates the @xenia/ui component labels and mounts the manager-approval dialog
* for `client` (OverrideHost), unless override={false}
* Until the bootstrap for the current token has loaded it renders `loading` (a spinner by
* default); if it fails, an error screen with Retry. Nothing below ever sees a half-loaded state.
*/
export function AccessProvider({
client, token = null, i18n, deviceLanguage, override = true, loading, children,
}) {
const [state, setState] = useState({ data: null, forToken: undefined, error: null })
const load = useCallback(async () => {
try {
const { data } = await client.get('/api/platform/bootstrap', { xenia: { ignoreUnauthorized: true, noOverride: true } })
if (i18n) {
await i18n.changeLanguage(resolveLanguage({ user: data.user?.language, device: deviceLanguage, venue: data.venue?.language }))
}
setState({ data, forToken: token, error: null })
} catch (e) {
setState(s => ({ ...s, forToken: token, error: parseError(e) }))
}
}, [client, token, i18n, deviceLanguage])
useEffect(() => { load() }, [load])
const value = useMemo(() => {
const d = state.data
if (!d) return null
return {
bootstrap: d,
venue: d.venue,
user: d.user,
license: d.license,
languages: d.languages,
language: d.language,
modules: new Set((d.modules || []).map(m => m.key)),
permissions: new Set(d.permissions || []),
refresh: load,
}
}, [state.data, load])
const current = state.forToken === token
let content
if (value && current && !state.error) {
content = (
<AccessContext.Provider value={value}>
{override && <OverrideHost client={client} />}
{children}
</AccessContext.Provider>
)
} else if (state.error && current) {
content = <LoadFailed error={state.error} retry={load} />
} else {
content = loading === undefined ? <DefaultLoading /> : loading
}
if (!i18n) return content
return (
<I18nProvider i18n={i18n} venue={state.data?.venue}>
<TranslatedLabels>{content}</TranslatedLabels>
</I18nProvider>
)
}
function TranslatedLabels({ children }) {
return <UiLabelsProvider labels={useUiLabels()}>{children}</UiLabelsProvider>
}
function DefaultLoading() {
return (
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<Spinner size="md" />
</div>
)
}
function LoadFailed({ error, retry }) {
const { t } = useTranslation('common')
return (
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }} data-testid="access-load-failed">
<EmptyState
title={t('access.loadFailed')}
description={t(`errors:${error.code}`, { ...error.params, defaultValue: error.message })}
action={<Button variant="secondary" onClick={retry}>{t('actions.retry')}</Button>}
/>
</div>
)
}
+76
View File
@@ -0,0 +1,76 @@
import { useEffect, useRef, useState } from 'react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input } from '@xenia/ui'
/**
* The manager-approval dialog (D-10) for an @xenia/api client. Mount it once (AccessProvider
* does). When a request is refused with `access.override_possible`, it asks for a manager's
* username + PIN; a wrong PIN shows the error and lets them try again; Cancel gives the
* original refusal back to the caller (err.xenia.overrideCancelled).
*/
export function OverrideHost({ client }) {
const { t } = useTranslation('common')
const [req, setReq] = useState(null) // { key, params, error, resolve }
const [busy, setBusy] = useState(false)
const [username, setUsername] = useState('')
const [pin, setPin] = useState('')
const pinRef = useRef(null)
const userRef = useRef(null)
useEffect(() => {
if (!client?.setOverrideHandler) return undefined
return client.setOverrideHandler({
ask: ({ key, params, error }) => new Promise(resolve => {
setBusy(false)
setPin('')
setReq({ key, params, error, resolve })
}),
finished: () => {
setReq(null)
setBusy(false)
setPin('')
},
})
}, [client])
if (!req) return null
const submit = e => {
e?.preventDefault()
if (busy || !username.trim() || !pin) return
setBusy(true)
req.resolve({ username: username.trim(), pin })
}
const cancel = () => { if (!busy) req.resolve(null) }
return (
<Dialog
open
size="sm"
onClose={busy ? undefined : cancel}
title={t('override.title')}
description={t('override.body')}
initialFocus={username ? pinRef : userRef}
footer={(
<>
<Button variant="secondary" onClick={cancel} disabled={busy}>{t('actions.cancel')}</Button>
<Button type="submit" form="x-override-form" loading={busy}>{t('override.approve')}</Button>
</>
)}
>
<form id="x-override-form" onSubmit={submit} style={{ display: 'grid', gap: 'var(--x-space-4)' }}>
<div style={{ fontSize: 'var(--x-text-label)', color: 'var(--x-ink-3)' }}>
{t('override.action')}: <code data-testid="override-key">{req.key}</code>
</div>
<Field label={t('override.username')}>
<Input ref={userRef} value={username} onChange={e => setUsername(e.target.value)} autoComplete="off" autoCapitalize="none" disabled={busy} />
</Field>
<Field label={t('override.pin')} error={req.error ? errorMessage({ xenia: req.error }, t) : undefined}>
<Input ref={pinRef} type="password" inputMode="numeric" autoComplete="off" value={pin} onChange={e => setPin(e.target.value.replace(/\D/g, ''))} disabled={busy} />
</Field>
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
</form>
</Dialog>
)
}
+4
View File
@@ -0,0 +1,4 @@
import { createContext } from 'react'
/** The loaded bootstrap + helpers (filled by <AccessProvider>, read by useAccess()). */
export const AccessContext = createContext(null)
+34
View File
@@ -0,0 +1,34 @@
import { EmptyState } from '@xenia/ui'
import { useTranslation } from '@xenia/i18n'
import { useCan, useModule } from './hooks.js'
/**
* Show children only to users holding the key(s).
* <Can perm="catalog.menu.manage"><Button>Edit</Button></Can>
* <Can perm={['reports.view', 'history.view']} fallback={<NoAccess />}>…</Can> (any of them)
* <Can perm={[…]} all>…</Can> (all of them)
*/
export function Can({ perm, all = false, fallback = null, children }) {
return useCan(perm, { all }) ? children : fallback
}
/**
* Render children only if the module is licensed and on; otherwise `fallback`
* (default: a "this feature is turned off" screen).
* <Route path="/kds" element={<RequireModule module="kds"><KdsPage /></RequireModule>} />
*/
export function RequireModule({ module, fallback, children }) {
const on = useModule(module)
if (on) return children
return fallback === undefined ? <ModuleOff /> : fallback
}
export function ModuleOff() {
const { t } = useTranslation('common')
return <EmptyState title={t('access.moduleOffTitle')} description={t('access.moduleOffBody')} />
}
export function NoAccess() {
const { t } = useTranslation('common')
return <EmptyState title={t('access.noAccessTitle')} description={t('access.noAccessBody')} />
}
+32
View File
@@ -0,0 +1,32 @@
import { useContext } from 'react'
import { AccessContext } from './context.js'
/**
* Everything bootstrap said (GET /api/platform/bootstrap):
* { venue, user, permissions (Set), modules (Set), license, languages, bootstrap (raw), refresh() }
* permissions: the keys the signed-in user holds, only for modules that are on (superadmin: all).
*/
export function useAccess() {
const ctx = useContext(AccessContext)
if (!ctx) throw new Error('useAccess() needs an <AccessProvider> above it')
return ctx
}
/** Is this module licensed and turned on? */
export function useModule(key) {
return useAccess().modules.has(key)
}
/**
* Does the signed-in user hold this key? With a list, ANY of them (like the backend's
* require_any); { all: true } for all of them. Hides UI only: the backend always checks too.
*/
export function useCan(keys, { all = false } = {}) {
return can(useAccess().permissions, keys, all)
}
export function can(permissions, keys, all = false) {
const list = Array.isArray(keys) ? keys : [keys]
if (!list.length) return true
return all ? list.every(k => permissions.has(k)) : list.some(k => permissions.has(k))
}
+15 -3
View File
@@ -1,3 +1,15 @@
// @xenia/access — Bootstrap provider and module/permission hooks: useModule, useCan, <Can>, <RequireModule> (plan step 2.5). // @xenia/access — what this venue has turned on and what the signed-in user may do,
// Imported from source by Vite (no build step). Filled in by its plan step. // for every frontend (plan step 2.5, APPS_PLATFORM §5, §6, §9). React; imported from source.
export {} //
// <AccessProvider client={client} token={token} i18n={i18n}> loads bootstrap, sets language,
// … mounts the manager-approval dialog
// useAccess() → { venue, user, permissions, modules, license, refresh }
// useModule('kds') · useCan('catalog.menu.manage') · useCan([a, b]) (any) · useCan([a, b], { all: true })
// <Can perm="…" fallback={…}> · <RequireModule module="…">
//
// UI hiding only: the backend checks every request (CS-14).
export { AccessProvider } from './AccessProvider.jsx'
export { useAccess, useModule, useCan, can } from './hooks.js'
export { Can, RequireModule, ModuleOff, NoAccess } from './guards.jsx'
export { OverrideHost } from './OverrideHost.jsx'
+20
View File
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { can } from '../src/hooks.js'
const held = new Set(['reports.view', 'catalog.menu.manage'])
test('one key', () => {
assert.equal(can(held, 'reports.view'), true)
assert.equal(can(held, 'core.staff.manage'), false)
})
test('a list means any of them (like require_any), or all with all=true', () => {
assert.equal(can(held, ['core.staff.manage', 'reports.view']), true)
assert.equal(can(held, ['core.staff.manage', 'reports.view'], true), false)
assert.equal(can(held, ['reports.view', 'catalog.menu.manage'], true), true)
})
test('an empty list asks for nothing', () => {
assert.equal(can(new Set(), []), true)
})
+4 -1
View File
@@ -3,9 +3,12 @@
"version": "0.0.0", "version": "0.0.0",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "HTTP client (base URL, auth/device/override headers, error codes) and the WebSocket client (plan step 2.5).", "description": "HTTP client (auth/device/override headers, error codes, manager-override retry) and the live WebSocket client with cursor replay (plan step 2.5).",
"main": "src/index.js", "main": "src/index.js",
"exports": { "exports": {
".": "./src/index.js" ".": "./src/index.js"
},
"scripts": {
"test": "node --test \"tests/*.test.mjs\""
} }
} }
+103
View File
@@ -0,0 +1,103 @@
// HTTP client for every frontend (plan step 2.5, APPS_PLATFORM §9).
//
// import axios from 'axios'
// const client = createApiClient({
// axios, // the app's own axios (each app pins its version)
// baseURL: '', // manager/terminal: same origin; waiter: () => apiBase() (CS-8)
// getToken: () => localStorage.getItem('manager_token'),
// getDeviceToken: () => …, // paired devices (D-8): X-Xenia-Device
// onUnauthorized: x => …, // a 401 (session ended, bad token)
// onOffline: x => …, // no response at all
// })
//
// Every rejected request carries err.xenia = parseError(err) ({ code, params, message, status, offline }).
// Manager override (D-10): when a request is refused with `access.override_possible`, the
// client asks the registered override handler (see @xenia/access <OverrideHost>) for a
// manager's username + PIN, gets a one-time token from POST /api/access/override, and
// retries the request ONCE with X-Xenia-Override. The token is bound to this session and
// key and valid for 60 s. Wrong PIN → the handler is asked again with the error; cancel →
// the original error is rejected with err.xenia.overrideCancelled = true.
//
// Per-request options (config.xenia): { ignoreUnauthorized: true } (don't call onUnauthorized,
// e.g. a login form's own 401), { noOverride: true } (never run the override flow).
import { parseError } from './errors.js'
export const DEVICE_HEADER = 'X-Xenia-Device'
export const OVERRIDE_HEADER = 'X-Xenia-Override'
export function createApiClient({
axios, baseURL = '', getToken, getDeviceToken, onUnauthorized, onOffline, timeout = 0,
} = {}) {
if (!axios?.create) throw new Error('createApiClient needs the app\'s axios: createApiClient({ axios, … })')
const client = axios.create({ baseURL: typeof baseURL === 'function' ? '' : baseURL, timeout })
let override = null // { ask, finished } from the UI, see setOverrideHandler
client.interceptors.request.use(config => {
if (typeof baseURL === 'function') config.baseURL = baseURL()
const token = getToken?.()
if (token && !config.headers.Authorization) config.headers.Authorization = `Bearer ${token}`
const device = getDeviceToken?.()
if (device) config.headers[DEVICE_HEADER] = device
return config
})
client.interceptors.response.use(
res => res,
async err => {
const x = parseError(err)
err.xenia = x
const opts = err.config?.xenia || {}
if (x.code === 'access.override_possible' && override && !opts.noOverride && !opts.overrideTried) {
return runOverride(err)
}
if (x.offline) onOffline?.(x)
else if (x.status === 401 && !opts.ignoreUnauthorized) onUnauthorized?.(x)
throw err
},
)
async function runOverride(original) {
const { key, ...params } = original.xenia.params || {}
const handler = override
let lastError = null
try {
for (;;) {
const creds = await handler.ask({ key, params, error: lastError })
if (!creds) {
original.xenia.overrideCancelled = true
throw original
}
let token
try {
const { data } = await client.post('/api/access/override',
{ key, username: creds.username, pin: creds.pin },
{ xenia: { noOverride: true, ignoreUnauthorized: true } })
token = data.override_token
} catch (e) {
lastError = parseError(e)
if (lastError.offline) throw e
continue // wrong PIN, approver lacks the key, rate limited… ask again (the user can cancel)
}
const config = original.config
return await client.request({
...config,
headers: { ...config.headers, [OVERRIDE_HEADER]: token },
xenia: { ...(config.xenia || {}), overrideTried: true },
})
}
} finally {
handler.finished?.()
}
}
/**
* The UI side of the override flow. handler.ask({ key, params, error }) → Promise<{ username, pin } | null>
* (null = cancelled); handler.finished() when the flow is over (approved or not).
* Returns a function that unregisters it.
*/
client.setOverrideHandler = handler => {
override = handler
return () => { if (override === handler) override = null }
}
return client
}
+51
View File
@@ -0,0 +1,51 @@
// Backend errors as data (APPS_PLATFORM D-12, §3.2; local_backend/core/errors.py).
//
// Every error response looks like
// { "error": { "code": "order.not_found", "params": { "order_id": 7 }, "message": "Order 7 not found." },
// "detail": "Order 7 not found." }
// Older endpoints still raise plain HTTPExceptions, which the backend wraps as "http.<status>"
// with their original `detail`. parseError() turns any axios error into one shape.
/**
* @returns {{ code: string, params: object, message: string, status: number|null, offline: boolean, detail: any }}
* offline: no response at all (network down, server unreachable, timeout) → code "network.offline"
*/
export function parseError(err) {
if (err?.xenia) return err.xenia
const res = err?.response
if (!res) {
return { code: 'network.offline', params: {}, message: err?.message || 'Network error', status: null, offline: true, detail: null }
}
const body = res.data && typeof res.data === 'object' ? res.data : {}
const e = body.error && typeof body.error === 'object' ? body.error : null
const detail = body.detail ?? null
return {
code: e?.code || `http.${res.status}`,
params: e?.params || {},
message: e?.message || (typeof detail === 'string' ? detail : '') || `HTTP ${res.status}`,
status: res.status,
offline: false,
detail,
}
}
/**
* A message for the user, in their language.
* errorMessage(err, t) with t from useTranslation() (@xenia/i18n has the `errors` namespace)
* Order: the translated code (errors:<code>, with the error's params) → the backend's English
* message → a generic text. Without `t`, the backend's English message.
*/
export function errorMessage(err, t) {
const x = parseError(err)
if (!t) return x.message
const key = `errors:${x.code}`
const translated = t(key, { ...x.params, defaultValue: '' })
if (translated && translated !== key) return translated
if (x.code.startsWith('http.') && x.message) return x.message
return t('errors:generic', { defaultValue: x.message })
}
/** True when the error is this code (works on axios errors and parsed ones). */
export function isError(err, code) {
return parseError(err).code === code
}
+13 -3
View File
@@ -1,3 +1,13 @@
// @xenia/api — HTTP client (base URL, auth/device/override headers, error codes) and the WebSocket client (plan step 2.5). // @xenia/api — talking to the local backend, for every frontend (plan step 2.5,
// Imported from source by Vite (no build step). Filled in by its plan step. // APPS_PLATFORM §9). Plain JavaScript (no React); imported from source by Vite.
export {} //
// createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized, onOffline })
// → an axios instance: auth/device headers, err.xenia on every error, manager-override retry
// parseError(err) / errorMessage(err, t) / isError(err, code)
// createLiveClient({ url, cursor, onEvent, onReady, onDisconnect }) WebSocket + cursor replay
//
// React glue (bootstrap, permissions, the override dialog) lives in @xenia/access.
export { createApiClient, DEVICE_HEADER, OVERRIDE_HEADER } from './client.js'
export { parseError, errorMessage, isError } from './errors.js'
export { createLiveClient, wsUrlFor, INITIAL_RECONNECT_DELAY, MAX_RECONNECT_DELAY } from './live.js'
+123
View File
@@ -0,0 +1,123 @@
// Live events over the backend WebSocket, with cursor replay (plan step 2.5).
// Lifted from waiter_pwa/src/hooks/useWebSocket.js without changing behaviour; the waiter's
// hook is now a thin wrapper around this. No React.
//
// Protocol (local_backend/routers/ws.py):
// 1. connect to ws[s]://host/api/ws/connect?token=<jwt>
// 2. send { cursor: <last seq> } at once (0 = first connect / no history)
// 3. the server replays missed events, then sends { type: "ready" }
// 4. live events: { seq, type, data }
// 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
// it. The browser's `online` event reconnects at once. The cursor survives reloads through
// the `cursor` store the app provides (the waiter keeps it in IndexedDB).
//
// const live = createLiveClient({
// url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`),
// cursor: { load: async () => seq, save: seq => … },
// onEvent: (type, data) => …, onReady: () => …, onDisconnect: () => …,
// })
// live.start(); …; live.reconnect(); …; live.stop()
export const INITIAL_RECONNECT_DELAY = 2_000
export const MAX_RECONNECT_DELAY = 30_000
/** ws(s)://<host of baseURL or the page>/<path> */
export function wsUrlFor(path, baseURL = '') {
const base = baseURL || (typeof location !== 'undefined' ? location.origin : 'http://localhost')
const u = new URL(path, base)
u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:'
return u.toString()
}
export function createLiveClient({
url, cursor, onEvent, onReady, onDisconnect,
WebSocketImpl = globalThis.WebSocket,
windowTarget = typeof window !== 'undefined' ? window : null,
timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id) },
}) {
let ws = null
let reconnectTimer = null
let reconnectDelay = INITIAL_RECONNECT_DELAY
let stopped = true
let lastSeq = 0
function connect() {
if (stopped) return
if (ws) {
ws.onclose = null // prevent a double reconnect
ws.close()
ws = null
}
const socket = new WebSocketImpl(typeof url === 'function' ? url() : url)
ws = socket
socket.onopen = () => {
reconnectDelay = INITIAL_RECONNECT_DELAY
socket.send(JSON.stringify({ cursor: lastSeq })) // the server replays what we missed
}
socket.onmessage = e => {
let msg
try { msg = JSON.parse(e.data) } catch { return }
if (msg.type === 'ping') return
if (msg.type === 'ready') { onReady?.(); return }
if (msg.seq && msg.seq > lastSeq) {
lastSeq = msg.seq
cursor?.save?.(msg.seq)
}
if (msg.type && msg.data !== undefined) onEvent?.(msg.type, msg.data)
}
socket.onerror = () => {} // onerror always comes before onclose; onclose reconnects
socket.onclose = () => {
ws = null
onDisconnect?.()
if (stopped) return
// wait the current delay, then grow it for the attempt after
reconnectTimer = timers.setTimeout(() => {
reconnectDelay = Math.min(reconnectDelay * 1.5, MAX_RECONNECT_DELAY)
connect()
}, reconnectDelay)
}
}
function onNetworkOnline() {
timers.clearTimeout(reconnectTimer)
reconnectDelay = INITIAL_RECONNECT_DELAY
connect()
}
return {
/** Load the saved cursor, then connect. */
async start() {
if (!stopped) return
stopped = false
windowTarget?.addEventListener('online', onNetworkOnline)
let seq = 0
try { seq = (await cursor?.load?.()) ?? 0 } catch { seq = 0 }
lastSeq = seq
if (!stopped) connect()
},
/** Close for good (no reconnect). */
stop() {
stopped = true
timers.clearTimeout(reconnectTimer)
windowTarget?.removeEventListener('online', onNetworkOnline)
if (ws) {
ws.onclose = null
ws.close()
ws = null
}
},
/** Reconnect now, with the backoff reset (e.g. the app came back to the foreground). */
reconnect() {
timers.clearTimeout(reconnectTimer)
reconnectDelay = INITIAL_RECONNECT_DELAY
connect()
},
get lastSeq() { return lastSeq },
get connected() { return !!ws && ws.readyState === 1 },
}
}
+157
View File
@@ -0,0 +1,157 @@
// createApiClient against a tiny HTTP server that answers like the backend.
// Uses the manager's real axios (the apps pass their own).
import assert from 'node:assert/strict'
import http from 'node:http'
import { createRequire } from 'node:module'
import { after, before, test } from 'node:test'
import { createApiClient, errorMessage, isError, parseError } from '../src/index.js'
const require = createRequire(new URL('../../../manager_dashboard/package.json', import.meta.url))
const axios = require('axios')
const err = (code, params, message) => ({ error: { code, params, message }, detail: message })
let server, base
const seen = []
before(async () => {
server = http.createServer((req, res) => {
let body = ''
req.on('data', c => { body += c })
req.on('end', () => {
seen.push({ method: req.method, url: req.url, headers: req.headers, body: body ? JSON.parse(body) : null })
const send = (status, obj) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(obj)) }
if (req.url === '/ok') return send(200, { ok: true })
if (req.url === '/old') return send(404, { detail: 'Not here' })
if (req.url === '/new') return send(404, err('order.not_found', { order_id: 7 }, 'Order 7 not found.'))
if (req.url === '/ended') return send(401, err('auth.session_ended', {}, 'Your session has ended.'))
if (req.url === '/api/orders/5/cancel') {
return req.headers['x-xenia-override'] === 'tok-1'
? send(200, { cancelled: true, body: body ? JSON.parse(body) : null })
: send(403, err('access.override_possible', { key: 'ordering.orders.cancel', reason: 'sent' }, 'A manager can approve this.'))
}
if (req.url === '/api/access/override') {
const b = JSON.parse(body)
if (b.pin === '9999') return send(429, err('access.override_rate_limited', {}, 'Too many wrong PINs.'))
return b.pin === '1234' && b.username === 'boss'
? send(200, { override_token: 'tok-1', key: b.key })
: send(401, err('auth.invalid_credentials', {}, 'Wrong username or password.'))
}
send(500, err('internal.error', { request_id: 'r1' }, 'Something went wrong'))
})
})
await new Promise(r => server.listen(0, '127.0.0.1', r))
base = `http://127.0.0.1:${server.address().port}`
})
after(() => server.close())
function make(extra = {}) {
const calls = { unauthorized: [], offline: [] }
const client = createApiClient({
axios, baseURL: base, getToken: () => 'jwt-1', getDeviceToken: () => 'dev-9',
onUnauthorized: x => calls.unauthorized.push(x.code), onOffline: x => calls.offline.push(x.code), ...extra,
})
return { client, calls }
}
test('sends the session and device headers', async () => {
const { client } = make()
await client.get('/ok')
const h = seen.at(-1).headers
assert.equal(h.authorization, 'Bearer jwt-1')
assert.equal(h['x-xenia-device'], 'dev-9')
})
test('baseURL can be a function (the waiter: active venue)', async () => {
let n = 0
const client = createApiClient({ axios, baseURL: () => { n++; return base } })
await client.get('/ok')
assert.equal(n, 1)
assert.equal(seen.at(-1).headers.authorization, undefined)
})
test('errors carry err.xenia: new codes and old detail-only errors', async () => {
const { client } = make()
const e1 = await client.get('/new').catch(e => e)
assert.deepEqual([e1.xenia.code, e1.xenia.params, e1.xenia.status], ['order.not_found', { order_id: 7 }, 404])
assert.equal(e1.response.data.detail, 'Order 7 not found.', 'v1 screens still read detail')
const e2 = await client.get('/old').catch(e => e)
assert.deepEqual([e2.xenia.code, e2.xenia.message], ['http.404', 'Not here'])
assert.ok(isError(e1, 'order.not_found'))
})
test('401 calls onUnauthorized unless the request opts out', async () => {
const { client, calls } = make()
await client.get('/ended').catch(() => {})
await client.get('/ended', { xenia: { ignoreUnauthorized: true } }).catch(() => {})
assert.deepEqual(calls.unauthorized, ['auth.session_ended'])
})
test('no response at all = network.offline + onOffline', async () => {
const calls = []
const client = createApiClient({ axios, baseURL: 'http://127.0.0.1:9', onOffline: x => calls.push(x.code) })
const e = await client.get('/ok').catch(x => x)
assert.equal(e.xenia.code, 'network.offline')
assert.ok(e.xenia.offline)
assert.deepEqual(calls, ['network.offline'])
})
test('override: wrong PIN, ask again, approve, retry once with the token', async () => {
const { client, calls } = make()
const asked = []
let finished = 0
const answers = [{ username: 'boss', pin: '0000' }, { username: 'boss', pin: '1234' }]
client.setOverrideHandler({ ask: async a => { asked.push(a); return answers.shift() }, finished: () => finished++ })
const res = await client.post('/api/orders/5/cancel', { reason: 'mistake' })
assert.deepEqual(res.data, { cancelled: true, body: { reason: 'mistake' } })
assert.deepEqual(asked.map(a => [a.key, a.params, a.error?.code ?? null]), [
['ordering.orders.cancel', { reason: 'sent' }, null],
['ordering.orders.cancel', { reason: 'sent' }, 'auth.invalid_credentials'],
])
assert.equal(finished, 1)
assert.deepEqual(calls.unauthorized, [], "a wrong manager PIN doesn't log the user out")
const grant = seen.filter(s => s.url === '/api/access/override').at(-1)
assert.deepEqual(grant.body, { key: 'ordering.orders.cancel', username: 'boss', pin: '1234' })
assert.equal(grant.headers.authorization, 'Bearer jwt-1', 'the override is asked for with the user\'s own session')
})
test('override cancelled → the original error, marked', async () => {
const { client } = make()
let finished = 0
client.setOverrideHandler({ ask: async () => null, finished: () => finished++ })
const e = await client.post('/api/orders/5/cancel').catch(x => x)
assert.equal(e.xenia.code, 'access.override_possible')
assert.equal(e.xenia.overrideCancelled, true)
assert.equal(finished, 1)
})
test('override: rate limited is shown, then the user can still cancel', async () => {
const { client } = make()
const errors = []
const answers = [{ username: 'boss', pin: '9999' }, null]
client.setOverrideHandler({ ask: async a => { errors.push(a.error?.code ?? null); return answers.shift() } })
const e = await client.post('/api/orders/5/cancel').catch(x => x)
assert.deepEqual(errors, [null, 'access.override_rate_limited'])
assert.equal(e.xenia.overrideCancelled, true)
})
test('without a handler, or with noOverride, the refusal is just an error', async () => {
const { client } = make()
const e1 = await client.post('/api/orders/5/cancel').catch(x => x)
assert.equal(e1.xenia.code, 'access.override_possible')
let asked = 0
const off = client.setOverrideHandler({ ask: async () => { asked++; return null } })
await client.post('/api/orders/5/cancel', null, { xenia: { noOverride: true } }).catch(() => {})
off()
await client.post('/api/orders/5/cancel').catch(() => {})
assert.equal(asked, 0)
})
test('errorMessage: translated code → backend message → generic', () => {
const t = (key, opts) => ({ 'errors:order.not_found': `Η παραγγελία ${opts.order_id} δεν βρέθηκε`, 'errors:generic': 'Κάτι πήγε στραβά' }[key] ?? opts.defaultValue)
const resp = (status, data) => ({ response: { status, data } })
assert.equal(errorMessage(resp(404, err('order.not_found', { order_id: 7 }, 'Order 7 not found.')), t), 'Η παραγγελία 7 δεν βρέθηκε')
assert.equal(errorMessage(resp(400, { detail: 'Old style text' }), t), 'Old style text')
assert.equal(errorMessage(resp(422, err('some.new_code', {}, 'English text')), t), 'Κάτι πήγε στραβά')
assert.equal(errorMessage(resp(422, err('some.new_code', {}, 'English text'))), 'English text')
assert.equal(parseError({ message: 'Network Error' }).code, 'network.offline')
})
+159
View File
@@ -0,0 +1,159 @@
// The live client must behave exactly like the waiter's original useWebSocket hook.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { createLiveClient, wsUrlFor } from '../src/live.js'
class FakeWS {
static all = []
constructor(url) { this.url = url; this.sent = []; this.readyState = 0; this.closed = false; FakeWS.all.push(this) }
send(s) { this.sent.push(JSON.parse(s)) }
close() { this.closed = true; this.readyState = 3 }
// server side helpers
open() { this.readyState = 1; this.onopen?.() }
msg(obj) { this.onmessage?.({ data: typeof obj === 'string' ? obj : JSON.stringify(obj) }) }
drop() { this.readyState = 3; this.onerror?.(); this.onclose?.() }
}
function fakeTimers() {
const pending = []
return {
pending,
setTimeout(fn, ms) { const t = { fn, ms }; pending.push(t); return t },
clearTimeout(t) { const i = pending.indexOf(t); if (i >= 0) pending.splice(i, 1) },
fire() { const t = pending.shift(); t.fn(); return t.ms },
}
}
class FakeWindow {
listeners = {}
addEventListener(n, f) { (this.listeners[n] ||= new Set()).add(f) }
removeEventListener(n, f) { this.listeners[n]?.delete(f) }
emit(n) { for (const f of this.listeners[n] || []) f() }
}
function setup({ saved = 0 } = {}) {
FakeWS.all = []
const events = []
const log = []
const saves = []
const timers = fakeTimers()
const win = new FakeWindow()
const live = createLiveClient({
url: () => 'ws://venue/api/ws/connect?token=t',
cursor: { load: async () => saved, save: s => saves.push(s) },
onEvent: (type, data) => events.push([type, data]),
onReady: () => log.push('ready'),
onDisconnect: () => log.push('disconnect'),
WebSocketImpl: FakeWS, windowTarget: win, timers,
})
return { live, events, log, saves, timers, win, last: () => FakeWS.all.at(-1) }
}
test('sends the saved cursor on open, replays, then goes live', async () => {
const s = setup({ saved: 41 })
await s.live.start()
const ws = s.last()
assert.equal(ws.url, 'ws://venue/api/ws/connect?token=t')
ws.open()
assert.deepEqual(ws.sent, [{ cursor: 41 }])
ws.msg({ seq: 42, type: 'order_created', data: { id: 1 } }) // replayed
ws.msg({ type: 'ready' })
ws.msg({ type: 'ping' })
ws.msg({ seq: 43, type: 'order_updated', data: { id: 1 } }) // live
ws.msg('not json')
assert.deepEqual(s.events, [['order_created', { id: 1 }], ['order_updated', { id: 1 }]])
assert.deepEqual(s.log, ['ready'])
assert.deepEqual(s.saves, [42, 43])
assert.equal(s.live.lastSeq, 43)
})
test('the cursor never goes back; events without seq still arrive', async () => {
const s = setup({ saved: 10 })
await s.live.start(); s.last().open()
s.last().msg({ seq: 5, type: 'x', data: {} })
s.last().msg({ type: 'y', data: null })
s.last().msg({ type: 'z' }) // no data → ignored
assert.equal(s.live.lastSeq, 10)
assert.deepEqual(s.saves, [])
assert.deepEqual(s.events.map(e => e[0]), ['x', 'y'])
})
test('reconnect backoff: 2 s, 3 s, 4.5 s … capped at 30 s; a good open resets it', async () => {
const s = setup()
await s.live.start()
const waits = []
for (let i = 0; i < 9; i++) { s.last().drop(); waits.push(s.timers.fire()) }
assert.deepEqual(waits, [2000, 3000, 4500, 6750, 10125, 15187.5, 22781.25, 30000, 30000])
assert.equal(FakeWS.all.length, 10)
s.last().open()
s.last().drop()
assert.equal(s.timers.fire(), 2000)
assert.equal(s.log.filter(l => l === 'disconnect').length, 10)
})
test('reconnects with the last cursor seen', async () => {
const s = setup()
await s.live.start(); s.last().open()
s.last().msg({ seq: 7, type: 'a', data: {} })
s.last().drop(); s.timers.fire()
s.last().open()
assert.deepEqual(s.last().sent, [{ cursor: 7 }])
})
test('the browser coming online reconnects at once with the backoff reset', async () => {
const s = setup()
await s.live.start()
s.last().drop(); s.timers.fire(); s.last().drop() // delay is now 3 s
assert.equal(s.timers.pending.length, 1)
s.win.emit('online')
assert.equal(s.timers.pending.length, 0, 'the pending retry is cancelled')
assert.equal(FakeWS.all.length, 3)
s.last().drop()
assert.equal(s.timers.fire(), 2000)
})
test('reconnect() replaces the socket without a double reconnect', async () => {
const s = setup()
await s.live.start(); s.last().open()
const first = s.last()
s.live.reconnect()
assert.ok(first.closed)
assert.equal(first.onclose, null)
assert.equal(FakeWS.all.length, 2)
assert.equal(s.timers.pending.length, 0)
})
test('stop() closes for good and stops listening', async () => {
const s = setup()
await s.live.start(); s.last().open()
const ws = s.last()
s.live.stop()
assert.ok(ws.closed)
assert.equal(s.timers.pending.length, 0)
s.win.emit('online')
assert.equal(FakeWS.all.length, 1)
assert.equal(s.win.listeners.online.size, 0)
})
test('stop() during the cursor load: never connects', async () => {
const s = setup()
const p = s.live.start()
s.live.stop()
await p
assert.equal(FakeWS.all.length, 0)
})
test('a failing cursor store starts from 0', async () => {
FakeWS.all = []
const live = createLiveClient({
url: 'ws://x', cursor: { load: async () => { throw new Error('idb') } },
WebSocketImpl: FakeWS, windowTarget: null, timers: fakeTimers(),
})
await live.start(); FakeWS.all[0].open()
assert.deepEqual(FakeWS.all[0].sent, [{ cursor: 0 }])
})
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', 'http://192.168.1.5'), 'ws://192.168.1.5/api/ws/connect')
})
+15
View File
@@ -32,5 +32,20 @@
"notifications": "Ειδοποιήσεις", "notifications": "Ειδοποιήσεις",
"backspace": "Διαγραφή", "backspace": "Διαγραφή",
"pinProgress": "{{count}} από {{total}} ψηφία" "pinProgress": "{{count}} από {{total}} ψηφία"
},
"override": {
"title": "Έγκριση υπευθύνου",
"body": "Αυτό χρειάζεται έγκριση υπευθύνου. Ο υπεύθυνος συμπληρώνει εδώ το όνομα χρήστη και το PIN του.",
"action": "Ενέργεια",
"username": "Όνομα χρήστη υπευθύνου",
"pin": "PIN",
"approve": "Έγκριση"
},
"access": {
"moduleOffTitle": "Αυτή η λειτουργία είναι απενεργοποιημένη",
"moduleOffBody": "Ένας υπεύθυνος μπορεί να την ενεργοποιήσει από τις Εφαρμογές.",
"noAccessTitle": "Δεν έχετε πρόσβαση σε αυτή τη σελίδα",
"noAccessBody": "Ζητήστε την από έναν υπεύθυνο, αν τη χρειάζεστε.",
"loadFailed": "Δεν φορτώθηκαν οι ρυθμίσεις του καταστήματος"
} }
} }
+71
View File
@@ -0,0 +1,71 @@
{
"generic": "Κάτι πήγε στραβά. Δοκιμάστε ξανά.",
"network": {
"offline": "Δεν υπάρχει σύνδεση με τον διακομιστή. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά."
},
"access": {
"denied": "Δεν έχετε δικαίωμα για αυτή την ενέργεια ({{key}}).",
"override_possible": "Αυτή την ενέργεια μπορεί να την εγκρίνει ένας υπεύθυνος ({{key}}).",
"override_invalid": "Η έγκριση δεν ισχύει πια. Ζητήστε την ξανά από υπεύθυνο.",
"not_overridable": "Το {{key}} δεν μπορεί να εγκριθεί από υπεύθυνο.",
"approver_lacks_key": "Αυτός ο λογαριασμός δεν μπορεί να το εγκρίνει ({{key}}).",
"override_rate_limited": "Πολλά λάθος PIN. Περιμένετε λίγα λεπτά και δοκιμάστε ξανά.",
"unknown_key": "Δεν υπάρχει το δικαίωμα {{key}}.",
"cannot_grant": "Μπορείτε να δώσετε μόνο δικαιώματα που έχετε κι εσείς ({{key}})."
},
"module": {
"disabled": "Η λειτουργία {{module}} είναι απενεργοποιημένη.",
"not_licensed": "Η άδεια του καταστήματος δεν περιλαμβάνει τη λειτουργία {{module}}.",
"unknown": "Δεν υπάρχει η λειτουργία {{module}}.",
"cannot_disable": "Η λειτουργία {{module}} είναι βασική και δεν απενεργοποιείται."
},
"license": {
"limit_reached": "Φτάσατε το όριο της άδειας για {{module}} {{limit}} ({{max}}).",
"expired": "Η άδεια έχει λήξει.",
"history_limited": "Με αυτή την άδεια φαίνονται μόνο οι τελευταίες {{days}} ημέρες ({{module}})."
},
"auth": {
"invalid_credentials": "Λάθος όνομα χρήστη ή κωδικός.",
"session_ended": "Η σύνδεσή σας έληξε. Συνδεθείτε ξανά.",
"session_exists": "Είστε ήδη συνδεδεμένοι σε άλλο {{client}}. Αποσυνδεθείτε πρώτα από εκεί.",
"login_mode_not_allowed": "Αυτός ο τρόπος σύνδεσης δεν είναι ενεργός ({{mode}}).",
"mode_needs_device": "Η σύνδεση με {{mode}} γίνεται μόνο σε συζευγμένη συσκευή.",
"username_required": "Συμπληρώστε το όνομα χρήστη.",
"client_not_allowed": "Αυτός ο λογαριασμός δεν μπορεί να χρησιμοποιήσει την εφαρμογή {{client}}.",
"session_not_found": "Η σύνδεση δεν βρέθηκε.",
"support_not_configured": "Η πρόσβαση υποστήριξης δεν έχει ρυθμιστεί σε αυτό το κατάστημα.",
"support_code_invalid": "Ο κωδικός υποστήριξης είναι λάθος ή έχει λήξει. Ζητήστε νέο κωδικό πρόκλησης.",
"support_rate_limited": "Πολλές αιτήσεις υποστήριξης. Περιμένετε λίγα λεπτά και δοκιμάστε ξανά."
},
"device": {
"revoked": "Αυτή η συσκευή αφαιρέθηκε. Κάντε ξανά σύζευξη.",
"not_paired": "Αυτή η συσκευή δεν είναι συζευγμένη με το κατάστημα.",
"out_of_scope": "Μια συσκευή {{app}} δεν μπορεί να το κάνει αυτό ({{key}}).",
"required": "Αυτή η σύνδεση ανήκει σε συζευγμένη συσκευή. Χρησιμοποιήστε την από εκείνη τη συσκευή.",
"not_found": "Η συσκευή {{device_id}} δεν βρέθηκε.",
"pair_code_invalid": "Ο κωδικός σύζευξης είναι λάθος ή έχει λήξει.",
"pair_rate_limited": "Πολλές αιτήσεις σύζευξης. Περιμένετε λίγα λεπτά και δοκιμάστε ξανά.",
"not_an_app": "Το {{app}} δεν είναι εφαρμογή που τρέχει σε συσκευή.",
"login_mode_invalid": "Μια συσκευή {{app}} δεν μπορεί να χρησιμοποιήσει τον τρόπο σύνδεσης {{mode}}.",
"link_invalid": "Η συσκευή {{device_id}} δεν μπορεί να συνδεθεί με αυτή τη συσκευή."
},
"validation": {
"invalid": "Κάποια πεδία δεν είναι σωστά.",
"unknown_language": "Μη υποστηριζόμενη γλώσσα: {{language}}.",
"unknown_timezone": "Άγνωστη ζώνη ώρας: {{timezone}}.",
"setting_value": "Η ρύθμιση {{key}} δεν μπορεί να πάρει την τιμή «{{value}}»."
},
"internal": {
"error": "Κάτι πήγε στραβά στον διακομιστή (αίτημα {{request_id}})."
},
"order": {
"not_found": "Η παραγγελία {{order_id}} δεν βρέθηκε."
},
"notification": {
"not_found": "Η ειδοποίηση {{notification_id}} δεν βρέθηκε."
},
"catalog": {
"unknown_category": "Δεν υπάρχει η κατηγορία {{category_id}}.",
"primary_not_listed": "Η κύρια κατηγορία ({{category_id}}) πρέπει να είναι μία από τις κατηγορίες του προϊόντος."
}
}
+15
View File
@@ -32,5 +32,20 @@
"notifications": "Notifications", "notifications": "Notifications",
"backspace": "Delete", "backspace": "Delete",
"pinProgress": "{{count}} of {{total}} digits entered" "pinProgress": "{{count}} of {{total}} digits entered"
},
"override": {
"title": "Manager approval",
"body": "This needs a manager's approval. A manager enters their username and PIN here.",
"action": "Action",
"username": "Manager username",
"pin": "PIN",
"approve": "Approve"
},
"access": {
"moduleOffTitle": "This feature is turned off",
"moduleOffBody": "A manager can turn it on in Apps.",
"noAccessTitle": "You don't have access to this page",
"noAccessBody": "Ask a manager if you need it.",
"loadFailed": "Can't load the venue's settings"
} }
} }
+71
View File
@@ -0,0 +1,71 @@
{
"generic": "Something went wrong. Please try again.",
"network": {
"offline": "Can't reach the server. Check the connection and try again."
},
"access": {
"denied": "You don't have permission to do this ({{key}}).",
"override_possible": "A manager can approve this ({{key}}).",
"override_invalid": "This approval isn't valid any more. Ask a manager again.",
"not_overridable": "{{key}} can't be approved by a manager.",
"approver_lacks_key": "That account can't approve this ({{key}}).",
"override_rate_limited": "Too many wrong PINs. Wait a few minutes and try again.",
"unknown_key": "There is no permission {{key}}.",
"cannot_grant": "You can only give permissions you have yourself ({{key}})."
},
"module": {
"disabled": "The {{module}} module is turned off.",
"not_licensed": "This site's license doesn't include {{module}}.",
"unknown": "There is no module {{module}}.",
"cannot_disable": "{{module}} is part of the core and can't be turned off."
},
"license": {
"limit_reached": "License limit reached for {{module}} {{limit}} ({{max}}).",
"expired": "The license has expired.",
"history_limited": "This license shows only the last {{days}} days of history ({{module}})."
},
"auth": {
"invalid_credentials": "Wrong username or password.",
"session_ended": "Your session has ended. Please log in again.",
"session_exists": "You're already logged in on another {{client}}. Log out there first.",
"login_mode_not_allowed": "This way of logging in isn't enabled ({{mode}}).",
"mode_needs_device": "Logging in by {{mode}} only works on a paired device.",
"username_required": "Enter your username.",
"client_not_allowed": "This account can't use the {{client}} app.",
"session_not_found": "Session not found.",
"support_not_configured": "Support access isn't set up on this site.",
"support_code_invalid": "That support code is wrong or has expired. Ask for a new challenge.",
"support_rate_limited": "Too many support challenges. Wait a few minutes and try again."
},
"device": {
"revoked": "This device was removed. Pair it again.",
"not_paired": "This device isn't paired with the venue.",
"out_of_scope": "A {{app}} device can't do this ({{key}}).",
"required": "This login belongs to a paired device. Use it from that device.",
"not_found": "Device {{device_id}} not found.",
"pair_code_invalid": "That pairing code is wrong or has expired.",
"pair_rate_limited": "Too many pairing requests. Wait a few minutes and try again.",
"not_an_app": "{{app}} is not an app that runs on a device.",
"login_mode_invalid": "A {{app}} device can't use the login mode {{mode}}.",
"link_invalid": "Device {{device_id}} can't be linked to this device."
},
"validation": {
"invalid": "Some fields are invalid.",
"unknown_language": "Unsupported language: {{language}}.",
"unknown_timezone": "Unknown time zone: {{timezone}}.",
"setting_value": "{{key}} can't be set to \"{{value}}\"."
},
"internal": {
"error": "Something went wrong on the server (request {{request_id}})."
},
"order": {
"not_found": "Order {{order_id}} not found."
},
"notification": {
"not_found": "Notification {{notification_id}} not found."
},
"catalog": {
"unknown_category": "There is no category {{category_id}}.",
"primary_not_listed": "The main category ({{category_id}}) must be one of the product's categories."
}
}
+7 -4
View File
@@ -1,15 +1,18 @@
// Every locale file, bundled (they're small; no loading step, no flash of keys). // Every locale file, bundled (they're small; no loading step, no flash of keys).
// Layout (APPS_PLATFORM §8): locales/<lang>/<namespace>.json. English is the source. // Layout (APPS_PLATFORM §8): locales/<lang>/<namespace>.json. English is the source.
// Namespaces: common (shared words, component labels), dev (sample screens). Apps add // Namespaces: common (shared words, component labels), errors (backend error codes,
// local_backend/core/errors.py; tests/errors.test.mjs keeps them complete), dev (sample screens). Apps add
// theirs here as they're converted: manager, waiter, terminal, modules. // theirs here as they're converted: manager, waiter, terminal, modules.
import elCommon from '../locales/el/common.json' import elCommon from '../locales/el/common.json'
import elDev from '../locales/el/dev.json' import elDev from '../locales/el/dev.json'
import elErrors from '../locales/el/errors.json'
import enCommon from '../locales/en/common.json' import enCommon from '../locales/en/common.json'
import enDev from '../locales/en/dev.json' import enDev from '../locales/en/dev.json'
import enErrors from '../locales/en/errors.json'
export const NAMESPACES = ['common', 'dev'] export const NAMESPACES = ['common', 'errors', 'dev']
export const resources = { export const resources = {
en: { common: enCommon, dev: enDev }, en: { common: enCommon, errors: enErrors, dev: enDev },
el: { common: elCommon, dev: elDev }, el: { common: elCommon, errors: elErrors, dev: elDev },
} }
+32
View File
@@ -0,0 +1,32 @@
// Every error code the backend can return has a text in every language, using only
// params the backend sends (local_backend/core/errors.py CODES).
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { test } from 'node:test'
const py = readFileSync(new URL('../../../local_backend/core/errors.py', import.meta.url), 'utf8')
const start = py.indexOf('CODES: dict')
const block = py.slice(start, py.indexOf('\n}\n', start))
const ENTRY = /^\s*"([\w.]+)":\s*\(\d+,\s*"((?:[^"\\]|\\.)*)"\)/gm
const codes = Object.fromEntries([...block.matchAll(ENTRY)].map(m => [m[1], m[2]]))
const flat = (o, p = '') => Object.entries(o).flatMap(([k, v]) => (typeof v === 'object' ? flat(v, `${p}${k}.`) : [[`${p}${k}`, v]]))
const load = lang => Object.fromEntries(flat(JSON.parse(readFileSync(new URL(`../locales/${lang}/errors.json`, import.meta.url), 'utf8'))))
test('the backend registry was read', () => {
assert.ok(Object.keys(codes).length >= 40, String(Object.keys(codes).length))
assert.ok('order.not_found' in codes)
})
for (const lang of ['en', 'el']) {
test(`${lang}: every backend code has a text with backend params only`, () => {
const texts = load(lang)
const missing = Object.keys(codes).filter(c => !(c in texts))
assert.deepEqual(missing, [])
const bad = Object.keys(codes).filter(c => {
const params = new Set([...codes[c].matchAll(/\{(\w+)/g)].map(m => m[1]))
return [...texts[c].matchAll(/\{\{\s*(\w+)/g)].some(m => !params.has(m[1]))
})
assert.deepEqual(bad, [], 'placeholders the backend never sends')
assert.ok(texts.generic && texts['network.offline'])
})
}
+4 -1
View File
@@ -17,7 +17,9 @@ npm test # server rediscovery scan
cd .. cd ..
npm test -w @xenia/ui # PIN rules + WCAG contrast of every token pair (light/dark × venue themes) npm test -w @xenia/ui # PIN rules + WCAG contrast of every token pair (light/dark × venue themes)
npm test -w @xenia/i18n # venue-time formatting (DST), money/numbers, comma-or-dot parsing, language order, check-i18n guard npm test -w @xenia/i18n # venue-time formatting (DST), money/numbers, comma-or-dot parsing, language order, check-i18n guard, error texts vs core/errors.py
npm test -w @xenia/api # live client = the waiter's old WebSocket behaviour (backoff, cursor, online); HTTP client vs a fake backend (headers, codes, 401, offline, approval retry)
npm test -w @xenia/access # can(): one key, any/all
``` ```
**DB tests** (`local_backend/tests/conftest.py`) run the real FastAPI app against a throwaway SQLite database in a temp folder (never your dev or venue DB). Fixtures: `db` (session, rolled back after each test even if the code commits), `client` (TestClient with `get_db` overridden, license check open, no lifespan), `make_user(role=..., perms=...)` (password `password`, PIN `1234`), `login(user)` (auth headers). A test that uses any of them is marked `db` automatically. **DB tests** (`local_backend/tests/conftest.py`) run the real FastAPI app against a throwaway SQLite database in a temp folder (never your dev or venue DB). Fixtures: `db` (session, rolled back after each test even if the code commits), `client` (TestClient with `get_db` overridden, license check open, no lifespan), `make_user(role=..., perms=...)` (password `password`, PIN `1234`), `login(user)` (auth headers). A test that uses any of them is marked `db` automatically.
@@ -38,6 +40,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 | 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 |
+157
View File
@@ -0,0 +1,157 @@
// Manager suite (Playwright + Edge): the manager on the shared packages (plan step 2.5).
// Starts a backend on a demo-seeded database (:8057, licensing off) and the manager's Vite
// dev server (:5186) proxied to it. Checks login and the platform bootstrap through
// @xenia/api + @xenia/access, the 401 rules (wrong password / wrong PIN stay on screen, an
// ended session logs out), a module turned off, and the manager-approval dialog.
// node manager.mjs
import { spawn } from 'node:child_process'
import { openSync } from 'node:fs'
import path from 'node:path'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, CS, OUT, reporter, sleep } from './lib/env.mjs'
import { killTree, startBackend, waitHttp } from './lib/proc.mjs'
const PORT = 5186
const APP = `http://localhost:${PORT}`
const backend = await startBackend({ port: 8057, siteId: 'test-site-1' })
const log = openSync(path.join(OUT, `vite-${PORT}.log`), 'w')
const vite = spawn('npx', ['vite', '--port', String(PORT), '--strictPort'], {
cwd: path.join(CS, 'manager_dashboard'), shell: process.platform === 'win32', detached: process.platform !== 'win32',
stdio: ['ignore', log, log], env: { ...process.env, XENIA_BACKEND: backend.url },
})
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const r = reporter('manager: login + bootstrap on @xenia/api / @xenia/access')
async function api(method, url, { token, body } = {}) {
const res = await fetch(backend.url + url, {
method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
})
const text = await res.text()
let data = null
try { data = JSON.parse(text) } catch { data = text }
if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`)
return data
}
const loginApi = (username, secret) => api('POST', '/api/auth/login', { body: { username, ...secret } }).then(d => d.access_token)
async function uiLogin(page, password) {
await page.goto(`${APP}/login`)
await page.waitForFunction(() => document.body.innerText.includes('Sign In'), null, { timeout: 60_000 })
const other = page.getByText('Sign in as different account')
if (await other.count()) { await other.click(); await sleep(300) }
const user = page.locator('input:not([type=password])').first()
if (await user.count()) await user.fill('manager')
await page.locator('input[type=password]').fill(password)
await page.getByRole('button', { name: 'Sign In' }).click()
}
try {
await waitHttp(`${APP}/`)
const ctx = await browser.newContext({ viewport: { width: 1400, height: 900 } })
const page = await ctx.newPage()
const errors = []
page.on('pageerror', e => errors.push(e.message))
const bootstraps = []
page.on('request', q => { if (q.url().includes('/api/platform/bootstrap')) bootstraps.push(q.headers().authorization || 'anonymous') })
// ── Wrong password: the message shows, no reload ───────────────────────────
await uiLogin(page, 'wrong-password')
await page.evaluate(() => { window.__noReload = true })
await sleep(1500)
r.check('bootstrap loaded before login (anonymous)', bootstraps[0] === 'anonymous', bootstraps.join(','))
r.check('wrong password: error shown, page not reloaded',
await page.getByText('Wrong username or password').count() > 0 && await page.evaluate(() => window.__noReload === true))
// ── Right password: dashboard, bootstrap again with the session ────────────
await page.locator('input[type=password]').fill('password')
await page.getByRole('button', { name: 'Sign In' }).click()
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 15_000 }).catch(() => {})
await sleep(1500)
r.check('login → /dashboard', new URL(page.url()).pathname === '/dashboard', page.url())
r.check('bootstrap reloaded with the session token', bootstraps.some(b => b.startsWith('Bearer ')), bootstraps.join(','))
r.check('sidebar built from bootstrap permissions (Διαχείριση, Αναφορές)',
await page.getByText('Διαχείριση').count() > 0 && await page.getByText('Αναφορές').count() > 0)
await page.goto(`${APP}/management/products`)
await sleep(1500)
r.check('a PermissionGuard page renders for the manager', await page.getByText('Δεν έχετε πρόσβαση').count() === 0 && (await page.evaluate(() => document.body.innerText.length)) > 200)
// ── Lock screen: a wrong PIN stays locked (no logout), the right one unlocks ─
await page.goto(`${APP}/dashboard`)
await sleep(1500)
await page.locator('header button').filter({ has: page.locator('svg.lucide-lock') }).first().click()
await sleep(600)
for (const d of '0000') { await page.keyboard.type(d); await sleep(120) }
await sleep(1500)
r.check('lock: wrong PIN → "Wrong PIN", still signed in',
await page.getByText('Wrong PIN').count() > 0 && !!(await page.evaluate(() => localStorage.getItem('manager_token'))) && new URL(page.url()).pathname === '/dashboard')
for (const d of '1234') { await page.keyboard.type(d); await sleep(120) }
await sleep(2000)
r.check('lock: right PIN unlocks', await page.getByText('Locked').count() === 0 && new URL(page.url()).pathname === '/dashboard')
// ── A module turned off: /kds shows the "turned off" screen ────────────────
const mgr = await page.evaluate(() => localStorage.getItem('manager_token'))
await api('PUT', '/api/platform/modules/kds', { token: mgr, body: { enabled: false } })
await page.goto(`${APP}/kds`)
await sleep(2000)
r.check('kds off → "feature turned off" screen', await page.locator('.x-empty__title').count() === 1, await page.locator('body').innerText().then(t => t.slice(0, 80)))
await api('PUT', '/api/platform/modules/kds', { token: mgr, body: { enabled: true } })
await page.goto(`${APP}/kds`)
await sleep(2000)
r.check('kds on again → the KDS renders', await page.locator('.x-empty__title').count() === 0)
// ── Session ended elsewhere: the next request logs out ─────────────────────
await page.goto(`${APP}/dashboard`)
await sleep(1500)
await api('POST', '/api/auth/logout', { token: mgr })
await page.getByText('Αναφορές').first().click()
await page.getByText('Σήμερα').first().click()
await page.waitForURL(u => u.pathname === '/login', { timeout: 10_000 }).catch(() => {})
r.check('session ended → back to /login, token cleared',
new URL(page.url()).pathname === '/login' && !(await page.evaluate(() => localStorage.getItem('manager_token'))), page.url())
// ── Manager approval (D-10): a waiter cancels without the key ──────────────
const boss = await loginApi('manager', { password: 'password' })
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
const waiter = await loginApi('demo_maria', { pin: '3302', client: 'waiter' })
await api('POST', '/api/shifts/start', { token: waiter, body: {} }).catch(() => {})
const tables = await api('GET', '/api/tables/', { token: boss })
const table = tables.find(t => !t.open_order_id && !t.current_order_id) || tables[0]
const order = await api('POST', '/api/orders/', { token: waiter, body: { table_id: table.id } })
const w = await (await browser.newContext({ viewport: { width: 1200, height: 900 } })).newPage()
w.on('pageerror', e => errors.push(e.message))
await w.goto(`${APP}/login`)
await w.evaluate(t => { localStorage.setItem('manager_token', t); localStorage.setItem('manager_username', 'demo_maria') }, waiter)
await w.goto(`${APP}/dashboard`)
await sleep(2500)
await w.evaluate(id => {
window.__res = window.__xeniaClient.delete(`/api/orders/${id}`) // cancel the whole order
.then(res => ({ ok: true, status: res.status }), e => ({ ok: false, code: e.xenia?.code, cancelled: !!e.xenia?.overrideCancelled }))
}, order.id)
const dialog = w.getByRole('dialog')
await dialog.waitFor({ timeout: 10_000 }).catch(() => {})
r.check('approval dialog opens for ordering.orders.cancel', await w.getByTestId('override-key').textContent().catch(() => '') === 'ordering.orders.cancel')
const inputs = dialog.locator('input')
await inputs.nth(0).fill('manager')
await inputs.nth(1).fill('0000')
await inputs.nth(1).press('Enter')
await sleep(1500)
r.check('wrong manager PIN: error in the dialog, waiter still signed in',
await dialog.locator('.x-field__error').count() === 1 && !!(await w.evaluate(() => localStorage.getItem('manager_token'))))
await w.screenshot({ path: path.join(OUT, 'manager-approval-wrong-pin.png') })
await inputs.nth(1).fill('1234')
await inputs.nth(1).press('Enter')
const result = await w.evaluate(() => window.__res)
r.check('right PIN: the cancel is retried and succeeds', result.ok === true && result.status === 204, JSON.stringify(result))
r.check('dialog closed', await w.getByRole('dialog').count() === 0)
const audit = await api('GET', '/api/access/overrides', { token: boss })
r.check('the approval is audited', audit[0]?.key === 'ordering.orders.cancel' && audit[0]?.target === `order:${order.id}` && !!audit[0]?.used_at, JSON.stringify(audit[0]))
await w.screenshot({ path: path.join(OUT, 'manager-after-approval.png') })
r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '))
} finally {
await browser.close()
killTree(vite)
await backend.stop()
}
process.exit(r.done() ? 1 : 0)
+3
View File
@@ -10,10 +10,13 @@ const suites = [
['unit: waiter_pwa (node --test)', 'npm', ['test', '--silent'], WAITER], ['unit: waiter_pwa (node --test)', 'npm', ['test', '--silent'], WAITER],
['unit: packages/ui (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/ui'], CS], ['unit: packages/ui (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/ui'], CS],
['unit: packages/i18n (node --test + guard)', 'npm', ['test', '--silent', '-w', '@xenia/i18n'], CS], ['unit: packages/i18n (node --test + guard)', 'npm', ['test', '--silent', '-w', '@xenia/i18n'], CS],
['unit: packages/api (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/api'], CS],
['unit: packages/access (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/access'], CS],
['install.sh', 'node', ['install.mjs'], E2E], ['install.sh', 'node', ['install.mjs'], E2E],
['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E], ['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E],
['browser', 'node', ['browser.mjs'], E2E], ['browser', 'node', ['browser.mjs'], E2E],
['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E], ['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E],
['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E],
] ]
if (!process.argv.includes('--no-android')) suites.push(['android (emulator)', 'node', ['android.mjs'], E2E]) if (!process.argv.includes('--no-android')) suites.push(['android (emulator)', 'node', ['android.mjs'], E2E])
+1
View File
@@ -19,6 +19,7 @@
"@capacitor/core": "8.5.2", "@capacitor/core": "8.5.2",
"@capgo/capacitor-updater": "8.51.25", "@capgo/capacitor-updater": "8.51.25",
"@tanstack/react-query": "^5.100.11", "@tanstack/react-query": "^5.100.11",
"@xenia/api": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.15.1", "axios": "^1.15.1",
"dexie": "^4.4.2", "dexie": "^4.4.2",
+26 -114
View File
@@ -1,40 +1,36 @@
/** /**
* Persistent WebSocket hook — replaces useSSE. * Persistent WebSocket hook — the waiter's live events.
* *
* Protocol: * The connection logic (cursor replay, reconnect backoff 2 s → ×1.5 → 30 s, reconnect when
* 1. Connect to ws[s]://host/api/ws/connect?token=<jwt> * the network comes back) is the shared client in @xenia/api (createLiveClient, plan step
* 2. Send { cursor: <last_seq> } immediately (0 = first connect) * 2.5), lifted from this file without changing behaviour. This hook keeps the waiter's
* 3. Receive replayed missed events, then { type: "ready" } * parts: the URL from the active venue (CS-8) and the cursor in IndexedDB, so it survives
* 4. Live events: { seq, type, data } * page reloads and missed events are replayed on every reconnect.
* 5. Keepalive: server sends { type: "ping" } every 25s
*
* The hook stores `lastSeq` in IndexedDB so it survives page reloads.
* On every clean reconnect, missed events are replayed automatically.
*/ */
import { useCallback, useEffect, useRef } from 'react' import { useCallback, useEffect, useRef } from 'react'
import { createLiveClient } from '@xenia/api'
import db from '../db/posdb' import db from '../db/posdb'
import { wsUrl } from '../config/server' import { wsUrl } from '../config/server'
const INITIAL_RECONNECT_DELAY = 2_000
const MAX_RECONNECT_DELAY = 30_000
const CURSOR_KEY = 'ws_last_seq' const CURSOR_KEY = 'ws_last_seq'
// ── Cursor persistence (IDB) ────────────────────────────────────────────────── // ── Cursor persistence (IDB) ──────────────────────────────────────────────────
async function loadCursor() { const idbCursor = {
async load() {
try { try {
const row = await db.kv?.get(CURSOR_KEY) const row = await db.kv?.get(CURSOR_KEY)
return row?.value ?? 0 return row?.value ?? 0
} catch { } catch {
return 0 return 0
} }
} },
async save(seq) {
async function saveCursor(seq) {
try { try {
await db.kv?.put({ key: CURSOR_KEY, value: seq }) await db.kv?.put({ key: CURSOR_KEY, value: seq })
} catch {} } catch { /* storage unavailable: replay starts from 0 next time */ }
},
} }
// ── Hook ────────────────────────────────────────────────────────────────────── // ── Hook ──────────────────────────────────────────────────────────────────────
@@ -47,112 +43,28 @@ export function useWebSocket({ token, onEvent, onConnect, onDisconnect, enabled
useEffect(() => { onConnectRef.current = onConnect }, [onConnect]) useEffect(() => { onConnectRef.current = onConnect }, [onConnect])
useEffect(() => { onDisconnectRef.current = onDisconnect }, [onDisconnect]) useEffect(() => { onDisconnectRef.current = onDisconnect }, [onDisconnect])
const wsRef = useRef(null) const liveRef = useRef(null)
const reconnectTimer = useRef(null)
const reconnectDelay = useRef(INITIAL_RECONNECT_DELAY)
const unmounted = useRef(false)
const connectRef = useRef(null)
const lastSeq = useRef(0)
useEffect(() => { useEffect(() => {
if (!token || !enabled) return if (!token || !enabled) return
unmounted.current = false const live = createLiveClient({
// Load persisted cursor before first connect
loadCursor().then(seq => {
lastSeq.current = seq
if (!unmounted.current) connectRef.current?.()
})
async function connect() {
if (unmounted.current) return
if (wsRef.current) {
wsRef.current.onclose = null // prevent double-reconnect
wsRef.current.close()
wsRef.current = null
}
// Same host as the page (web) or the active venue's server (native) // Same host as the page (web) or the active venue's server (native)
const url = wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`) url: () => wsUrl(`/api/ws/connect?token=${encodeURIComponent(token)}`),
cursor: idbCursor,
const ws = new WebSocket(url) onEvent: (type, data) => onEventRef.current?.(type, data),
wsRef.current = ws onReady: () => onConnectRef.current?.(),
onDisconnect: () => onDisconnectRef.current?.(),
ws.onopen = () => { })
reconnectDelay.current = INITIAL_RECONNECT_DELAY liveRef.current = live
// Send cursor so server can replay missed events live.start()
ws.send(JSON.stringify({ cursor: lastSeq.current }))
}
ws.onmessage = (e) => {
let msg
try { msg = JSON.parse(e.data) } catch { return }
if (msg.type === 'ping') return // keepalive — no response needed
if (msg.type === 'ready') {
// Replay complete — we're now on the live stream
onConnectRef.current?.()
return
}
// Live or replayed event
if (msg.seq && msg.seq > lastSeq.current) {
lastSeq.current = msg.seq
saveCursor(msg.seq)
}
if (msg.type && msg.data !== undefined) {
onEventRef.current?.(msg.type, msg.data)
}
}
ws.onerror = () => {
// onerror always fires before onclose — let onclose handle reconnect
}
ws.onclose = () => {
wsRef.current = null
onDisconnectRef.current?.()
if (unmounted.current) return
// Schedule next attempt with current delay, then increase for the one after
reconnectTimer.current = setTimeout(() => {
reconnectDelay.current = Math.min(
reconnectDelay.current * 1.5,
MAX_RECONNECT_DELAY,
)
connect()
}, reconnectDelay.current)
}
}
connectRef.current = connect
// When the browser detects network restoration, immediately reset backoff and reconnect.
// This fires as soon as the OS reports connectivity — no need to wait for the
// backed-off timer or for the user to switch tabs.
function onNetworkOnline() {
clearTimeout(reconnectTimer.current)
reconnectDelay.current = INITIAL_RECONNECT_DELAY
connect()
}
window.addEventListener('online', onNetworkOnline)
return () => { return () => {
unmounted.current = true live.stop()
clearTimeout(reconnectTimer.current) if (liveRef.current === live) liveRef.current = null
window.removeEventListener('online', onNetworkOnline)
if (wsRef.current) {
wsRef.current.onclose = null
wsRef.current.close()
wsRef.current = null
}
} }
}, [token, enabled]) }, [token, enabled])
const reconnect = useCallback(() => { const reconnect = useCallback(() => {
clearTimeout(reconnectTimer.current) liveRef.current?.reconnect()
reconnectDelay.current = INITIAL_RECONNECT_DELAY
connectRef.current?.()
}, []) }, [])
return { reconnect } return { reconnect }