// 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 (3.1a): each app's device_app.config fields are rendered by // DeviceConfigFields in the pair and edit dialogs and sent as `config`. 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 DeviceConfigFields from './DeviceConfigFields' import { configInitial, 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
{t('common:actions.retry')}} />
if (!devices || !modules) return
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 (

{t('devices.intro')}

{apps.filter(a => a.effective).map(a => { const u = usage[a.key] || { used: 0, max: null } return ( = 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 })} ) })}
{devices.length === 0 ? } title={t('devices.empty')} description={t('devices.emptyBody')} /> : (
{['device', 'app', 'status', 'signIn', 'linked', 'actions'].map(c => )} {devices.map(d => { const s = deviceStatus(d, { appOn: appOn(d.app_key) }) return ( ) })}
{t(`devices.columns.${c}`)}
{d.name}
{f.formatDate(d.paired_at, 'dateMedium')}
{appName(d.app_key)} {statusText(d)} {d.revoked_at ? '—' : signInLabel(d)} {byId(d.linked_device_id)?.name || '—'} {!d.revoked_at && (
)}
)} {dialog?.kind === 'pair' && ( setDialog(null)} onPair={body => act(() => client.post('/api/devices', body), t('devices.paired', { name: body.name }))} /> )} {dialog?.kind === 'edit' && ( setDialog(null)} onSave={body => act(() => client.patch(`/api/devices/${dialog.device.id}`, body), t('devices.saved'))} /> )} {dialog?.kind === 'app' && ( setDialog(null)} onSave={appKey => act(() => client.post(`/api/devices/${dialog.device.id}/reassign`, { app_key: appKey }), t('devices.saved'))} /> )} {dialog?.kind === 'remove' && ( setDialog(null)} onRemove={() => act(() => client.post(`/api/devices/${dialog.device.id}/revoke`))} /> )}
) } 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 app = apps.find(a => a.key === appKey) const fields = app?.device_app?.config || [] const [config, setConfig] = useState(() => configInitial(fields)) const { busy, error, run } = useSubmit(onPair) 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, config: fields.length ? config : null }) } return ( }> {usable.length === 0 ?

{t('devices.form.noApps')}

: (
setCode(normalizeCode(e.target.value))} autoComplete="off" spellCheck={false} className="font-mono tracking-[0.3em] text-center uppercase" autoFocus /> setName(e.target.value)} placeholder={t('devices.form.namePlaceholder')} maxLength={60} /> {modes && ( setLink(e.target.value)} options={[{ value: '', label: t('devices.form.noLink') }, ...linkTargets(devices).map(d => ({ value: String(d.id), label: d.name }))]} /> )} {error &&

{error}

}
) } 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 app = apps.find(a => a.key === device.app_key) const fields = app?.device_app?.config || [] const [config, setConfig] = useState(() => configInitial(fields, device.config)) const { busy, error, run } = useSubmit(onSave) const modes = loginModeOptions(app, 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, ...(fields.length ? { config } : {}) }) } return ( }>
setName(e.target.value)} maxLength={60} /> {modes && ( setLink(e.target.value)} options={[{ value: '', label: t('devices.form.noLink') }, ...targets.map(d => ({ value: String(d.id), label: d.name }))]} /> )} {error &&

{error}

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