feat(manager): Devices page — pair by code, app, name, sign-in mode, link, change app, remove

Platform-v2 step 2.6d:
- /devices (core.devices.manage, sidebar): devices from /api/devices with
  status (online / last seen / waiting for the device / app turned off /
  removed), app, sign-in mode (own or venue default), linked device; usage per
  device app against the license limit (devices)
- pair dialog: code as typed (normalized), app (only apps that are on, "all in
  use" when the limit is reached), name, sign-in mode for apps with a choice,
  optional linked device; license.limit_reached explained with the app's limit
- edit (name, sign-in mode, link), change app (signs out whoever is on it),
  remove with confirm (the device goes back to pairing), show removed
- manager_dashboard gets node --test (tests/platform.test.mjs: module states,
  dependents, device status/usage/room/links), added to run-all
- e2e manager.mjs: 54 checks (+ wrong code, normalized code, pair, the device
  picks up its token, online, rename, change app, remove → device.revoked)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 23:22:43 +02:00
co-authored by Claude Opus 5.5
parent 1f28016122
commit cc00ec39c7
12 changed files with 638 additions and 5 deletions
+1 -1
View File
@@ -148,7 +148,7 @@ The native plugins (`@capacitor/*`, `@capgo/*`) are pinned to **exact** versions
## Testing
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|i18n|api|access>` 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|@xenia/i18n|@xenia/api|@xenia/access|manager-dashboard>` 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.
**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.
+2 -1
View File
@@ -6,7 +6,8 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
"preview": "vite preview",
"test": "node --test \"tests/*.test.mjs\""
},
"dependencies": {
"@tanstack/react-query": "^5.62.0",
+2
View File
@@ -53,6 +53,7 @@ import MiscPage from './pages/reports/MiscPage'
// Other
import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage'
import LicensePage from './pages/platform/LicensePage'
import DevicesPage from './pages/platform/DevicesPage'
import PhonePage from './pages/PhonePage'
import SettingsPage from './pages/Settings/SettingsPage'
import NotesPage from './pages/NotesPage'
@@ -181,6 +182,7 @@ export default function App() {
<Route path="apps" element={<AppsPage />} />
<Route path="integrations" element={<IntegrationsPage />} />
<Route path="license" element={<LicensePage />} />
<Route path="devices" element={<DevicesPage />} />
<Route path="apps/phone" element={<PhonePage />} />
<Route path="settings" element={<SettingsPage />} />
<Route path="notes" element={<NotesPage />} />
@@ -0,0 +1,327 @@
// Devices page (plan step 2.6d, APPS_PLATFORM D-8, §6.3): screens and terminals paired
// with the venue, each running one app. Backend: /api/devices (step 1.8, core.devices.manage).
// - Pair: the device shows a 6-character code (POST /api/devices/pair-request on its side);
// the manager enters it here with the app, a name, how staff sign in on it and an optional
// linked device → POST /api/devices. The license limit per app is shown and enforced
// (license.limit_reached).
// - Edit (name, sign-in mode, link) → PATCH; change app → POST /reassign (signs out whoever
// is on it); remove → POST /revoke (the device goes back to its pairing screen).
// Per-app settings (e.g. a KDS's prep zone) arrive with the apps themselves in phase 3.
import { useCallback, useEffect, useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { MonitorSmartphone, Plus } from 'lucide-react'
import { errorMessage, parseError } from '@xenia/api'
import { useTranslation, useFormat } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from './devicesLogic'
const STATUS_TONE = {
online: 'bg-success-soft text-success-ink',
offline: 'bg-surface-2 text-ink-2',
waiting: 'bg-info-soft text-info-ink',
app_off: 'bg-warning-soft text-warning-ink',
removed: 'bg-surface-2 text-ink-3',
}
export default function DevicesPage() {
const { t } = useTranslation('manager')
const f = useFormat()
const [devices, setDevices] = useState(null)
const [modules, setModules] = useState(null)
const [showRemoved, setShowRemoved] = useState(false)
const [error, setError] = useState(null)
const [dialog, setDialog] = useState(null) // { kind: 'pair' | 'edit' | 'app' | 'remove', device? }
const load = useCallback(async () => {
try {
const [d, m] = await Promise.all([
client.get('/api/devices', { params: { include_revoked: showRemoved } }),
client.get('/api/platform/modules'),
])
setDevices(d.data)
setModules(m.data.modules)
setError(null)
} catch (err) {
setError(errorMessage(err, t))
}
}, [showRemoved, t])
useEffect(() => { load() }, [load])
const apps = useMemo(() => (modules || []).filter(m => m.device_app), [modules])
const appOn = key => !!apps.find(a => a.key === key)?.effective
const usage = useMemo(() => (devices && modules ? deviceUsage(devices, modules) : {}), [devices, modules])
const appName = key => t(`modules:${key}.name`, { defaultValue: key })
const limitLabel = key => t(`modules:${key}.limits.devices`, { defaultValue: appName(key) })
const byId = id => devices?.find(d => d.id === id)
/** A refusal for one more device of `app`: say it with the app's own words. */
const explain = useCallback(err => {
const x = parseError(err)
if (x.code === 'license.limit_reached') return t('devices.limitReached', { label: limitLabel(x.params.module), max: x.params.max })
return errorMessage(err, t)
}, [t]) // eslint-disable-line react-hooks/exhaustive-deps
async function act(fn, okText) {
try {
await fn()
setDialog(null)
if (okText) toast.success(okText)
await load()
return null
} catch (err) {
return explain(err)
}
}
if (error) return <div className="p-8"><EmptyState title={error} action={<Button variant="secondary" onClick={load}>{t('common:actions.retry')}</Button>} /></div>
if (!devices || !modules) return <div className="p-8 flex justify-center"><Spinner /></div>
const live = devices.filter(d => !d.revoked_at)
const signInLabel = d => {
const modes = apps.find(a => a.key === d.app_key)?.device_app?.login_modes || []
if (d.login_mode || modes.length < 2) return t(`devices.signIn.${d.effective_login_mode}`) // its own choice, or the only one the app has
return t('devices.signIn.default', { mode: t(`devices.signIn.${d.effective_login_mode}`) })
}
const statusText = d => {
const s = deviceStatus(d, { appOn: appOn(d.app_key) })
if (s === 'offline') return d.last_seen_at ? t('devices.status.offline', { when: f.formatRelative(d.last_seen_at) }) : t('devices.status.offlineNever')
if (s === 'removed') return t('devices.status.removed', { when: f.formatRelative(d.revoked_at) })
return t(`devices.status.${s}`)
}
return (
<div className="p-6 lg:p-8 max-w-6xl grid gap-6">
<div className="flex flex-wrap items-start gap-4 justify-between">
<p className="text-body text-ink-2 max-w-2xl">{t('devices.intro')}</p>
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'pair' })}>{t('devices.pair')}</Button>
</div>
<div className="flex flex-wrap gap-2" data-testid="device-usage">
{apps.filter(a => a.effective).map(a => {
const u = usage[a.key] || { used: 0, max: null }
return (
<span key={a.key} className={`rounded-full px-3 py-1 text-label ${u.max != null && u.used >= u.max ? 'bg-warning-soft text-warning-ink' : 'bg-surface-2 text-ink-2'}`}>
{u.max == null
? t('devices.usageUnlimited', { label: limitLabel(a.key), used: u.used })
: t('devices.usage', { label: limitLabel(a.key), used: u.used, max: u.max })}
</span>
)
})}
</div>
{devices.length === 0
? <EmptyState icon={<MonitorSmartphone />} title={t('devices.empty')} description={t('devices.emptyBody')} />
: (
<div className="bg-surface border border-line rounded-card shadow-raised overflow-x-auto">
<table className="w-full text-body" data-testid="devices-table">
<thead>
<tr className="text-left text-label text-ink-3 border-b border-line">
{['device', 'app', 'status', 'signIn', 'linked', 'actions'].map(c => <th key={c} className="px-4 py-2.5 font-medium">{t(`devices.columns.${c}`)}</th>)}
</tr>
</thead>
<tbody>
{devices.map(d => {
const s = deviceStatus(d, { appOn: appOn(d.app_key) })
return (
<tr key={d.id} className="border-b border-line last:border-0" data-testid={`device-${d.id}`} data-status={s}>
<td className="px-4 py-3">
<div className="font-medium text-ink">{d.name}</div>
<div className="text-caption text-ink-3">{f.formatDate(d.paired_at, 'dateMedium')}</div>
</td>
<td className="px-4 py-3 text-ink-2">{appName(d.app_key)}</td>
<td className="px-4 py-3"><span className={`rounded-full px-2.5 py-0.5 text-caption font-medium ${STATUS_TONE[s]}`}>{statusText(d)}</span></td>
<td className="px-4 py-3 text-ink-2">{d.revoked_at ? '—' : signInLabel(d)}</td>
<td className="px-4 py-3 text-ink-2">{byId(d.linked_device_id)?.name || '—'}</td>
<td className="px-4 py-3 whitespace-nowrap text-right">
{!d.revoked_at && (
<div className="inline-flex gap-1">
<Button size="sm" variant="ghost" onClick={() => setDialog({ kind: 'edit', device: d })}>{t('devices.actions.edit')}</Button>
<Button size="sm" variant="ghost" onClick={() => setDialog({ kind: 'app', device: d })}>{t('devices.actions.changeApp')}</Button>
<Button size="sm" variant="ghost" className="text-danger-ink" onClick={() => setDialog({ kind: 'remove', device: d })}>{t('devices.actions.remove')}</Button>
</div>
)}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
<label className="inline-flex items-center gap-2 text-label text-ink-2 cursor-pointer w-fit">
<input type="checkbox" checked={showRemoved} onChange={e => setShowRemoved(e.target.checked)} />
{t('devices.showRemoved')}
</label>
{dialog?.kind === 'pair' && (
<PairDialog apps={apps} usage={usage} devices={live} appName={appName} limitLabel={limitLabel}
onClose={() => setDialog(null)}
onPair={body => act(() => client.post('/api/devices', body), t('devices.paired', { name: body.name }))} />
)}
{dialog?.kind === 'edit' && (
<EditDialog device={dialog.device} apps={apps} devices={live}
onClose={() => setDialog(null)}
onSave={body => act(() => client.patch(`/api/devices/${dialog.device.id}`, body), t('devices.saved'))} />
)}
{dialog?.kind === 'app' && (
<ChangeAppDialog device={dialog.device} apps={apps} usage={usage} appName={appName}
onClose={() => setDialog(null)}
onSave={appKey => act(() => client.post(`/api/devices/${dialog.device.id}/reassign`, { app_key: appKey }), t('devices.saved'))} />
)}
{dialog?.kind === 'remove' && (
<RemoveDialog device={dialog.device} onClose={() => setDialog(null)}
onRemove={() => act(() => client.post(`/api/devices/${dialog.device.id}/revoke`))} />
)}
</div>
)
}
function loginModeOptions(app, t) {
const modes = app?.device_app?.login_modes || []
if (modes.length < 2) return null
return [{ value: '', label: t('devices.signIn.defaultPlain') }, ...modes.map(m => ({ value: m, label: t(`devices.signIn.${m}`) }))]
}
function useSubmit(fn) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const run = async (...args) => {
setBusy(true)
setError('')
const err = await fn(...args)
setBusy(false)
if (err) setError(err)
}
return { busy, error, run }
}
function PairDialog({ apps, usage, devices, appName, limitLabel, onClose, onPair }) {
const { t } = useTranslation('manager')
const usable = apps.filter(a => a.effective)
const [code, setCode] = useState('')
const [appKey, setAppKey] = useState(usable.find(a => hasRoom(usage, a.key))?.key || usable[0]?.key || '')
const [name, setName] = useState('')
const [mode, setMode] = useState('')
const [link, setLink] = useState('')
const { busy, error, run } = useSubmit(onPair)
const app = apps.find(a => a.key === appKey)
const full = appKey && !hasRoom(usage, appKey)
const modes = loginModeOptions(app, t)
const ready = code.length === 6 && appKey && name.trim() && !full
const submit = e => {
e.preventDefault()
if (!ready || busy) return
run({ code, app_key: appKey, name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null })
}
return (
<Dialog open onClose={onClose} title={t('devices.pair')}
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button type="submit" form="pair-form" loading={busy} disabled={!ready}>{t('devices.pair')}</Button></>}>
{usable.length === 0
? <p>{t('devices.form.noApps')}</p>
: (
<form id="pair-form" onSubmit={submit} className="grid gap-4">
<Field label={t('devices.form.code')} hint={t('devices.form.codeHint')}>
<Input value={code} onChange={e => setCode(normalizeCode(e.target.value))} autoComplete="off" spellCheck={false}
className="font-mono tracking-[0.3em] text-center uppercase" autoFocus />
</Field>
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: limitLabel(appKey), max: usage[appKey].max }) : undefined}>
<Select value={appKey} onChange={e => { setAppKey(e.target.value); setMode('') }}
options={usable.map(a => ({ value: a.key, label: appName(a.key) }))} />
</Field>
<Field label={t('devices.form.name')}>
<Input value={name} onChange={e => setName(e.target.value)} placeholder={t('devices.form.namePlaceholder')} maxLength={60} />
</Field>
{modes && (
<Field label={t('devices.form.signIn')}>
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
</Field>
)}
{devices.length > 0 && (
<Field label={t('devices.form.link')} hint={t('devices.form.linkHint')}>
<Select value={link} onChange={e => setLink(e.target.value)}
options={[{ value: '', label: t('devices.form.noLink') }, ...linkTargets(devices).map(d => ({ value: String(d.id), label: d.name }))]} />
</Field>
)}
{error && <p className="text-label text-danger-ink" role="alert" data-testid="pair-error">{error}</p>}
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
</form>
)}
</Dialog>
)
}
function EditDialog({ device, apps, devices, onClose, onSave }) {
const { t } = useTranslation('manager')
const [name, setName] = useState(device.name)
const [mode, setMode] = useState(device.login_mode || '')
const [link, setLink] = useState(device.linked_device_id ? String(device.linked_device_id) : '')
const { busy, error, run } = useSubmit(onSave)
const modes = loginModeOptions(apps.find(a => a.key === device.app_key), t)
const targets = linkTargets(devices, device.id)
const submit = e => {
e.preventDefault()
if (!name.trim() || busy) return
run({ name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null })
}
return (
<Dialog open onClose={onClose} title={device.name}
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button type="submit" form="edit-form" loading={busy}>{t('devices.actions.save')}</Button></>}>
<form id="edit-form" onSubmit={submit} className="grid gap-4">
<Field label={t('devices.form.name')}>
<Input value={name} onChange={e => setName(e.target.value)} maxLength={60} />
</Field>
{modes && (
<Field label={t('devices.form.signIn')}>
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
</Field>
)}
{targets.length > 0 && (
<Field label={t('devices.form.link')} hint={t('devices.form.linkHint')}>
<Select value={link} onChange={e => setLink(e.target.value)}
options={[{ value: '', label: t('devices.form.noLink') }, ...targets.map(d => ({ value: String(d.id), label: d.name }))]} />
</Field>
)}
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
</form>
</Dialog>
)
}
function ChangeAppDialog({ device, apps, usage, appName, onClose, onSave }) {
const { t } = useTranslation('manager')
const usable = apps.filter(a => a.effective)
const [appKey, setAppKey] = useState(device.app_key)
const { busy, error, run } = useSubmit(onSave)
const full = appKey !== device.app_key && !hasRoom(usage, appKey)
return (
<Dialog open onClose={onClose} title={`${t('devices.actions.changeApp')}: ${device.name}`} description={t('devices.changeAppBody')}
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button loading={busy} disabled={appKey === device.app_key || full} onClick={() => run(appKey)}>{t('devices.actions.save')}</Button></>}>
<div className="grid gap-4">
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: t(`modules:${appKey}.limits.devices`), max: usage[appKey].max }) : undefined}>
<Select value={appKey} onChange={e => setAppKey(e.target.value)} options={usable.map(a => ({ value: a.key, label: appName(a.key) }))} />
</Field>
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
</div>
</Dialog>
)
}
function RemoveDialog({ device, onClose, onRemove }) {
const { t } = useTranslation('manager')
const { busy, error, run } = useSubmit(onRemove)
return (
<Dialog open size="sm" onClose={onClose} title={t('devices.removeTitle', { name: device.name })} description={t('devices.removeBody')}
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button variant="danger" loading={busy} onClick={() => run()}>{t('devices.actions.remove')}</Button></>}>
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
</Dialog>
)
}
@@ -0,0 +1,55 @@
// Pure helpers for the Devices page (plan step 2.6d). Unit-tested in manager_dashboard/tests.
/** Seen within this long = "Online" (the backend writes last_seen_at at most once a minute). */
export const ONLINE_WITHIN_MS = 3 * 60 * 1000
/**
* A device's status for the list:
* removed revoked
* waiting paired here, but the device hasn't picked up its token yet
* app_off its app is turned off or not licensed (the device shows "app disabled")
* online seen in the last 3 minutes
* offline seen before that (or never since pairing)
*/
export function deviceStatus(d, { appOn = true, now = Date.now() } = {}) {
if (d.revoked_at) return 'removed'
if (!d.claimed) return 'waiting'
if (!appOn) return 'app_off'
const seen = d.last_seen_at ? Date.parse(d.last_seen_at) : NaN
return Number.isFinite(seen) && now - seen <= ONLINE_WITHIN_MS ? 'online' : 'offline'
}
/** Pairing codes are typed by people: upper-case, no spaces or dashes, at most 6 characters. */
export function normalizeCode(input) {
return String(input || '').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 6)
}
/**
* How many devices of each app are paired (not removed), and the license limit:
* { kds: { used: 1, max: 2 }, signage: { used: 0, max: null } } (max null = unlimited)
* `modules` = GET /api/platform/modules → modules.
*/
export function deviceUsage(devices, modules) {
const out = {}
for (const m of modules) {
if (!m.device_app) continue
const limit = m.limits.find(l => l.key === 'devices')
out[m.key] = { used: 0, max: limit ? limit.value ?? null : null }
}
for (const d of devices) {
if (!d.revoked_at && out[d.app_key]) out[d.app_key].used++
}
return out
}
/** Is there room for one more device of this app? (when moving a device, it doesn't count against itself) */
export function hasRoom(usage, appKey, { moving = false } = {}) {
const u = usage[appKey]
if (!u || u.max == null) return true
return u.used - (moving ? 1 : 0) < u.max
}
/** Devices another device may link to: not itself, not removed. */
export function linkTargets(devices, selfId = null) {
return devices.filter(d => !d.revoked_at && d.id !== selfId)
}
+2 -1
View File
@@ -16,7 +16,7 @@ import {
BookUser, Users, Receipt, CreditCard,
Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes,
BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText,
AppWindow, Settings, CookingPot, StickyNote, Percent, Plug, BadgeCheck,
AppWindow, Settings, CookingPot, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone,
} from 'lucide-react'
const DASH = 'core.dashboard.access'
@@ -96,6 +96,7 @@ export const NAV = [
export const NAV_BOTTOM = [
{ to: '/apps', icon: AppWindow, label: 'nav.apps', module: 'core', perm: DASH },
{ to: '/integrations', icon: Plug, label: 'nav.integrations', module: 'core', perm: DASH },
{ to: '/devices', icon: MonitorSmartphone, label: 'nav.devices', module: 'core', perm: 'core.devices.manage' },
{ to: '/license', icon: BadgeCheck, label: 'nav.license', module: 'core', perm: DASH },
{ to: '/settings', icon: Settings, label: 'nav.settings', module: 'core', perm: 'core.settings.manage' },
]
+64
View File
@@ -0,0 +1,64 @@
// Pure logic of the platform pages (plan steps 2.6c, 2.6d).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from '../src/pages/platform/devicesLogic.js'
import { moduleState, stoppedBy } from '../src/pages/platform/modulesLogic.js'
const mod = (key, extra = {}) => ({ key, depends: [], can_disable: true, entitled: true, enabled: true, effective: true, limits: [], device_app: null, ...extra })
test('module state', () => {
assert.equal(moduleState(mod('core', { can_disable: false })), 'always')
assert.equal(moduleState(mod('kds', { entitled: false, effective: false })), 'not_licensed')
assert.equal(moduleState(mod('kds')), 'on')
assert.equal(moduleState(mod('kds', { effective: false })), 'waiting')
assert.equal(moduleState(mod('kds', { enabled: false, effective: false })), 'off')
})
test('turning a module off stops what depends on it, directly or not (only those that are on)', () => {
const modules = [
mod('catalog'), mod('ordering', { depends: ['catalog'] }), mod('kds', { depends: ['ordering'] }),
mod('pos_counter', { depends: ['ordering'] }), mod('customer_display', { depends: ['pos_counter'] }),
mod('pricing', { depends: ['ordering'], effective: false }), mod('notes'),
]
assert.deepEqual(stoppedBy('ordering', modules).map(m => m.key).sort(), ['customer_display', 'kds', 'pos_counter'])
assert.deepEqual(stoppedBy('notes', modules), [])
})
test('device status', () => {
const now = Date.parse('2026-11-13T12:00:00Z')
const d = { claimed: true, revoked_at: null, last_seen_at: '2026-11-13T11:58:30Z' }
assert.equal(deviceStatus(d, { now }), 'online')
assert.equal(deviceStatus({ ...d, last_seen_at: '2026-11-13T11:50:00Z' }, { now }), 'offline')
assert.equal(deviceStatus({ ...d, last_seen_at: null }, { now }), 'offline')
assert.equal(deviceStatus({ ...d, claimed: false }, { now }), 'waiting')
assert.equal(deviceStatus(d, { now, appOn: false }), 'app_off')
assert.equal(deviceStatus({ ...d, revoked_at: '2026-11-13T11:00:00Z' }, { now }), 'removed')
})
test('pairing codes as typed', () => {
assert.equal(normalizeCode(' ab-c d2e '), 'ABCD2E')
assert.equal(normalizeCode('k7m9pq2x'), 'K7M9PQ')
assert.equal(normalizeCode(null), '')
})
test('device usage against the license limit', () => {
const modules = [
mod('kds', { device_app: {}, limits: [{ key: 'devices', value: 2 }] }),
mod('signage', { device_app: {}, limits: [{ key: 'devices', value: null }] }),
mod('notes'),
]
const devices = [
{ app_key: 'kds', revoked_at: null }, { app_key: 'kds', revoked_at: '2026-01-01T00:00:00Z' },
{ app_key: 'kds', revoked_at: null }, { app_key: 'signage', revoked_at: null },
]
const usage = deviceUsage(devices, modules)
assert.deepEqual(usage, { kds: { used: 2, max: 2 }, signage: { used: 1, max: null } })
assert.equal(hasRoom(usage, 'kds'), false)
assert.equal(hasRoom(usage, 'kds', { moving: true }), true)
assert.equal(hasRoom(usage, 'signage'), true)
})
test('link targets: not itself, not removed', () => {
const devices = [{ id: 1, revoked_at: null }, { id: 2, revoked_at: 'x' }, { id: 3, revoked_at: null }]
assert.deepEqual(linkTargets(devices, 1).map(d => d.id), [3])
})
+61 -1
View File
@@ -42,7 +42,8 @@
"kds": "Οθόνη κουζίνας",
"soon": "σύντομα",
"integrations": "Συνδέσεις",
"license": "Άδεια"
"license": "Άδεια",
"devices": "Συσκευές"
},
"profile": {
"edit": "Επεξεργασία προφίλ",
@@ -127,5 +128,64 @@
"dev": "Ανάπτυξη",
"notIncluded": "Δεν περιλαμβάνεται",
"limits": "Όρια"
},
"devices": {
"intro": "Οθόνες και τερματικά που τρέχουν από μία εφαρμογή: οθόνες κουζίνας, ταμεία πάγκου, οθόνες πελάτη, σήμανση, tablet μενού. Τα κινητά του προσωπικού δεν είναι συσκευές· συνδέονται με τον λογαριασμό τους.",
"pair": "Σύζευξη συσκευής",
"empty": "Δεν υπάρχουν συσκευές ακόμα",
"emptyBody": "Ανοίξτε την εφαρμογή στην οθόνη που θέλετε: δείχνει έναν κωδικό 6 χαρακτήρων. Μετά πατήστε εδώ «Σύζευξη συσκευής».",
"showRemoved": "Εμφάνιση συσκευών που αφαιρέθηκαν",
"usage": "{{label}}: {{used}} από {{max}}",
"usageUnlimited": "{{label}}: {{used}}",
"columns": {
"device": "Συσκευή",
"app": "Εφαρμογή",
"status": "Κατάσταση",
"signIn": "Σύνδεση",
"linked": "Συνδεδεμένη με",
"actions": ""
},
"status": {
"online": "Σε σύνδεση",
"offline": "Τελευταία φορά {{when}}",
"offlineNever": "Δεν έχει εμφανιστεί ακόμα",
"waiting": "Περιμένει να συνδεθεί η συσκευή",
"app_off": "Η εφαρμογή είναι κλειστή",
"removed": "Αφαιρέθηκε {{when}}"
},
"signIn": {
"default": "Προεπιλογή καταστήματος ({{mode}})",
"pin": "PIN",
"password": "Κωδικός",
"tap": "Επιλογή ονόματος",
"none": "Χωρίς σύνδεση",
"defaultPlain": "Προεπιλογή καταστήματος"
},
"form": {
"code": "Κωδικός που δείχνει η συσκευή",
"codeHint": "6 χαρακτήρες, γράμματα και αριθμοί",
"app": "Εφαρμογή",
"name": "Όνομα",
"namePlaceholder": "π.χ. Κουζίνα, Μπαρ, Ταμείο 1",
"signIn": "Πώς συνδέεται το προσωπικό",
"link": "Συνδεδεμένη συσκευή",
"noLink": "Καμία",
"linkHint": "Για παράδειγμα μια οθόνη πελάτη που δείχνει την παραγγελία ενός ταμείου πάγκου.",
"full": "{{label}}: η άδεια επιτρέπει {{max}} και χρησιμοποιούνται όλα. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια.",
"noApps": "Καμία εφαρμογή συσκευών δεν είναι ενεργή. Ενεργοποιήστε μία πρώτα από τις Εφαρμογές."
},
"actions": {
"rename": "Μετονομασία",
"changeApp": "Αλλαγή εφαρμογής",
"remove": "Αφαίρεση",
"save": "Αποθήκευση",
"edit": "Επεξεργασία"
},
"paired": "Η συσκευή {{name}} συνδέθηκε. Ξεκινά σε λίγα δευτερόλεπτα.",
"saved": "Αποθηκεύτηκε",
"removeTitle": "Αφαίρεση: {{name}};",
"removeBody": "Σταματά αμέσως και δείχνει την οθόνη σύζευξης. Για να ξαναχρησιμοποιηθεί, κάντε ξανά σύζευξη.",
"changeAppBody": "Όποιος είναι συνδεδεμένος σε αυτή αποσυνδέεται.",
"limitReached": "{{label}}: η άδεια επιτρέπει {{max}}. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια."
}
}
+61 -1
View File
@@ -42,7 +42,8 @@
"kds": "Kitchen display",
"soon": "soon",
"integrations": "Integrations",
"license": "License"
"license": "License",
"devices": "Devices"
},
"profile": {
"edit": "Edit profile",
@@ -127,5 +128,64 @@
"dev": "Development",
"notIncluded": "Not included",
"limits": "Limits"
},
"devices": {
"intro": "Screens and terminals that run one app each: kitchen displays, counter POS, customer displays, signage, menu tablets. Phones of staff are not devices; they sign in as themselves.",
"pair": "Pair a device",
"empty": "No devices yet",
"emptyBody": "Open the app on the screen you want to use: it shows a 6-character code. Then choose \"Pair a device\" here.",
"showRemoved": "Show removed devices",
"usage": "{{label}}: {{used}} of {{max}}",
"usageUnlimited": "{{label}}: {{used}}",
"columns": {
"device": "Device",
"app": "App",
"status": "Status",
"signIn": "Sign-in",
"linked": "Linked to",
"actions": ""
},
"status": {
"online": "Online",
"offline": "Last seen {{when}}",
"offlineNever": "Not seen yet",
"waiting": "Waiting for the device to connect",
"app_off": "App turned off",
"removed": "Removed {{when}}"
},
"signIn": {
"default": "Venue default ({{mode}})",
"pin": "PIN",
"password": "Password",
"tap": "Tap your name",
"none": "No sign-in",
"defaultPlain": "Venue default"
},
"form": {
"code": "Code shown on the device",
"codeHint": "6 characters, letters and digits",
"app": "App to run",
"name": "Name",
"namePlaceholder": "e.g. Kitchen, Bar, Counter 1",
"signIn": "How staff sign in",
"link": "Linked device",
"noLink": "None",
"linkHint": "For example a customer display that shows a counter POS's order.",
"full": "{{label}}: the license allows {{max}}, all in use. Remove one or ask for a bigger license.",
"noApps": "No device app is turned on. Turn one on in Apps first."
},
"actions": {
"rename": "Rename",
"changeApp": "Change app",
"remove": "Remove",
"save": "Save",
"edit": "Edit"
},
"paired": "{{name}} is paired. It starts in a few seconds.",
"saved": "Saved",
"removeTitle": "Remove {{name}}?",
"removeBody": "It stops at once and shows the pairing screen. To use it again, pair it again.",
"changeAppBody": "Whoever is signed in on it is signed out.",
"limitReached": "{{label}}: the license allows {{max}}. Remove one or ask for a bigger license."
}
}
+1
View File
@@ -20,6 +20,7 @@ npm test -w @xenia/ui # PIN rules + WCAG contrast of every to
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
npm test -w manager-dashboard # platform pages' logic: module states, what stops with a module, device status/usage/limits
```
**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.
+61
View File
@@ -35,6 +35,15 @@ async function api(method, url, { token, body } = {}) {
if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`)
return data
}
// A device's side of pairing (what the terminal app will do in phase 3)
async function deviceRequestsPairing() {
return api('POST', '/api/devices/pair-request')
}
async function devicePicksUpToken(req) {
const res = await fetch(`${backend.url}/api/devices/pair-request/${req.code}`, { headers: { 'X-Xenia-Pair-Secret': req.secret } })
return (await res.json()).device_token
}
const asDevice = (token, url) => fetch(`${backend.url}${url}`, { headers: { 'X-Xenia-Device': token } })
const loginApi = (username, secret) => api('POST', '/api/auth/login', { body: { username, ...secret } }).then(d => d.access_token)
async function uiLogin(page, password) {
@@ -145,6 +154,58 @@ try {
await card('notes').waitFor()
await page.screenshot({ path: path.join(OUT, 'manager-apps.png'), fullPage: true })
// ── 2.6d: Devices: pair by code, edit, change app, remove ──────────────────
await page.goto(`${APP}/devices`)
await page.getByTestId('device-usage').waitFor({ timeout: 15_000 })
r.check('devices: empty state before any pairing', await page.getByText('No devices yet').count() === 1)
const dlg = page.getByRole('dialog')
await page.getByRole('button', { name: 'Pair a device' }).first().click()
await dlg.getByLabel('Code shown on the device').fill('zz-zz-zz')
await dlg.getByLabel('App to run').selectOption('kds')
await dlg.getByLabel('Name').fill('Kitchen')
await dlg.getByRole('button', { name: 'Pair a device' }).click()
await page.getByTestId('pair-error').waitFor({ timeout: 5000 }).catch(() => {})
r.check('devices: a wrong code is refused with a message', (await page.getByTestId('pair-error').textContent().catch(() => '')).includes('pairing code is wrong'))
const req = await deviceRequestsPairing()
const typed = `${req.code.slice(0, 3).toLowerCase()}-${req.code.slice(3).toLowerCase()}`
await dlg.getByLabel('Code shown on the device').fill(typed)
r.check('devices: the code is normalized as typed (lower case, dash)', await dlg.getByLabel('Code shown on the device').inputValue() === req.code)
await dlg.getByLabel('How staff sign in').selectOption('pin')
await dlg.getByRole('button', { name: 'Pair a device' }).click()
await page.waitForFunction(() => document.querySelectorAll('[data-testid^="device-"][data-status]').length === 1, null, { timeout: 8000 }).catch(() => {})
const row = page.locator('[data-testid^="device-"][data-status]').first()
r.check('devices: paired → listed as "waiting for the device"', await row.getAttribute('data-status') === 'waiting' && (await row.textContent()).includes('Kitchen'))
const deviceToken = await devicePicksUpToken(req)
const me = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
r.check('devices: the device got its token and runs the kitchen display', me.app_key === 'kds' && me.name === 'Kitchen' && me.login_mode === 'pin', JSON.stringify(me))
await page.reload()
await row.waitFor({ timeout: 10_000 })
r.check('devices: after it connected → "Online", sign-in PIN', await row.getAttribute('data-status') === 'online' && (await row.textContent()).includes('PIN'))
r.check('devices: usage shows kitchen screens in use', (await page.getByTestId('device-usage').textContent()).includes('Kitchen screens: 1'))
await row.getByRole('button', { name: 'Edit' }).click()
await dlg.getByLabel('Name').fill('Kitchen 1')
await dlg.getByRole('button', { name: 'Save' }).click()
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Kitchen 1'), null, { timeout: 8000 }).catch(() => {})
r.check('devices: renamed', (await row.textContent()).includes('Kitchen 1') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).name === 'Kitchen 1')
await row.getByRole('button', { name: 'Change app' }).click()
await dlg.getByLabel('App to run').selectOption('pos_counter')
await dlg.getByRole('button', { name: 'Save' }).click()
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Counter POS'), null, { timeout: 8000 }).catch(() => {})
r.check('devices: app changed to Counter POS (the device follows)', (await row.textContent()).includes('Counter POS') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).app_key === 'pos_counter')
await page.screenshot({ path: path.join(OUT, 'manager-devices.png'), fullPage: true })
await row.getByRole('button', { name: 'Remove' }).click()
await dlg.getByRole('button', { name: 'Remove' }).click()
await page.getByText('No devices yet').waitFor({ timeout: 8000 }).catch(() => {})
const after = await asDevice(deviceToken, '/api/devices/me')
r.check('devices: removed → gone from the list, the device is refused (device.revoked)',
await page.getByText('No devices yet').count() === 1 && after.status === 401 && (await after.json()).error.code === 'device.revoked')
await page.getByLabel('Show removed devices').check()
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status="removed"]'), null, { timeout: 8000 }).catch(() => {})
r.check('devices: "show removed" lists it as removed', await page.locator('[data-status="removed"]').count() === 1)
// ── Lock screen: a wrong PIN stays locked (no logout), the right one unlocks ─
await page.goto(`${APP}/dashboard`)
await sleep(1500)
+1
View File
@@ -12,6 +12,7 @@ const suites = [
['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],
['unit: manager_dashboard (node --test)', 'npm', ['test', '--silent', '-w', 'manager-dashboard'], CS],
['install.sh', 'node', ['install.mjs'], E2E],
['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E],
['browser', 'node', ['browser.mjs'], E2E],