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:
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createContext } from 'react'
|
||||
|
||||
/** The loaded bootstrap + helpers (filled by <AccessProvider>, read by useAccess()). */
|
||||
export const AccessContext = createContext(null)
|
||||
@@ -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')} />
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
Reference in New Issue
Block a user