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
+12 -1
View File
@@ -3,9 +3,20 @@
"version": "0.0.0",
"private": true,
"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",
"exports": {
".": "./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).
// Imported from source by Vite (no build step). Filled in by its plan step.
export {}
// @xenia/access — what this venue has turned on and what the signed-in user may do,
// for every frontend (plan step 2.5, APPS_PLATFORM §5, §6, §9). React; imported from source.
//
// <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",
"private": true,
"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",
"exports": {
".": "./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).
// Imported from source by Vite (no build step). Filled in by its plan step.
export {}
// @xenia/api — talking to the local backend, for every frontend (plan step 2.5,
// APPS_PLATFORM §9). Plain JavaScript (no React); imported from source by Vite.
//
// 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": "Ειδοποιήσεις",
"backspace": "Διαγραφή",
"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",
"backspace": "Delete",
"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).
// 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.
import elCommon from '../locales/el/common.json'
import elDev from '../locales/el/dev.json'
import elErrors from '../locales/el/errors.json'
import enCommon from '../locales/en/common.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 = {
en: { common: enCommon, dev: enDev },
el: { common: elCommon, dev: elDev },
en: { common: enCommon, errors: enErrors, dev: enDev },
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'])
})
}