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:
@@ -10,6 +10,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
"@xenia/access": "^0.0.0",
|
||||
"@xenia/api": "^0.0.0",
|
||||
"@xenia/i18n": "^0.0.0",
|
||||
"@xenia/ui": "^0.0.0",
|
||||
"axios": "^1.7.9",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { lazy, Suspense, useEffect, useState } from 'react'
|
||||
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom'
|
||||
import { BrowserRouter, Routes, Route, Navigate, Outlet, useNavigate } from 'react-router-dom'
|
||||
import { AccessProvider, RequireModule } from '@xenia/access'
|
||||
import { createI18n } from '@xenia/i18n'
|
||||
import useAuthStore from './store/authStore'
|
||||
import AppLayout from './layouts/AppLayout'
|
||||
import client from './api/client'
|
||||
@@ -54,6 +56,10 @@ import SettingsPage from './pages/Settings/SettingsPage'
|
||||
import NotesPage from './pages/NotesPage'
|
||||
import PermissionGuard from './components/PermissionGuard'
|
||||
|
||||
// Texts for the shared parts (approval dialog, "feature off" screens, component labels).
|
||||
// The language follows bootstrap (user -> venue); the current pages are still Greek (phase 6).
|
||||
const i18n = createI18n()
|
||||
|
||||
// Visual check pages for the shared packages, dev builds only (left out of production bundles)
|
||||
const UiGallery = import.meta.env.DEV ? lazy(() => import('@xenia/ui/gallery')) : null
|
||||
const I18nSample = import.meta.env.DEV ? lazy(() => import('@xenia/i18n/sample')) : null
|
||||
@@ -107,16 +113,29 @@ function SetupGuard({ children }) {
|
||||
return children
|
||||
}
|
||||
|
||||
// Platform bootstrap (modules, permission keys, venue, language) for every real page; it
|
||||
// reloads when the session token changes (login, logout, unlock). @xenia/access, plan step 2.5.
|
||||
function ManagerRoot() {
|
||||
const token = useAuthStore(s => s.token)
|
||||
return (
|
||||
<AccessProvider client={client} token={token} i18n={i18n} loading={<Spinner />}>
|
||||
<AuthRehydrator>
|
||||
<Outlet />
|
||||
</AuthRehydrator>
|
||||
</AccessProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthRehydrator>
|
||||
<Routes>
|
||||
<Routes>
|
||||
{UiGallery && <Route path="/ui-gallery" element={<Suspense fallback={null}><UiGallery /></Suspense>} />}
|
||||
{I18nSample && <Route path="/i18n-sample" element={<Suspense fallback={null}><I18nSample /></Suspense>} />}
|
||||
<Route element={<ManagerRoot />}>
|
||||
<Route path="/setup" element={<SetupWizard />} />
|
||||
{UiGallery && <Route path="/ui-gallery" element={<Suspense fallback={null}><UiGallery /></Suspense>} />}
|
||||
{I18nSample && <Route path="/i18n-sample" element={<Suspense fallback={null}><I18nSample /></Suspense>} />}
|
||||
<Route path="/login" element={<SetupGuard><LoginPage /></SetupGuard>} />
|
||||
<Route path="/kds" element={<RequireAuth><KdsPage /></RequireAuth>} />
|
||||
<Route path="/kds" element={<RequireAuth><RequireModule module="kds"><KdsPage /></RequireModule></RequireAuth>} />
|
||||
|
||||
<Route path="/" element={<RequireAuth><AppLayout /></RequireAuth>}>
|
||||
<Route index element={<Navigate to="/dashboard" replace />} />
|
||||
@@ -173,8 +192,8 @@ export default function App() {
|
||||
<Route path="management" element={<Navigate to="/management/products" replace />} />
|
||||
<Route path="reports" element={<Navigate to="/reports/today" replace />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthRehydrator>
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
import axios from 'axios'
|
||||
import { createApiClient } from '@xenia/api'
|
||||
|
||||
const client = axios.create({ baseURL: '' })
|
||||
|
||||
client.interceptors.request.use(config => {
|
||||
const token = localStorage.getItem('manager_token')
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
// The shared client (@xenia/api, plan step 2.5): session header, err.xenia on every error,
|
||||
// and the manager-approval retry (the dialog is mounted by <AccessProvider>).
|
||||
// Same origin: nginx (or Vite in dev) forwards /api to the backend.
|
||||
const client = createApiClient({
|
||||
axios,
|
||||
baseURL: '',
|
||||
getToken: () => localStorage.getItem('manager_token'),
|
||||
// A 401 on a normal request = the session ended (expired, logged out elsewhere, ended by
|
||||
// a manager): full logout. Login and unlock forms opt out with { xenia: { ignoreUnauthorized: true } }.
|
||||
onUnauthorized: () => {
|
||||
localStorage.removeItem('manager_token')
|
||||
localStorage.removeItem('manager_username')
|
||||
localStorage.removeItem('manager_lock_timeout')
|
||||
window.location.href = '/login'
|
||||
},
|
||||
})
|
||||
|
||||
client.interceptors.response.use(
|
||||
res => res,
|
||||
err => {
|
||||
if (err.response?.status === 401) {
|
||||
// On hard 401 (expired/invalid token) force a full logout
|
||||
localStorage.removeItem('manager_token')
|
||||
localStorage.removeItem('manager_username')
|
||||
localStorage.removeItem('manager_lock_timeout')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(err)
|
||||
}
|
||||
)
|
||||
// Dev builds only: lets the e2e suite (tests/e2e/manager.mjs) drive requests through this client
|
||||
if (import.meta.env.DEV) window.__xeniaClient = client
|
||||
|
||||
export default client
|
||||
|
||||
|
||||
@@ -1,11 +1,30 @@
|
||||
import useAuthStore from '../store/authStore'
|
||||
import { useAccess } from '@xenia/access'
|
||||
|
||||
// The current screens' permission names -> the v2 keys they stand for (the same pairs as
|
||||
// local_backend/core/access/legacy.py). Removed when the pages use useCan(key) directly (phase 6).
|
||||
const KEYS = {
|
||||
accessDashboard: 'core.dashboard.access',
|
||||
accessWaiterApp: 'waiter_app.access',
|
||||
accessKds: 'kds.access',
|
||||
cancelOrders: 'ordering.orders.cancel',
|
||||
applyDiscounts: 'pricing.discounts.apply',
|
||||
modifyPrices: 'ordering.prices.modify',
|
||||
openOrders: 'ordering.orders.open',
|
||||
closeOrders: 'ordering.orders.close',
|
||||
viewReports: 'reports.view',
|
||||
manageStaff: 'core.staff.manage',
|
||||
manageTables: 'catalog.tables.manage',
|
||||
manageMenu: 'catalog.menu.manage',
|
||||
manageSettings: 'core.settings.manage',
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a permissions object derived from the logged-in user.
|
||||
* Superadmin always has every permission regardless of stored flags.
|
||||
* The signed-in user's permissions in the shape the current pages use, from the keys in
|
||||
* the platform bootstrap (@xenia/access). A key whose module is off counts as not held.
|
||||
* Superadmin holds every key (the backend sends them all).
|
||||
*/
|
||||
export default function usePermissions() {
|
||||
const user = useAuthStore(s => s.user)
|
||||
const { user, permissions } = useAccess()
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
@@ -26,24 +45,7 @@ export default function usePermissions() {
|
||||
}
|
||||
}
|
||||
|
||||
const superadmin = user.role === 'superadmin'
|
||||
|
||||
const p = (flag) => superadmin || !!user[flag]
|
||||
|
||||
return {
|
||||
isSuperadmin: superadmin,
|
||||
accessDashboard: p('perm_access_dashboard'),
|
||||
accessWaiterApp: p('perm_access_waiter_app'),
|
||||
accessKds: p('perm_access_kds'),
|
||||
cancelOrders: p('perm_cancel_orders'),
|
||||
applyDiscounts: p('perm_apply_discounts'),
|
||||
modifyPrices: p('perm_modify_prices'),
|
||||
openOrders: p('perm_open_orders'),
|
||||
closeOrders: p('perm_close_orders'),
|
||||
viewReports: p('perm_view_reports'),
|
||||
manageStaff: p('perm_manage_staff'),
|
||||
manageTables: p('perm_manage_tables'),
|
||||
manageMenu: p('perm_manage_menu'),
|
||||
manageSettings: p('perm_manage_settings'),
|
||||
}
|
||||
const out = { isSuperadmin: user.role === 'superadmin' }
|
||||
for (const [name, key] of Object.entries(KEYS)) out[name] = permissions.has(key)
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -188,7 +188,8 @@ function LockScreen({ username, displayName, onUnlock, onLogout }) {
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
const { data } = await client.post('/api/auth/login', { username, pin: usedPin })
|
||||
// A wrong PIN is a 401: say "Wrong PIN" instead of the session-ended logout
|
||||
const { data } = await client.post('/api/auth/login', { username, pin: usedPin }, { xenia: { ignoreUnauthorized: true } })
|
||||
if (!data.user.perm_access_dashboard) {
|
||||
setError('Not a manager account.')
|
||||
setPin('')
|
||||
|
||||
@@ -145,7 +145,7 @@ export default function LoginPage() {
|
||||
async function handleAutoLogin(uname) {
|
||||
setLoading(true)
|
||||
try {
|
||||
const { data } = await client.post('/api/auth/login-no-auth', { username: uname })
|
||||
const { data } = await client.post('/api/auth/login-no-auth', { username: uname }, { xenia: { ignoreUnauthorized: true } })
|
||||
if (!data.user.perm_access_dashboard) { setLoading(false); return }
|
||||
clearManualLogoutFlag()
|
||||
login(data.user, data.access_token)
|
||||
@@ -169,7 +169,8 @@ export default function LoginPage() {
|
||||
if (loginMethod === 'password') body.password = password
|
||||
else if (loginMethod === 'pin') body.pin = pin
|
||||
|
||||
const { data } = await client.post('/api/auth/login', body)
|
||||
// A wrong password is a 401: show it here instead of the session-ended logout
|
||||
const { data } = await client.post('/api/auth/login', body, { xenia: { ignoreUnauthorized: true } })
|
||||
if (!data.user.perm_access_dashboard) {
|
||||
setError('This account does not have manager access.')
|
||||
setPin('')
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
const BACKEND = process.env.XENIA_BACKEND || 'http://localhost:8000'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
// npm workspace (D-15): shared packages are imported from source, so make
|
||||
@@ -12,11 +14,12 @@ export default defineConfig({
|
||||
host: '0.0.0.0',
|
||||
port: 5174,
|
||||
// Same as the waiter: the API is same-origin in production (nginx), so in
|
||||
// dev (and `vite preview`) forward it to the local backend.
|
||||
// dev (and `vite preview`) forward it to the local backend. XENIA_BACKEND picks
|
||||
// another one (the e2e suite runs its own on :8056).
|
||||
proxy: {
|
||||
'/api/ws': { target: 'ws://localhost:8000', ws: true, changeOrigin: true },
|
||||
'/api': { target: 'http://localhost:8000', changeOrigin: true },
|
||||
'/static': { target: 'http://localhost:8000', changeOrigin: true },
|
||||
'/api/ws': { target: BACKEND.replace(/^http/, 'ws'), ws: true, changeOrigin: true },
|
||||
'/api': { target: BACKEND, changeOrigin: true },
|
||||
'/static': { target: BACKEND, changeOrigin: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user