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
+4 -1
View File
@@ -17,7 +17,9 @@ npm test # server rediscovery scan
cd ..
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.
@@ -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 |
| `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 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 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 |
+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: 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/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],
['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E],
['browser', 'node', ['browser.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])