feat(waiter): the waiter app on the shared foundations (api client, access, i18n), lint clean, starts offline
Plan step 4.1. No visible change to layout or flows. - api/client.js on @xenia/api createApiClient (CS-8 baseURL, 401 → sign out, no answer → backend-offline, err.xenia, the manager-approval retry); the PIN login handles its own 401 (before, a wrong PIN reloaded the page). - <AccessProvider> at the root with an i18n instance: modules, permission keys, venue, language from bootstrap; who is signed in comes with it (no more /api/auth/me polling). packages/access: AccessProvider gains `cache` (the last bootstrap per session; used when the server can't be reached, `offline` in the context, keeps retrying) and `failed` (the app's own screen when there's nothing cached). The waiter caches per venue, shows its offline page (server search) on a first start without a server, retries every 5 s; ServerRediscovery and BundleSync run outside the bootstrap. - Role names → keys: the shift gate and the user menu use core.dashboard.access. - One shared, offline-cached read of the venue settings (api/venueSettings.js) instead of seven GET /api/settings/ calls; apiError() shows backend error codes in the user's language (17 places). - Lint: 78 errors → 0 (unused code, empty catches, two duplicate style keys, a component created during render, refs read during render → state, hooks after an early return); set-state-in-effect is a warning like the manager/terminal; lint in run-all. - Tests: tests/bootstrapCache.test.mjs; e2e browser: an offline restart stays signed in. Android rediscovery waits for what the screen shows instead of fixed sleeps: 10/10 three runs in a row (KI-009). Terminal 3.4 waits for both displays before the sale. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+1
-1
@@ -52,7 +52,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
|
||||
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
|
||||
| `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below |
|
||||
| `waiter_pwa/src/native/pairing.js`, `src/pages/VenuesPage.jsx` | Pairing with a venue (QR / typed address) and the venue switcher |
|
||||
| `waiter_pwa/src/api/client.js` | axios instance: auth header, 401 → logout, network error → offline |
|
||||
| `waiter_pwa/src/api/client.js`, `src/api/bootstrapCache.js`, `src/api/venueSettings.js`, `src/api/errors.js` | The waiter's client on `@xenia/api` (since 4.1): token, 401 → logout, no answer → `backend-offline`, the manager-approval retry; `<AccessProvider cache>` keeps the last bootstrap per venue so an offline restart stays signed in (CS-3); one shared, offline-cached read of the venue settings; `apiError(err, fallback)` shows backend error codes in the user's language |
|
||||
| `waiter_pwa/src/context/LiveContext.jsx`, `src/hooks/useWebSocket.js` | Real-time lifecycle, event → store/cache updates, visibility refresh; the socket itself is `createLiveClient` from `@xenia/api` |
|
||||
| `waiter_pwa/src/db/posdb`, `src/services/offlineOrders` | Offline cache and queued orders |
|
||||
| `nginx-proxy/nginx.conf` | Proxy config used in dev / by hand |
|
||||
|
||||
Generated
+2
@@ -9645,7 +9645,9 @@
|
||||
"@capacitor/core": "8.6.2",
|
||||
"@capgo/capacitor-updater": "8.54.2",
|
||||
"@tanstack/react-query": "^5.107.1",
|
||||
"@xenia/access": "^0.0.0",
|
||||
"@xenia/api": "^0.0.0",
|
||||
"@xenia/i18n": "^0.0.0",
|
||||
"@xenia/ui": "^0.0.0",
|
||||
"axios": "^1.21.1",
|
||||
"dexie": "^4.4.7",
|
||||
|
||||
@@ -22,32 +22,56 @@ import { OverrideHost } from './OverrideHost.jsx'
|
||||
* default); if it fails, an error screen with Retry. Nothing below ever sees a half-loaded state.
|
||||
* autoRetryMs (unattended screens, e.g. the terminal): when the server can't be reached
|
||||
* (offline or 5xx), retry by itself every autoRetryMs as well.
|
||||
* cache (apps that must start offline, CS-3: the waiter, plan step 4.1): { load(token) → data
|
||||
* | null, save(token, data) }. Every bootstrap that loads is saved; when the server can't be
|
||||
* reached, the last one saved for the same token is used (`offline: true` in the context)
|
||||
* and the provider keeps retrying (autoRetryMs, or every 15 s) until the server answers.
|
||||
* failed (optional): (error, retry) → what to show when the bootstrap can't load and there is
|
||||
* no cached one (the waiter shows its offline screen with the server search); default: an
|
||||
* error with Retry.
|
||||
*/
|
||||
const CACHE_RETRY_MS = 15_000
|
||||
|
||||
export function AccessProvider({
|
||||
client, token = null, i18n, deviceLanguage, override = true, loading, autoRetryMs = 0, children,
|
||||
client, token = null, i18n, deviceLanguage, override = true, loading, autoRetryMs = 0, cache, failed, children,
|
||||
}) {
|
||||
const [state, setState] = useState({ data: null, forToken: undefined, error: null })
|
||||
const [state, setState] = useState({ data: null, forToken: undefined, error: null, offline: false })
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const { data } = await client.get('/api/platform/bootstrap', { xenia: { ignoreUnauthorized: true, noOverride: true } })
|
||||
const apply = async data => {
|
||||
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])
|
||||
try {
|
||||
const { data } = await client.get('/api/platform/bootstrap', { xenia: { ignoreUnauthorized: true, noOverride: true } })
|
||||
await apply(data)
|
||||
try { cache?.save(token, data) } catch { /* storage full or blocked: still works online */ }
|
||||
setState({ data, forToken: token, error: null, offline: false })
|
||||
} catch (e) {
|
||||
const error = parseError(e)
|
||||
let cached = null
|
||||
if (cache && (error.offline || error.status >= 500)) {
|
||||
try { cached = cache.load(token) } catch { cached = null }
|
||||
}
|
||||
if (cached) {
|
||||
await apply(cached)
|
||||
setState({ data: cached, forToken: token, error: null, offline: true })
|
||||
} else {
|
||||
setState(s => ({ ...s, forToken: token, error, offline: false }))
|
||||
}
|
||||
}
|
||||
}, [client, token, i18n, deviceLanguage, cache])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const unreachable = !!state.error && (state.error.offline || state.error.status >= 500)
|
||||
useEffect(() => {
|
||||
if (!autoRetryMs || !unreachable) return undefined
|
||||
const id = setTimeout(load, autoRetryMs)
|
||||
const every = state.offline ? (autoRetryMs || CACHE_RETRY_MS) : unreachable ? autoRetryMs : 0
|
||||
if (!every) return undefined
|
||||
const id = setTimeout(load, every)
|
||||
return () => clearTimeout(id)
|
||||
}, [autoRetryMs, unreachable, state.error, load])
|
||||
}, [autoRetryMs, unreachable, state.offline, state.error, load])
|
||||
|
||||
const value = useMemo(() => {
|
||||
const d = state.data
|
||||
@@ -62,9 +86,10 @@ export function AccessProvider({
|
||||
language: d.language,
|
||||
modules: new Set((d.modules || []).map(m => m.key)),
|
||||
permissions: new Set(d.permissions || []),
|
||||
offline: state.offline, // running on the cached bootstrap (cache prop)
|
||||
refresh: load,
|
||||
}
|
||||
}, [state.data, load])
|
||||
}, [state.data, state.offline, load])
|
||||
|
||||
const current = state.forToken === token
|
||||
let content
|
||||
@@ -76,7 +101,7 @@ export function AccessProvider({
|
||||
</AccessContext.Provider>
|
||||
)
|
||||
} else if (state.error && current) {
|
||||
content = <LoadFailed error={state.error} retry={load} />
|
||||
content = failed?.(state.error, load) ?? <LoadFailed error={state.error} retry={load} />
|
||||
} else {
|
||||
content = loading === undefined ? <DefaultLoading /> : loading
|
||||
}
|
||||
|
||||
+13
-8
@@ -155,7 +155,12 @@ async function rediscovery() {
|
||||
await setVenues(v, { active: 'test-site-1', venues: { 'test-site-1': venue('test-site-1', `http://${H}:8055`) } })
|
||||
await v.evaluate(`localStorage.setItem('xenia:test-site-1:token', ${JSON.stringify(token)})`)
|
||||
v = await reloadApp(v)
|
||||
r.check('setup: paired and logged in', !!(await waitFor(async () => (await v.evaluate('location.pathname')) === '/tables', 30_000)))
|
||||
// waits for what the screen shows instead of fixed sleeps (KI-009): the app reloads at the
|
||||
// new address, so the WebView handle may need re-attaching meanwhile
|
||||
const onScreen = (check, ms = 30_000) => waitFor(async () => {
|
||||
try { return await check(v) } catch { v = await attach().catch(() => v); return false }
|
||||
}, ms, 500)
|
||||
r.check('setup: paired and logged in', !!(await onScreen(async vv => (await vv.evaluate('location.pathname')) === '/tables', 45_000)))
|
||||
|
||||
const stale = async (vv) => {
|
||||
await setVenues(vv, { active: 'test-site-1', venues: { 'test-site-1': venue('test-site-1', `http://${H.replace(/\d+$/, '99')}:8055`) } })
|
||||
@@ -167,20 +172,20 @@ async function rediscovery() {
|
||||
|
||||
v = await stale(v)
|
||||
r.check('logged in: server "moved" → found and saved', !!(await found()))
|
||||
await sleep(4000); v = await attach(); await sleep(4000)
|
||||
r.check('logged in: back on /tables, live', (await v.evaluate('location.pathname')) === '/tables' && (await connectivityColor(v)) === GREEN)
|
||||
r.check('logged in: back on /tables, live', !!(await onScreen(async vv =>
|
||||
(await vv.evaluate('location.pathname')) === '/tables' && (await connectivityColor(vv)) === GREEN, 40_000)))
|
||||
|
||||
await v.evaluate("localStorage.removeItem('xenia:test-site-1:token')")
|
||||
v = await stale(v)
|
||||
r.check('logged out: found and saved', !!(await found()))
|
||||
await sleep(4000); v = await attach(); await sleep(3000)
|
||||
r.check('logged out: waiter list loads from the new address', (await v.evaluate('document.body.innerText')).includes('Manager'))
|
||||
r.check('logged out: waiter list loads from the new address', !!(await onScreen(async vv =>
|
||||
(await vv.evaluate('document.body.innerText')).includes('Manager'), 40_000)))
|
||||
|
||||
await backend.stop()
|
||||
v = await stale(v)
|
||||
await sleep(15000)
|
||||
const offlineShown = await onScreen(async vv => (await vv.evaluate('location.pathname')) === '/offline', 45_000)
|
||||
r.check('server really down: saved address untouched', (await venuesState(v)).venues['test-site-1'].baseUrl.includes('.99:'))
|
||||
r.check('server really down: offline screen', (await v.evaluate('location.pathname')) === '/offline')
|
||||
r.check('server really down: offline screen', !!offlineShown)
|
||||
await v.evaluate("[...document.querySelectorAll('button')].find(e => e.textContent.includes('Αναζήτηση server')).click()")
|
||||
const notFound = await waitFor(async () => (await v.evaluate('document.body.innerText')).includes('Ο server δεν βρέθηκε'), 60_000)
|
||||
r.check('manual search ends with "not found" guidance', !!notFound)
|
||||
@@ -196,7 +201,7 @@ async function rediscovery() {
|
||||
await sleep(12000)
|
||||
r.check('cold start with the server down: still logged in', await v.evaluate("!!localStorage.getItem('xenia:test-site-1:token')"))
|
||||
backend = await startBackend({ port: 8055, siteId: 'test-site-1', dataDir: backend.dataDir })
|
||||
const recovered = await waitFor(async () => (await v.evaluate('location.pathname')) === '/tables', 30_000)
|
||||
const recovered = await onScreen(async vv => (await vv.evaluate('location.pathname')) === '/tables', 45_000)
|
||||
r.check('server back → app lands on /tables by itself', !!recovered)
|
||||
v.close()
|
||||
} finally {
|
||||
|
||||
@@ -57,6 +57,17 @@ try {
|
||||
r1.check(`${m.name}: IndexedDB "${m.db}"`, dbs.includes(m.db), dbs.join(','))
|
||||
r1.check(`${m.name}: secure context = ${m.secure}`, (await page.evaluate(() => window.isSecureContext)) === m.secure)
|
||||
if (m.name.startsWith('venue')) r1.check(`${m.name}: API calls go to the venue server`, [...apiHosts].every(h => h === '127.0.0.1:8055'), [...apiHosts].join(','))
|
||||
if (m.name.startsWith('same-origin')) {
|
||||
// 4.1: the bootstrap (who is signed in, permissions, venue) is cached per venue, so a
|
||||
// phone that reopens the app without the server still starts signed in
|
||||
const cached = await page.evaluate(() => !!localStorage.getItem('bootstrap'))
|
||||
await page.context().setOffline(true)
|
||||
await page.reload().catch(() => {})
|
||||
await sleep(4000)
|
||||
const signedIn = await page.evaluate(() => location.pathname).catch(() => '')
|
||||
r1.check(`${m.name}: the bootstrap is cached and an offline restart stays signed in`, cached && signedIn.startsWith('/tables'), `${cached} ${signedIn}`)
|
||||
await page.context().setOffline(false)
|
||||
}
|
||||
await page.context().close()
|
||||
}
|
||||
failures += r1.done()
|
||||
|
||||
@@ -9,6 +9,7 @@ const shell = process.platform === 'win32'
|
||||
const suites = [
|
||||
['unit: local_backend (pytest)', PYTHON, ['-m', 'pytest', 'tests', '-q'], BACKEND],
|
||||
['unit: waiter_pwa (node --test)', 'npm', ['test', '--silent'], WAITER],
|
||||
['lint: waiter_pwa', 'npm', ['run', 'lint', '--silent'], WAITER],
|
||||
['unit: packages/ui (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/ui'], CS],
|
||||
['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],
|
||||
|
||||
@@ -695,6 +695,7 @@ try {
|
||||
// its own address for the pairing rate limit (one per screen in a real venue)
|
||||
const otherDisplay = await screen(await (await browser.newContext({ viewport: { width: 1024, height: 600 }, extraHTTPHeaders: { 'x-real-ip': '10.9.0.42' } })).newPage())
|
||||
await pairFromManager(otherDisplay, boss, { app_key: 'customer_display', name: 'Display elsewhere' })
|
||||
await shown(otherDisplay, 'display-idle', 15_000) // both screens up before the sale
|
||||
r.check('3.4: a display linked to the counter shows the idle screen: the venue name (the default)',
|
||||
await shown(myDisplay, 'display-idle', 15_000) && (await myDisplay.getByTestId('display-name').textContent()) === 'Taverna E2E')
|
||||
await simpleCard.locator('button').first().click()
|
||||
|
||||
@@ -23,7 +23,12 @@ export default defineConfig([
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
|
||||
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]', argsIgnorePattern: '^_' }],
|
||||
// Like the manager and the terminal (2.99b): loading data in an effect is the pattern the
|
||||
// pages use; it becomes an error again when they load with react-query (phase 6 note).
|
||||
'react-hooks/set-state-in-effect': 'warn',
|
||||
// A context's provider and its hook live in one file
|
||||
'react-refresh/only-export-components': ['error', { allowConstantExport: true, allowExportNames: ['useLiveContext', 'useNotifications'] }],
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
@@ -19,7 +19,9 @@
|
||||
"@capacitor/core": "8.6.2",
|
||||
"@capgo/capacitor-updater": "8.54.2",
|
||||
"@tanstack/react-query": "^5.107.1",
|
||||
"@xenia/access": "^0.0.0",
|
||||
"@xenia/api": "^0.0.0",
|
||||
"@xenia/i18n": "^0.0.0",
|
||||
"@xenia/ui": "^0.0.0",
|
||||
"axios": "^1.21.1",
|
||||
"dexie": "^4.4.7",
|
||||
|
||||
+43
-36
@@ -1,6 +1,8 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { BrowserRouter, Routes, Route, Navigate, Outlet, useNavigate } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { AccessProvider, useAccess, useCan } from '@xenia/access'
|
||||
import { i18n } from './i18n'
|
||||
import useAuthStore from './store/authStore'
|
||||
import useShiftStore from './store/shiftStore'
|
||||
import useThemeStore from './store/themeStore'
|
||||
@@ -8,6 +10,9 @@ import useTableColourStore from './store/tableColourStore'
|
||||
import useConnectionStore from './store/connectionStore'
|
||||
import useWaiterFavoritesStore from './store/waiterFavoritesStore'
|
||||
import client from './api/client'
|
||||
import { apiError } from './api/errors'
|
||||
import { getVenueSettings } from './api/venueSettings'
|
||||
import { bootstrapCache } from './api/bootstrapCache'
|
||||
import LoginPage from './pages/LoginPage'
|
||||
import TableListPage from './pages/TableListPage'
|
||||
import TableDetailPage from './pages/TableDetailPage'
|
||||
@@ -111,7 +116,7 @@ function StartShiftScreen({ username, onStart, onLogout }) {
|
||||
try {
|
||||
await onStart(startingCash ? parseFloat(startingCash) : null)
|
||||
} catch (e) {
|
||||
setError(e.response?.data?.detail || 'Σφάλμα εκκίνησης βάρδιας')
|
||||
setError(apiError(e, 'Σφάλμα εκκίνησης βάρδιας'))
|
||||
setStarting(false)
|
||||
}
|
||||
}
|
||||
@@ -173,15 +178,13 @@ function AppLayout() {
|
||||
const { token, user, logout } = useAuthStore()
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
shift, businessDay,
|
||||
setShift, setBusinessDay,
|
||||
setSelfStartAllowed, setSelfEndAllowed,
|
||||
gateStatus, setGateStatus,
|
||||
} = useShiftStore()
|
||||
|
||||
if (!token) return <Navigate to="/login" replace />
|
||||
|
||||
const isManager = user?.role && user.role !== 'waiter'
|
||||
// People with the manager dashboard work without a shift of their own (plan 4.1: the key,
|
||||
// not the role name)
|
||||
const isManager = useCan('core.dashboard.access')
|
||||
|
||||
async function checkGate() {
|
||||
if (!user) return
|
||||
@@ -203,7 +206,7 @@ function AppLayout() {
|
||||
|
||||
// No active shift — check self-start setting
|
||||
try {
|
||||
const settingsRes = await client.get('/api/settings/')
|
||||
const settingsRes = await getVenueSettings()
|
||||
const canStart = settingsRes.data?.['shifts.waiter_self_start']?.value !== 'false'
|
||||
const canEnd = settingsRes.data?.['shifts.waiter_self_end']?.value !== 'false'
|
||||
setSelfStartAllowed(canStart)
|
||||
@@ -222,7 +225,7 @@ function AppLayout() {
|
||||
|
||||
useEffect(() => {
|
||||
if (user) checkGate()
|
||||
}, [user?.id])
|
||||
}, [user?.id]) // eslint-disable-line react-hooks/exhaustive-deps -- once per signed-in user
|
||||
|
||||
// Poll every 15s to detect shift-end or business-day-close triggered by manager
|
||||
useEffect(() => {
|
||||
@@ -241,7 +244,7 @@ function AppLayout() {
|
||||
}
|
||||
}, 15_000)
|
||||
return () => clearInterval(id)
|
||||
}, [user, isManager, gateStatus])
|
||||
}, [user, isManager, gateStatus]) // eslint-disable-line react-hooks/exhaustive-deps -- checkGate reads the latest store
|
||||
|
||||
async function handleStartShift(startingCash) {
|
||||
const res = await client.post('/api/shifts/start', { starting_cash: startingCash })
|
||||
@@ -254,6 +257,7 @@ function AppLayout() {
|
||||
navigate('/login')
|
||||
}
|
||||
|
||||
if (!token) return <Navigate to="/login" replace />
|
||||
if (!user || gateStatus === 'loading') return <Spinner />
|
||||
|
||||
if (gateStatus === 'closed') return <ClosedScreen onRefresh={checkGate} onLogout={handleLogout} />
|
||||
@@ -273,34 +277,17 @@ function AppLayout() {
|
||||
|
||||
// ─── Global helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
/** Who is signed in comes with the bootstrap (plan 4.1): online it's the server's answer;
|
||||
* offline the bootstrap cached for this token keeps the waiter signed in (CS-3). A token the
|
||||
* server no longer knows comes back with no user: sign out. */
|
||||
function AuthRehydrator() {
|
||||
const { token, user, login, logout } = useAuthStore()
|
||||
const access = useAccess()
|
||||
useEffect(() => {
|
||||
if (!token || user) return
|
||||
let cancelled = false
|
||||
let timer = null
|
||||
async function load() {
|
||||
try {
|
||||
const r = await client.get('/api/auth/me')
|
||||
if (!cancelled) login(r.data, token)
|
||||
} catch (err) {
|
||||
if (cancelled) return
|
||||
// Server unreachable (flaky WiFi, server restarting, IP change being
|
||||
// rediscovered): keep the login and try again. Only a real answer from
|
||||
// the server ends the session — 401 is also handled by the axios interceptor.
|
||||
if (!err.response) {
|
||||
timer = setTimeout(load, 5000)
|
||||
return
|
||||
}
|
||||
logout()
|
||||
}
|
||||
}
|
||||
load()
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [token, user])
|
||||
if (access.user) login(access.user, token)
|
||||
else if (!access.offline) logout()
|
||||
}, [token, user, access.user, access.offline, login, logout])
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -376,7 +363,7 @@ function AndroidBackGuard() {
|
||||
function ColourLoader() {
|
||||
const loadFromBackend = useTableColourStore(s => s.loadFromBackend)
|
||||
useEffect(() => {
|
||||
client.get('/api/settings/')
|
||||
getVenueSettings()
|
||||
.then(r => {
|
||||
const raw = r.data?.['ui.table_colours']?.value
|
||||
if (raw) loadFromBackend(raw)
|
||||
@@ -432,7 +419,29 @@ export default function App() {
|
||||
if (deliveryMode() === 'native' && !getActiveVenue()) {
|
||||
return <VenuesPage firstRun />
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{/* outside the bootstrap: they must run even when the server can't be reached yet */}
|
||||
{deliveryMode() === 'native' && <ServerRediscovery />}
|
||||
{deliveryMode() === 'native' && <BundleSync />}
|
||||
<Access><Routed /></Access>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** The platform bootstrap for the current session (plan step 4.1): modules, permission keys,
|
||||
* venue and language for every screen; cached per venue so the app also starts offline. */
|
||||
function Access({ children }) {
|
||||
const token = useAuthStore(s => s.token)
|
||||
return (
|
||||
<AccessProvider client={client} token={token} i18n={i18n} cache={bootstrapCache} loading={<Spinner />} autoRetryMs={5000}
|
||||
failed={error => (error.offline || error.status >= 500 ? <OfflinePage /> : undefined)}>
|
||||
{children}
|
||||
</AccessProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function Routed() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
@@ -448,8 +457,6 @@ export default function App() {
|
||||
{/* Native builds ship their UI in the app bundle — no service worker to update */}
|
||||
{deliveryMode() !== 'native' && <UpdatePrompt />}
|
||||
<InstallAppDialog />
|
||||
{deliveryMode() === 'native' && <ServerRediscovery />}
|
||||
{deliveryMode() === 'native' && <BundleSync />}
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginGuard><LoginPage /></LoginGuard>} />
|
||||
<Route path="/offline" element={<OfflinePage />} />
|
||||
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
// The last platform bootstrap (modules, permission keys, venue, language), kept per venue so
|
||||
// the waiter app starts and works offline (CS-3, plan step 4.1). <AccessProvider cache={…}>
|
||||
// saves every bootstrap it loads and uses this one, for the same session token, when the
|
||||
// server can't be reached. Rules: src/logic/bootstrapCache.js.
|
||||
import { storageKey } from '../config/server'
|
||||
import { makeBootstrapCache } from '../logic/bootstrapCache'
|
||||
|
||||
export const bootstrapCache = makeBootstrapCache(localStorage, () => storageKey('bootstrap'))
|
||||
@@ -1,27 +1,28 @@
|
||||
// The waiter's HTTP client on the shared @xenia/api (plan step 4.1): the session header, every
|
||||
// error carries err.xenia ({ code, params, message, … } shown in the user's language), and a
|
||||
// request a manager may approve opens the approval dialog (mounted by <AccessProvider>) and is
|
||||
// retried once with their PIN. The backend address follows the active venue (CS-8: same
|
||||
// origin in a browser served by the venue, absolute in the native app).
|
||||
import axios from 'axios'
|
||||
import { createApiClient } from '@xenia/api'
|
||||
import { apiBase, storageKey } from '../config/server'
|
||||
|
||||
const client = axios.create({ baseURL: apiBase() })
|
||||
|
||||
client.interceptors.request.use(config => {
|
||||
const token = localStorage.getItem(storageKey('token'))
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
})
|
||||
|
||||
client.interceptors.response.use(
|
||||
res => res,
|
||||
err => {
|
||||
if (!err.response) {
|
||||
window.dispatchEvent(new Event('backend-offline'))
|
||||
} else if (err.response.status === 401) {
|
||||
// Token expired or user blocked — force logout
|
||||
const client = createApiClient({
|
||||
axios,
|
||||
baseURL: () => apiBase(),
|
||||
getToken: () => localStorage.getItem(storageKey('token')),
|
||||
// No answer at all: the connectivity bar and the rediscovery scan listen for this
|
||||
onOffline: () => window.dispatchEvent(new Event('backend-offline')),
|
||||
// A 401 on a normal request = the session ended (expired, ended by a manager, signed in
|
||||
// elsewhere): sign out. The login and PIN forms opt out with { xenia: { ignoreUnauthorized: true } }.
|
||||
onUnauthorized: () => {
|
||||
localStorage.removeItem(storageKey('token'))
|
||||
localStorage.removeItem(storageKey('savedUsername'))
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(err)
|
||||
}
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
// Dev builds only: lets the e2e suites drive requests through this client
|
||||
if (import.meta.env.DEV) window.__xeniaClient = client
|
||||
|
||||
export default client
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// A refused request as a message for the waiter (plan step 4.1): a backend error code is
|
||||
// shown in the user's language (packages/i18n locales errors.json); an older endpoint's own
|
||||
// text as it comes; with no answer at all, the screen's own fallback text.
|
||||
import { errorMessage, parseError } from '@xenia/api'
|
||||
import { i18n } from '../i18n'
|
||||
|
||||
export function apiError(err, fallback = '') {
|
||||
const x = parseError(err)
|
||||
if (x.offline) return fallback || errorMessage(err, i18n.t.bind(i18n))
|
||||
if (!x.code.startsWith('http.')) return errorMessage(err, i18n.t.bind(i18n))
|
||||
return (typeof x.detail === 'string' && x.detail) || fallback || x.message
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// The venue's settings the waiter app reads (shift self-start, card payments, courses, quick
|
||||
// notes, table colours…), plan step 4.1: one request shared by every screen instead of a
|
||||
// GET /api/settings/ per page, kept per venue so the screens keep their options offline (CS-3).
|
||||
//
|
||||
// const { data } = await getVenueSettings() // same shape as the old client.get(...)
|
||||
// data?.['payments.card_enabled']?.value
|
||||
//
|
||||
// Fresh for FRESH_MS; concurrent callers share one request; without a server the last copy
|
||||
// saved for this venue answers (or {} on a first start offline).
|
||||
import client from './client'
|
||||
import { storageKey } from '../config/server'
|
||||
|
||||
const FRESH_MS = 30_000
|
||||
let memo = null // { at, data }
|
||||
let inflight = null
|
||||
|
||||
const KEY = () => storageKey('venueSettings')
|
||||
|
||||
function saved() {
|
||||
try { return JSON.parse(localStorage.getItem(KEY()) || 'null') } catch { return null }
|
||||
}
|
||||
|
||||
export function getVenueSettings({ fresh = false } = {}) {
|
||||
if (!fresh && memo && Date.now() - memo.at < FRESH_MS) return Promise.resolve({ data: memo.data })
|
||||
if (inflight) return inflight
|
||||
inflight = client.get('/api/settings/')
|
||||
.then(r => {
|
||||
memo = { at: Date.now(), data: r.data }
|
||||
try { localStorage.setItem(KEY(), JSON.stringify(r.data)) } catch { /* storage full: still works online */ }
|
||||
return { data: r.data }
|
||||
})
|
||||
.catch(err => {
|
||||
const copy = saved()
|
||||
if (copy && !err?.response) return { data: copy }
|
||||
throw err
|
||||
})
|
||||
.finally(() => { inflight = null })
|
||||
return inflight
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import UserMenu from './UserMenu'
|
||||
import { useNotifications } from '../context/NotificationContext'
|
||||
|
||||
@@ -15,7 +15,6 @@ export default function ConnectivityBar() {
|
||||
|
||||
const isOnline = status === 'online'
|
||||
const isReconnecting = status === 'reconnecting'
|
||||
const isOffline = status === 'offline'
|
||||
|
||||
const color = isOnline
|
||||
? (liveAlive ? '#22c55e' : '#3b82f6')
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
|
||||
import client from '../api/client'
|
||||
import { getVenueSettings } from '../api/venueSettings'
|
||||
import { assetUrl } from '../config/server'
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function fmt(n) {
|
||||
if (n === 0) return ''
|
||||
const s = n > 0 ? `+${n.toFixed(2)} €` : `${n.toFixed(2)} €`
|
||||
return s
|
||||
}
|
||||
|
||||
function buildInitialState(product) {
|
||||
const preferenceSets = product.preference_sets || []
|
||||
|
||||
@@ -445,7 +439,7 @@ function FavoritesTab({ product, waiterOverride, quickState, setQuickState, extr
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
{favorites.map((fav, fi) => {
|
||||
{favorites.map((fav, _fi) => {
|
||||
if (fav.type === 'quick') {
|
||||
return <QuickOptionRow key={`quick-${fav.item.id}`} opt={fav.item} quickState={quickState} setQuickState={setQuickState} compact={false} />
|
||||
}
|
||||
@@ -931,12 +925,10 @@ function NotesTab({ note, setNote, quickNotes = FALLBACK_QUICK_NOTES }) {
|
||||
|
||||
// ── Tab: Summary ──────────────────────────────────────────────────────────────
|
||||
|
||||
function SummaryTab({ product, summaryLines, note, onJumpTab }) {
|
||||
const isEmpty = summaryLines.length === 0 && !note
|
||||
const byGroup = { quick: [], extras: [], removed: [], prefs: [] }
|
||||
summaryLines.forEach(l => byGroup[l.group]?.push(l))
|
||||
|
||||
const Section = ({ title, tab, lines }) => lines.length === 0 ? null : (
|
||||
/** One group of the summary (prefs, quick options, extras, removed) with its "change" link. */
|
||||
function Section({ title, tab, lines, onJumpTab }) {
|
||||
if (lines.length === 0) return null
|
||||
return (
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 2px 8px' }}>
|
||||
<div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{title}</div>
|
||||
@@ -973,7 +965,14 @@ function SummaryTab({ product, summaryLines, note, onJumpTab }) {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function SummaryTab({ _product, summaryLines, note, onJumpTab }) {
|
||||
const isEmpty = summaryLines.length === 0 && !note
|
||||
const byGroup = { quick: [], extras: [], removed: [], prefs: [] }
|
||||
summaryLines.forEach(l => byGroup[l.group]?.push(l))
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -983,10 +982,10 @@ function SummaryTab({ product, summaryLines, note, onJumpTab }) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Section title="Προτιμήσεις" tab="prefs" lines={byGroup.prefs} />
|
||||
<Section title="Γρήγορες Επιλογές" tab="quick" lines={byGroup.quick} />
|
||||
<Section title="Extras" tab="extras" lines={byGroup.extras} />
|
||||
<Section title="Αφαιρέθηκαν" tab="ingredients" lines={byGroup.removed} />
|
||||
<Section title="Προτιμήσεις" tab="prefs" lines={byGroup.prefs} onJumpTab={onJumpTab} />
|
||||
<Section title="Γρήγορες Επιλογές" tab="quick" lines={byGroup.quick} onJumpTab={onJumpTab} />
|
||||
<Section title="Extras" tab="extras" lines={byGroup.extras} onJumpTab={onJumpTab} />
|
||||
<Section title="Αφαιρέθηκαν" tab="ingredients" lines={byGroup.removed} onJumpTab={onJumpTab} />
|
||||
{note && (
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 2px 8px' }}>
|
||||
@@ -1051,7 +1050,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
|
||||
const [priceAdjAllowed, setPriceAdjAllowed] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
client.get('/api/settings/')
|
||||
getVenueSettings()
|
||||
.then(r => setPriceAdjAllowed(r.data?.['orders.waiter_price_adjust_allowed']?.value === 'true'))
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
@@ -208,7 +208,7 @@ const PRICING_EVENT_STYLE = {
|
||||
deal_offer_accepted: { color: '#4ade80', label: null }, // label from deal_name
|
||||
}
|
||||
|
||||
function PricingRows({ events, layout, nameIndent = 12 }) {
|
||||
function PricingRows({ events, _layout, nameIndent = 12 }) {
|
||||
const rows = events.filter(ev =>
|
||||
ev.event_type === 'modifier_applied' ||
|
||||
ev.event_type === 'waiter_discount' ||
|
||||
@@ -225,7 +225,6 @@ function PricingRows({ events, layout, nameIndent = 12 }) {
|
||||
const evStyle = PRICING_EVENT_STYLE[ev.event_type] || { color: '#94a3b8', label: ev.event_type }
|
||||
const label = ev.modifier_name || ev.deal_name || evStyle.label || ev.event_type
|
||||
const delta = ev.delta_amount
|
||||
const afterPrice = ev.price_after
|
||||
|
||||
return (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
|
||||
|
||||
@@ -181,7 +181,7 @@ function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
|
||||
const onDetail = useCallback(() => onShowDetail(product), [onShowDetail, product])
|
||||
const longPress = useLongPress(onDetail, 1200)
|
||||
|
||||
function handleClick(e) {
|
||||
function handleClick(_e) {
|
||||
// If a long-press just fired, don't open the drawer
|
||||
if (longPress.didFire()) return
|
||||
onOpen(product)
|
||||
|
||||
@@ -51,7 +51,6 @@ function computeKdsBadge(order) {
|
||||
if (!order?.items) return null
|
||||
const relevant = order.items.filter(i => i.status !== 'cancelled' && kds(i.kds_status) !== 'served')
|
||||
if (relevant.length === 0) return null
|
||||
const pending = relevant.filter(i => kds(i.kds_status) === 'pending').length
|
||||
const preparing = relevant.filter(i => kds(i.kds_status) === 'preparing').length
|
||||
const done = relevant.filter(i => kds(i.kds_status) === 'done').length
|
||||
const total = relevant.length
|
||||
@@ -282,7 +281,7 @@ function Amount({ value, size = 22, color }) {
|
||||
// ─── Card variants ────────────────────────────────────────────────────────────
|
||||
|
||||
// 1x1 — square-ish, 4 per row. Badges top (up to 2 + +N), name center, KDS badge bottom (replaces status).
|
||||
function Card1x1({ table, order, flags, waiterObjects, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
function Card1x1({ table, _order, flags, _waiterObjects, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
return (
|
||||
<div style={{
|
||||
width: '100%', aspectRatio: '1 / 1.05',
|
||||
@@ -329,7 +328,7 @@ function Card1x1({ table, order, flags, waiterObjects, cfg, statusKey, kdsBadge,
|
||||
}
|
||||
|
||||
// 2x1 — half width, compact horizontal. Name left, KDS badge (or status) + flags right.
|
||||
function Card2x1({ table, order, flags, waiterObjects, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
function Card2x1({ table, _order, flags, _waiterObjects, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
return (
|
||||
<div style={{
|
||||
width: '100%', height: 64,
|
||||
@@ -369,7 +368,7 @@ function Card2x1({ table, order, flags, waiterObjects, cfg, statusKey, kdsBadge,
|
||||
}
|
||||
|
||||
// 2x2 — current-style square. Name top-left, status below, amount bottom-left, KDS badge top-right, flags right.
|
||||
function Card2x2({ table, order, flags, waiterObjects, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
function Card2x2({ table, order, flags, _waiterObjects, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
const isFree = !order
|
||||
const total = order?.items?.filter(i => i.status === 'active').reduce((s, i) => s + i.unit_price * i.quantity, 0) ?? 0
|
||||
|
||||
@@ -419,7 +418,7 @@ function Card2x2({ table, order, flags, waiterObjects, cfg, statusKey, kdsBadge,
|
||||
}
|
||||
|
||||
// 4x1 — full width horizontal. Name + amount left-center, flags, KDS badge (or status) right.
|
||||
function Card4x1({ table, order, flags, waiterObjects, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
function Card4x1({ table, order, flags, _waiterObjects, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
const isFree = !order
|
||||
const total = order?.items?.filter(i => i.status === 'active').reduce((s, i) => s + i.unit_price * i.quantity, 0) ?? 0
|
||||
|
||||
@@ -555,7 +554,7 @@ function Card4x2({ table, order, flags, waiterObjects, groupName, cfg, statusKey
|
||||
}
|
||||
|
||||
// 4x3 — full width, two-column detail card. Left: name/zone/status/amount. Right: items. KDS footer. Waiter footer.
|
||||
function Card4x3({ table, order, flags, waiterObjects, groupName, cfg, statusKey, kdsBadge, flashOverlay }) {
|
||||
function Card4x3({ table, order, flags, waiterObjects, groupName, cfg, statusKey, _kdsBadge, flashOverlay }) {
|
||||
const isFree = !order
|
||||
const activeItems = order?.items?.filter(i => i.status === 'active') ?? []
|
||||
const total = activeItems.reduce((s, i) => s + i.unit_price * i.quantity, 0)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useCan } from '@xenia/access'
|
||||
import useAuthStore from '../store/authStore'
|
||||
import useShiftStore from '../store/shiftStore'
|
||||
import useThemeStore from '../store/themeStore'
|
||||
@@ -46,8 +47,9 @@ export default function UserMenu() {
|
||||
navigate('/login')
|
||||
}
|
||||
|
||||
const canDashboard = useCan('core.dashboard.access')
|
||||
const activeBreak = shift?.breaks?.find(b => !b.ended_at)
|
||||
const isWaiter = user?.role === 'waiter'
|
||||
const isWaiter = !canDashboard // works in a shift (plan 4.1: the key, not the role)
|
||||
|
||||
async function handleEndShift() {
|
||||
if (!window.confirm('Να τελειώσει η βάρδια σου;')) return
|
||||
|
||||
@@ -164,7 +164,7 @@ export function LiveProvider({ children }) {
|
||||
...o,
|
||||
waiter_ids: o.waiters?.map(w => w.waiter_id) ?? [],
|
||||
})
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
useKdsReadyStore.getState().refresh()
|
||||
break
|
||||
}
|
||||
|
||||
@@ -164,7 +164,7 @@ export function NotificationProvider({ children }) {
|
||||
try {
|
||||
const res = await client.get('/api/notifications/recent?limit=10')
|
||||
setRecentMessages(res.data)
|
||||
} catch { }
|
||||
} catch { /* ignore */ }
|
||||
}, [token, user?.id])
|
||||
|
||||
// Initial load + 5s fallback poll (SSE is primary, poll is safety net)
|
||||
@@ -235,7 +235,7 @@ export function NotificationProvider({ children }) {
|
||||
await client.post(`/api/notifications/${messageId}/ack`)
|
||||
setPendingMessages(prev => prev.filter(m => m.id !== messageId))
|
||||
fetchRecent()
|
||||
} catch { }
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// Mark all pending as read (used when notification panel opens in never-popup mode)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// The waiter app's translations instance (plan step 4.1; its own texts become keys in 4.5).
|
||||
import { createI18n } from '@xenia/i18n'
|
||||
|
||||
export const i18n = createI18n({ defaultNS: 'common' })
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
// The cached-bootstrap rules (plan step 4.1), pure so Node tests can run them
|
||||
// (tests/bootstrapCache.test.mjs). src/api/bootstrapCache.js binds them to localStorage and
|
||||
// the venue's key.
|
||||
|
||||
/** { load(token), save(token, data) } over a Storage-like object; one entry under `key()`. */
|
||||
export function makeBootstrapCache(storage, key) {
|
||||
return {
|
||||
load(token) {
|
||||
const raw = storage.getItem(key())
|
||||
if (!raw) return null
|
||||
let saved
|
||||
try { saved = JSON.parse(raw) } catch { return null }
|
||||
// only for the same session: another waiter's (or a signed-out) bootstrap never leaks in
|
||||
return saved && saved.token === (token || null) ? saved.data : null
|
||||
},
|
||||
save(token, data) {
|
||||
storage.setItem(key(), JSON.stringify({ token: token || null, data }))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import ProductPicker from '../components/ProductPicker'
|
||||
import OrderDrawer from '../components/OrderDrawer'
|
||||
import OrderSummaryModal from '../components/OrderSummaryModal'
|
||||
import client from '../api/client'
|
||||
import { apiError } from '../api/errors'
|
||||
import { getVenueSettings } from '../api/venueSettings'
|
||||
import db from '../db/posdb'
|
||||
import { useProductCache } from '../hooks/useProductCache'
|
||||
import useOrderingSettingsStore from '../store/orderingSettingsStore'
|
||||
@@ -195,14 +197,14 @@ export default function AddItemsPage() {
|
||||
_key: Date.now() + Math.random(),
|
||||
}))
|
||||
setCart(initialCart)
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
load()
|
||||
}, [tableId, isStandalone, orderType])
|
||||
|
||||
useEffect(() => {
|
||||
client.get('/api/settings/').then(r => {
|
||||
getVenueSettings().then(r => {
|
||||
const s = r.data
|
||||
if (s?.['orders.courses_enabled']?.value === 'true') {
|
||||
try { setCourses(JSON.parse(s?.['orders.courses']?.value || '[]')) } catch { /* ignore */ }
|
||||
@@ -348,7 +350,7 @@ export default function AddItemsPage() {
|
||||
setTimeout(() => navigate('/tables'), 1200)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα αποστολής — η παραγγελία δεν στάλθηκε')
|
||||
setError(apiError(err, 'Σφάλμα αποστολής — η παραγγελία δεν στάλθηκε'))
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
@@ -685,7 +687,7 @@ export default function AddItemsPage() {
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{groups.map((group, gi) => (
|
||||
{groups.map((group, _gi) => (
|
||||
<div key={group.course?.id ?? '__none__'} style={{ position: 'relative' }}>
|
||||
{/* Colored left accent bar */}
|
||||
<div style={{
|
||||
@@ -949,7 +951,7 @@ export default function AddItemsPage() {
|
||||
|
||||
// ── Deal Offer Modal ──────────────────────────────────────────────────────────
|
||||
|
||||
function DealOfferModal({ offer, products, onAccept, onDismiss }) {
|
||||
function DealOfferModal({ offer, _products, onAccept, onDismiss }) {
|
||||
const isFreeItem = offer.action_type === 'free_item'
|
||||
const isFreeChoice = offer.action_type === 'free_choice'
|
||||
const isDiscount = ['set_price','add_amount','add_percent','apply_modifier'].includes(offer.action_type)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import client from '../api/client'
|
||||
import { apiError } from '../api/errors'
|
||||
import useAuthStore from '../store/authStore'
|
||||
import useChatStore from '../store/chatStore'
|
||||
|
||||
@@ -53,7 +54,6 @@ function Avatar({ label, size = 44, isGroup = false }) {
|
||||
|
||||
function ConvRow({ conv, currentUserId, onClick }) {
|
||||
const isGroup = conv.type === 'group'
|
||||
const isDirect = conv.type === 'direct'
|
||||
|
||||
const title = isGroup
|
||||
? (conv.name || 'Ομάδα')
|
||||
@@ -74,7 +74,7 @@ function ConvRow({ conv, currentUserId, onClick }) {
|
||||
onClick={onClick}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 12,
|
||||
padding: '14px 16px', borderBottom: '1px solid var(--border)',
|
||||
padding: '14px 16px',
|
||||
background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
|
||||
width: '100%', textAlign: 'left', cursor: 'pointer',
|
||||
}}
|
||||
@@ -150,7 +150,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
|
||||
})
|
||||
onConversationCreated(res.data)
|
||||
} catch (e) {
|
||||
setError(e.response?.data?.detail || 'Σφάλμα δημιουργίας συνομιλίας')
|
||||
setError(apiError(e, 'Σφάλμα δημιουργίας συνομιλίας'))
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
@@ -167,7 +167,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
|
||||
})
|
||||
onConversationCreated(res.data)
|
||||
} catch (e) {
|
||||
setError(e.response?.data?.detail || 'Σφάλμα δημιουργίας ομάδας')
|
||||
setError(apiError(e, 'Σφάλμα δημιουργίας ομάδας'))
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,7 +203,6 @@ export default function ChatThreadPage() {
|
||||
const displayMessages = [...rawMessages].reverse()
|
||||
|
||||
const isGroup = conv?.type === 'group'
|
||||
const isDirect = conv?.type === 'direct'
|
||||
|
||||
const title = isGroup
|
||||
? (conv?.name || 'Ομάδα')
|
||||
@@ -215,7 +214,7 @@ export default function ChatThreadPage() {
|
||||
try {
|
||||
await client.post(`/api/chat/conversations/${conversationId}/read`)
|
||||
markConvRead(conversationId)
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
}, [conversationId, markConvRead])
|
||||
|
||||
// ── Initial load ─────────────────────────────────────────────────────────────
|
||||
@@ -229,7 +228,7 @@ export default function ChatThreadPage() {
|
||||
try {
|
||||
const r = await client.get(`/api/chat/conversations/${conversationId}`)
|
||||
if (!cancelled) upsertConversation(r.data)
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// Load first page of messages
|
||||
@@ -287,7 +286,7 @@ export default function ChatThreadPage() {
|
||||
el.scrollTop = el.scrollHeight - prevScrollHeight + prevScrollTop
|
||||
}
|
||||
})
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
setLoadingMore(false)
|
||||
}
|
||||
|
||||
@@ -405,7 +404,7 @@ export default function ChatThreadPage() {
|
||||
.reduce((s, c) => s + (c.unread_count || 0), 0),
|
||||
}))
|
||||
navigate('/messages', { replace: true })
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
setShowLeave(false)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom'
|
||||
import PinPad from '../components/PinPad'
|
||||
import useAuthStore from '../store/authStore'
|
||||
import client from '../api/client'
|
||||
import { apiError } from '../api/errors'
|
||||
import { assetUrl, deliveryMode, getActiveVenue } from '../config/server'
|
||||
|
||||
|
||||
@@ -103,11 +104,11 @@ export default function LoginPage() {
|
||||
setLoading(true)
|
||||
try {
|
||||
// We send waiter id as identifier; backend matches by id+pin
|
||||
const { data } = await client.post('/api/auth/login-by-id', { waiter_id: selectedWaiter.id, pin })
|
||||
const { data } = await client.post('/api/auth/login-by-id', { waiter_id: selectedWaiter.id, pin }, { xenia: { ignoreUnauthorized: true } })
|
||||
login({ id: data.user.id, username: data.user.username, role: data.user.role }, data.access_token)
|
||||
navigate('/tables', { replace: true })
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Λανθασμένο PIN')
|
||||
setError(apiError(err, 'Λανθασμένο PIN'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ import { deliveryMode } from '../config/server'
|
||||
import { canRediscover, rediscover } from '../native/autoRediscover'
|
||||
import { useState } from 'react'
|
||||
|
||||
// Shown at /offline, and (plan step 4.1) instead of the whole app when the server can't be
|
||||
// reached on a start with no cached bootstrap (the app retries by itself and then opens the
|
||||
// screen the address asks for).
|
||||
export default function OfflinePage() {
|
||||
const [checking, setChecking] = useState(false)
|
||||
const [search, setSearch] = useState(null) // null | { done, total } | 'not-found'
|
||||
|
||||
@@ -812,12 +812,14 @@ function PloigisiTab() {
|
||||
|
||||
// ── Icon Navbar drag state ────────────────────────────────────────────────────
|
||||
const dragKey = useRef(null)
|
||||
const [dragging, setDragging] = useState(null) // drawn dimmed while dragged (refs aren't read in render)
|
||||
const touchDragKey = useRef(null)
|
||||
const itemRefs = useRef({})
|
||||
const [dropIndex, setDropIndex] = useState(null)
|
||||
|
||||
// ── Triple Pill drag state ────────────────────────────────────────────────────
|
||||
const triDragKey = useRef(null)
|
||||
const [triDragging, setTriDragging] = useState(null)
|
||||
const triTouchDragKey = useRef(null)
|
||||
const triItemRefs = useRef({})
|
||||
const [triDropIndex, setTriDropIndex] = useState(null)
|
||||
@@ -865,45 +867,45 @@ function PloigisiTab() {
|
||||
}
|
||||
|
||||
// ── Icon Navbar drag handlers ────────────────────────────────────────────────
|
||||
function onDragStart(key) { dragKey.current = key }
|
||||
function onDragStart(key) { dragKey.current = key; setDragging(key) }
|
||||
function onDragOverContainer(e, items) {
|
||||
e.preventDefault()
|
||||
setDropIndex(computeDropIndex(e.clientY, itemRefs, items))
|
||||
}
|
||||
function onDropContainer(items) {
|
||||
applyReorder(dragKey.current, dropIndex, items, setNavItems)
|
||||
dragKey.current = null; setDropIndex(null)
|
||||
dragKey.current = null; setDragging(null); setDropIndex(null)
|
||||
}
|
||||
function onDragEnd() { dragKey.current = null; setDropIndex(null) }
|
||||
function onTouchStart(e, key) { touchDragKey.current = key }
|
||||
function onDragEnd() { dragKey.current = null; setDragging(null); setDropIndex(null) }
|
||||
function onTouchStart(e, key) { touchDragKey.current = key; setDragging(key) }
|
||||
function onTouchMove(e, items) {
|
||||
e.preventDefault()
|
||||
setDropIndex(computeDropIndex(e.touches[0].clientY, itemRefs, items))
|
||||
}
|
||||
function onTouchEnd(items) {
|
||||
applyReorder(touchDragKey.current, dropIndex, items, setNavItems)
|
||||
touchDragKey.current = null; setDropIndex(null)
|
||||
touchDragKey.current = null; setDragging(null); setDropIndex(null)
|
||||
}
|
||||
|
||||
// ── Triple Pill drag handlers ────────────────────────────────────────────────
|
||||
function triOnDragStart(key) { triDragKey.current = key }
|
||||
function triOnDragStart(key) { triDragKey.current = key; setTriDragging(key) }
|
||||
function triOnDragOver(e, items) {
|
||||
e.preventDefault()
|
||||
setTriDropIndex(computeDropIndex(e.clientY, triItemRefs, items))
|
||||
}
|
||||
function triOnDrop(items) {
|
||||
applyReorder(triDragKey.current, triDropIndex, items, setTripleItems)
|
||||
triDragKey.current = null; setTriDropIndex(null)
|
||||
triDragKey.current = null; setTriDragging(null); setTriDropIndex(null)
|
||||
}
|
||||
function triOnDragEnd() { triDragKey.current = null; setTriDropIndex(null) }
|
||||
function triOnTouchStart(e, key) { triTouchDragKey.current = key }
|
||||
function triOnDragEnd() { triDragKey.current = null; setTriDragging(null); setTriDropIndex(null) }
|
||||
function triOnTouchStart(e, key) { triTouchDragKey.current = key; setTriDragging(key) }
|
||||
function triOnTouchMove(e, items) {
|
||||
e.preventDefault()
|
||||
setTriDropIndex(computeDropIndex(e.touches[0].clientY, triItemRefs, items))
|
||||
}
|
||||
function triOnTouchEnd(items) {
|
||||
applyReorder(triTouchDragKey.current, triDropIndex, items, setTripleItems)
|
||||
triTouchDragKey.current = null; setTriDropIndex(null)
|
||||
triTouchDragKey.current = null; setTriDragging(null); setTriDropIndex(null)
|
||||
}
|
||||
|
||||
const enabledItems = navItems.map(k => NAV_MAP[k]).filter(Boolean)
|
||||
@@ -978,7 +980,7 @@ function PloigisiTab() {
|
||||
border: '2px solid var(--accent)',
|
||||
background: 'var(--accent)18',
|
||||
cursor: 'grab', userSelect: 'none',
|
||||
opacity: (triDragKey.current === item.key || triTouchDragKey.current === item.key) ? 0.4 : 1,
|
||||
opacity: triDragging === item.key ? 0.4 : 1,
|
||||
transition: 'opacity 0.1s',
|
||||
}}
|
||||
>
|
||||
@@ -1080,7 +1082,7 @@ function PloigisiTab() {
|
||||
background: 'var(--accent)18',
|
||||
cursor: 'grab',
|
||||
userSelect: 'none',
|
||||
opacity: (dragKey.current === item.key || touchDragKey.current === item.key) ? 0.4 : 1,
|
||||
opacity: dragging === item.key ? 0.4 : 1,
|
||||
transition: 'opacity 0.1s',
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import AppShell from '../components/AppShell'
|
||||
import client from '../api/client'
|
||||
import { getVenueSettings } from '../api/venueSettings'
|
||||
|
||||
// ── helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -144,7 +145,7 @@ export default function ShiftOverviewPage() {
|
||||
|
||||
const { data: settings } = useQuery({
|
||||
queryKey: ['pos-settings'],
|
||||
queryFn: () => client.get('/api/settings/').then(r => r.data),
|
||||
queryFn: () => getVenueSettings().then(r => r.data),
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useEffect, useState, useRef, useCallback } from 'react'
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import OrderSummary from '../components/OrderSummary'
|
||||
import useAuthStore from '../store/authStore'
|
||||
import useConnectionStore from '../store/connectionStore'
|
||||
import client from '../api/client'
|
||||
import { apiError } from '../api/errors'
|
||||
import { getVenueSettings } from '../api/venueSettings'
|
||||
import db from '../db/posdb'
|
||||
import { queueOfflineSplit, queueOfflinePayment as queueOfflinePaymentOp } from '../services/offlineOrders'
|
||||
import { TransferIcon, MergeIcon, FlagsIcon, WaiterIcon, PrintIcon } from '../components/Icons'
|
||||
@@ -365,13 +366,13 @@ function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCance
|
||||
|
||||
// ─── Apply Discount modal ─────────────────────────────────────────────────────
|
||||
|
||||
function ApplyDiscountModal({ order, waiterId, onClose, onApplied }) {
|
||||
function ApplyDiscountModal({ order, _waiterId, onClose, onApplied }) {
|
||||
const activeItems = (order?.items ?? []).filter(i => i.status === 'active')
|
||||
const [selectedIds, setSelectedIds] = useState(activeItems.map(i => i.id))
|
||||
const [pct, setPct] = useState(10)
|
||||
const [note, setNote] = useState('')
|
||||
const [applying, setApplying] = useState(false)
|
||||
const [remaining, setRemaining] = useState(null) // { shift, workday }
|
||||
const [, setRemaining] = useState(null) // { shift, workday }
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const PCT_PRESETS = [5, 10, 15, 20, 25, 50, 100]
|
||||
@@ -406,7 +407,7 @@ function ApplyDiscountModal({ order, waiterId, onClose, onApplied }) {
|
||||
onApplied()
|
||||
onClose()
|
||||
} catch (e) {
|
||||
setError(e?.response?.data?.detail || 'Σφάλμα εφαρμογής έκπτωσης')
|
||||
setError(apiError(e, 'Σφάλμα εφαρμογής έκπτωσης'))
|
||||
} finally {
|
||||
setApplying(false)
|
||||
}
|
||||
@@ -546,7 +547,7 @@ function DiscountIcon({ width = 20, height = 20 }) {
|
||||
)
|
||||
}
|
||||
|
||||
function ActionsSheet({ order, tableId, isStandalone, onClose, onTransfer, onMerge, onSetFlags, onAssignWaiter, onPrintSynopsis, onCancelOrder, onMarkAllServed, canCancel, canDiscount, onApplyDiscount }) {
|
||||
function ActionsSheet({ order, _tableId, isStandalone, onClose, onTransfer, onMerge, onSetFlags, onAssignWaiter, onPrintSynopsis, onCancelOrder, onMarkAllServed, canCancel, canDiscount, onApplyDiscount }) {
|
||||
const hasOrder = !!order
|
||||
const hasServable = hasOrder && order.items?.some(i => i.kds_status === 'done')
|
||||
const hasActiveItems = hasOrder && order.items?.some(i => i.status === 'active')
|
||||
@@ -605,7 +606,7 @@ function ActionsSheet({ order, tableId, isStandalone, onClose, onTransfer, onMer
|
||||
|
||||
// ─── Table picker (for transfer / merge / move-items) ─────────────────────────
|
||||
|
||||
function TablePicker({ title, subtitle, tables, currentTableId, onSelect, onClose, loading }) {
|
||||
function TablePicker({ title, subtitle, tables, _currentTableId, onSelect, onClose, loading }) {
|
||||
return (
|
||||
<div className="modal-overlay modal-overlay--top" onClick={onClose}>
|
||||
<div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()}>
|
||||
@@ -651,7 +652,7 @@ function TablePicker({ title, subtitle, tables, currentTableId, onSelect, onClos
|
||||
|
||||
// ─── Flag picker ──────────────────────────────────────────────────────────────
|
||||
|
||||
function FlagPicker({ tableId, currentFlagIds, flagDefs, onSave, onClose, loading }) {
|
||||
function FlagPicker({ _tableId, currentFlagIds, flagDefs, onSave, onClose, loading }) {
|
||||
const [selected, setSelected] = useState(currentFlagIds || [])
|
||||
|
||||
// Sync selected when currentFlagIds loads
|
||||
@@ -1037,7 +1038,6 @@ export default function TableDetailPage() {
|
||||
const { tableId, orderId: standaloneOrderId } = useParams()
|
||||
const isStandalone = !!standaloneOrderId
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const { user } = useAuthStore()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [table, setTable] = useState(null)
|
||||
@@ -1226,7 +1226,7 @@ export default function TableDetailPage() {
|
||||
client.get('/api/pricing/discount-settings/me')
|
||||
.then(r => setCanDiscount(!!r.data.can_apply_discounts))
|
||||
.catch(() => {})
|
||||
client.get('/api/settings/')
|
||||
getVenueSettings()
|
||||
.then(r => {
|
||||
setCardEnabled(r.data?.['payments.card_enabled']?.value === 'true')
|
||||
setRevertAllowed(r.data?.['payments.waiter_revert_allowed']?.value === 'true')
|
||||
@@ -1322,7 +1322,7 @@ export default function TableDetailPage() {
|
||||
await client.post('/api/orders/', { table_id: Number(tableId) })
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα ανοίγματος')
|
||||
setError(apiError(err, 'Σφάλμα ανοίγματος'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1358,15 +1358,14 @@ export default function TableDetailPage() {
|
||||
if (res.data?.auto_closed || andClose) {
|
||||
if (andClose && !res.data?.auto_closed) {
|
||||
// Payment succeeded, now close the order explicitly
|
||||
try { await client.post(`/api/orders/${order.id}/close`) } catch {}
|
||||
try { await client.post(`/api/orders/${order.id}/close`) } catch { /* ignore */ }
|
||||
}
|
||||
navigate('/tables', { replace: true })
|
||||
return
|
||||
}
|
||||
await load()
|
||||
} catch (err) {
|
||||
const detail = err?.response?.data?.detail
|
||||
setError(detail ? `Σφάλμα πληρωμής: ${detail}` : 'Σφάλμα πληρωμής')
|
||||
setError(apiError(err, 'Σφάλμα πληρωμής'))
|
||||
} finally {
|
||||
setPaying(false)
|
||||
}
|
||||
@@ -1379,7 +1378,7 @@ export default function TableDetailPage() {
|
||||
setPaidSelectedIds([])
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα αναίρεσης πληρωμής')
|
||||
setError(apiError(err, 'Σφάλμα αναίρεσης πληρωμής'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1389,7 +1388,7 @@ export default function TableDetailPage() {
|
||||
setConfirmClose(false)
|
||||
navigate('/tables')
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα κλεισίματος')
|
||||
setError(apiError(err, 'Σφάλμα κλεισίματος'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1405,7 +1404,7 @@ export default function TableDetailPage() {
|
||||
setItemActionTarget(null)
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα ακύρωσης')
|
||||
setError(apiError(err, 'Σφάλμα ακύρωσης'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1415,7 +1414,7 @@ export default function TableDetailPage() {
|
||||
await client.delete(`/api/orders/${order.id}?print_cancellation=true`)
|
||||
navigate('/tables')
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα ακύρωσης παραγγελίας')
|
||||
setError(apiError(err, 'Σφάλμα ακύρωσης παραγγελίας'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1434,7 +1433,7 @@ export default function TableDetailPage() {
|
||||
setPaidSelectedIds([])
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα σήμανσης')
|
||||
setError(apiError(err, 'Σφάλμα σήμανσης'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1446,7 +1445,7 @@ export default function TableDetailPage() {
|
||||
await client.post(`/api/kds/orders/${order.id}/items/mark-all-served`)
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα σήμανσης')
|
||||
setError(apiError(err, 'Σφάλμα σήμανσης'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1493,7 +1492,7 @@ export default function TableDetailPage() {
|
||||
setSelectedIds([])
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα διαχωρισμού')
|
||||
setError(apiError(err, 'Σφάλμα διαχωρισμού'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1506,7 +1505,7 @@ export default function TableDetailPage() {
|
||||
await client.post(`/api/orders/${order.id}/transfer`, { target_table_id: targetTable.id })
|
||||
navigate('/tables')
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα μεταφοράς')
|
||||
setError(apiError(err, 'Σφάλμα μεταφοράς'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1521,7 +1520,7 @@ export default function TableDetailPage() {
|
||||
await client.post(`/api/orders/${order.id}/merge`, { target_order_id: targetOrder.id })
|
||||
navigate('/tables')
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα συγχώνευσης')
|
||||
setError(apiError(err, 'Σφάλμα συγχώνευσης'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1540,7 +1539,7 @@ export default function TableDetailPage() {
|
||||
setSelectedIds([])
|
||||
await load()
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || 'Σφάλμα μεταφοράς αντικειμένων')
|
||||
setError(apiError(err, 'Σφάλμα μεταφοράς αντικειμένων'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1778,7 +1777,7 @@ export default function TableDetailPage() {
|
||||
onClick={() => setShowMergeModal(true)}
|
||||
style={{
|
||||
width: 40, flexShrink: 0,
|
||||
borderRadius: 10, border: 'none', cursor: 'pointer',
|
||||
borderRadius: 10, cursor: 'pointer',
|
||||
background: mergeMode !== MERGE_OFF ? 'rgba(99,102,241,0.25)' : 'var(--bg2)',
|
||||
color: mergeMode !== MERGE_OFF ? '#a5b4fc' : 'var(--muted)',
|
||||
border: mergeMode !== MERGE_OFF ? '1px solid rgba(99,102,241,0.45)' : '1px solid var(--border)',
|
||||
@@ -2177,7 +2176,7 @@ export default function TableDetailPage() {
|
||||
if (order) {
|
||||
try {
|
||||
await client.patch(`/api/orders/${order.id}/customer-count`, { customer_count: v })
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}}
|
||||
onClose={() => setCustomerCountOpen(false)}
|
||||
|
||||
@@ -6,6 +6,7 @@ import useTableColourStore from '../store/tableColourStore'
|
||||
import useConnectionStore from '../store/connectionStore'
|
||||
import useTableViewStore from '../store/tableViewStore'
|
||||
import client from '../api/client'
|
||||
import { getVenueSettings } from '../api/venueSettings'
|
||||
import db from '../db/posdb'
|
||||
import { FlagsIcon, TransferIcon, MergeIcon, PrintIcon, WaiterIcon } from '../components/Icons'
|
||||
|
||||
@@ -111,7 +112,7 @@ function TableQuickModal({ table, order, flags, onClose, onNavigate, onAction, o
|
||||
<div style={{ background: 'var(--bg2)', borderRadius: '0 0 16px 16px', padding: '8px 20px 24px', borderTop: '2px solid var(--border)' }}>
|
||||
<p style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', letterSpacing: 1, marginBottom: 8, marginTop: 8 }}>ACTIONS</p>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
|
||||
{QUICK_ACTIONS.map((a, i) => {
|
||||
{QUICK_ACTIONS.map((a, _i) => {
|
||||
const disabled = !order && a.key !== 'flags'
|
||||
return (
|
||||
<button key={a.key} disabled={disabled} onClick={() => { onClose(); onAction(a.key) }} style={{
|
||||
@@ -306,7 +307,7 @@ export default function TableListPage() {
|
||||
const [flagDefs, setFlagDefs] = useState([])
|
||||
const [flagAssignments, setFlagAssignments] = useState([])
|
||||
const [waiters, setWaiters] = useState([]) // waiter objects for avatar lookup
|
||||
const [offline, setOffline] = useState(false)
|
||||
const [, setOffline] = useState(false)
|
||||
const [showFilters, setShowFilters] = useState(false)
|
||||
const [quickModal, setQuickModal] = useState(null)
|
||||
const [canCancel, setCanCancel] = useState(false)
|
||||
@@ -391,7 +392,7 @@ export default function TableListPage() {
|
||||
client.get('/api/tables/groups'),
|
||||
client.get('/api/flags/defs'),
|
||||
client.get('/api/flags/assignments'),
|
||||
client.get('/api/settings/'),
|
||||
getVenueSettings(),
|
||||
client.get('/api/waiters/on-shift'),
|
||||
])
|
||||
|
||||
@@ -452,14 +453,14 @@ export default function TableListPage() {
|
||||
setCancelConfirm(null)
|
||||
setQuickModal(null)
|
||||
load()
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
async function executeMarkAllServed(orderId) {
|
||||
try {
|
||||
await client.post(`/api/kds/orders/${orderId}/items/mark-all-served`)
|
||||
load()
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// ── SSE live updates ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -129,7 +129,6 @@ export async function queueOfflinePayment({ orderId, itemIds, paymentMethod }) {
|
||||
const offlineAt = new Date().toISOString()
|
||||
const seq = Date.now()
|
||||
|
||||
const allLocal = itemIds.every(id => String(id).startsWith('offline_item_'))
|
||||
const allReal = itemIds.every(id => typeof id === 'number' || !String(id).startsWith('offline_item_'))
|
||||
|
||||
if (allReal) {
|
||||
|
||||
@@ -4,7 +4,7 @@ function computeUnread(conversations) {
|
||||
return conversations.reduce((sum, c) => sum + (c.unread_count || 0), 0)
|
||||
}
|
||||
|
||||
const useChatStore = create((set, get) => ({
|
||||
const useChatStore = create((set, _get) => ({
|
||||
conversations: [],
|
||||
totalUnread: 0,
|
||||
// Messages cache: { [convId]: MessageOut[] } — newest first (API order)
|
||||
|
||||
@@ -34,7 +34,6 @@ const useConnectionStore = create((set, get) => ({
|
||||
|
||||
const graceTimer = setTimeout(() => {
|
||||
if (get().status !== 'reconnecting') return
|
||||
const lostAt = get().lostAt
|
||||
|
||||
// Start the 5-min flash timer
|
||||
const flashTimer = setTimeout(() => {
|
||||
|
||||
@@ -104,7 +104,7 @@ const useTableColourStore = create((set) => ({
|
||||
}
|
||||
set({ colours: merged })
|
||||
}
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
},
|
||||
}))
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { storageKey } from '../config/server'
|
||||
|
||||
const useTableViewStore = create(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
(set, _get) => ({
|
||||
density: '2x2',
|
||||
ownerFilter: 'all',
|
||||
statusFilter: 'all',
|
||||
|
||||
@@ -87,7 +87,7 @@ const useWaiterFavoritesStore = create(
|
||||
try {
|
||||
const res = await client.get('/api/auth/me/settings')
|
||||
existing = JSON.parse(res.data?.settings || '{}')
|
||||
} catch {}
|
||||
} catch { /* ignore */ }
|
||||
|
||||
const { favorites, quickNotes, itemFavorites } = get()
|
||||
const merged = { ...existing, [SETTINGS_KEY]: { favorites, quickNotes, itemFavorites } }
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// The waiter's cached bootstrap (plan step 4.1): offline it starts with the last bootstrap of
|
||||
// the same session only.
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { makeBootstrapCache } from '../src/logic/bootstrapCache.js'
|
||||
|
||||
function memory() {
|
||||
const m = new Map()
|
||||
return { getItem: k => (m.has(k) ? m.get(k) : null), setItem: (k, v) => m.set(k, String(v)) }
|
||||
}
|
||||
|
||||
test('the same session gets its saved bootstrap back; another session or none gets nothing', () => {
|
||||
const store = memory()
|
||||
const cache = makeBootstrapCache(store, () => 'xenia:site:bootstrap')
|
||||
assert.equal(cache.load('tok-a'), null)
|
||||
cache.save('tok-a', { user: { id: 7 }, permissions: ['ordering.orders.open'] })
|
||||
assert.deepEqual(cache.load('tok-a'), { user: { id: 7 }, permissions: ['ordering.orders.open'] })
|
||||
assert.equal(cache.load('tok-b'), null, "another waiter's session never sees it")
|
||||
assert.equal(cache.load(null), null)
|
||||
cache.save(null, { user: null })
|
||||
assert.deepEqual(cache.load(null), { user: null }, 'signed out: the anonymous bootstrap')
|
||||
assert.equal(cache.load('tok-a'), null)
|
||||
})
|
||||
|
||||
test('a damaged entry is ignored', () => {
|
||||
const store = memory()
|
||||
store.setItem('k', '{not json')
|
||||
assert.equal(makeBootstrapCache(store, () => 'k').load('t'), null)
|
||||
})
|
||||
Reference in New Issue
Block a user