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
@@ -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>
)
}