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:
2026-11-16 11:37:47 +02:00
co-authored by Claude Opus 5.5
parent f85894a72e
commit 9f5498332a
41 changed files with 389 additions and 213 deletions
+1 -1
View File
@@ -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/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/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/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/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 | | `waiter_pwa/src/db/posdb`, `src/services/offlineOrders` | Offline cache and queued orders |
| `nginx-proxy/nginx.conf` | Proxy config used in dev / by hand | | `nginx-proxy/nginx.conf` | Proxy config used in dev / by hand |
+2
View File
@@ -9645,7 +9645,9 @@
"@capacitor/core": "8.6.2", "@capacitor/core": "8.6.2",
"@capgo/capacitor-updater": "8.54.2", "@capgo/capacitor-updater": "8.54.2",
"@tanstack/react-query": "^5.107.1", "@tanstack/react-query": "^5.107.1",
"@xenia/access": "^0.0.0",
"@xenia/api": "^0.0.0", "@xenia/api": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.21.1", "axios": "^1.21.1",
"dexie": "^4.4.7", "dexie": "^4.4.7",
+38 -13
View File
@@ -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. * 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 * autoRetryMs (unattended screens, e.g. the terminal): when the server can't be reached
* (offline or 5xx), retry by itself every autoRetryMs as well. * (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({ 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 () => { const load = useCallback(async () => {
try { const apply = async data => {
const { data } = await client.get('/api/platform/bootstrap', { xenia: { ignoreUnauthorized: true, noOverride: true } })
if (i18n) { if (i18n) {
await i18n.changeLanguage(resolveLanguage({ user: data.user?.language, device: deviceLanguage, venue: data.venue?.language })) 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]) useEffect(() => { load() }, [load])
const unreachable = !!state.error && (state.error.offline || state.error.status >= 500) const unreachable = !!state.error && (state.error.offline || state.error.status >= 500)
useEffect(() => { useEffect(() => {
if (!autoRetryMs || !unreachable) return undefined const every = state.offline ? (autoRetryMs || CACHE_RETRY_MS) : unreachable ? autoRetryMs : 0
const id = setTimeout(load, autoRetryMs) if (!every) return undefined
const id = setTimeout(load, every)
return () => clearTimeout(id) return () => clearTimeout(id)
}, [autoRetryMs, unreachable, state.error, load]) }, [autoRetryMs, unreachable, state.offline, state.error, load])
const value = useMemo(() => { const value = useMemo(() => {
const d = state.data const d = state.data
@@ -62,9 +86,10 @@ export function AccessProvider({
language: d.language, language: d.language,
modules: new Set((d.modules || []).map(m => m.key)), modules: new Set((d.modules || []).map(m => m.key)),
permissions: new Set(d.permissions || []), permissions: new Set(d.permissions || []),
offline: state.offline, // running on the cached bootstrap (cache prop)
refresh: load, refresh: load,
} }
}, [state.data, load]) }, [state.data, state.offline, load])
const current = state.forToken === token const current = state.forToken === token
let content let content
@@ -76,7 +101,7 @@ export function AccessProvider({
</AccessContext.Provider> </AccessContext.Provider>
) )
} else if (state.error && current) { } else if (state.error && current) {
content = <LoadFailed error={state.error} retry={load} /> content = failed?.(state.error, load) ?? <LoadFailed error={state.error} retry={load} />
} else { } else {
content = loading === undefined ? <DefaultLoading /> : loading content = loading === undefined ? <DefaultLoading /> : loading
} }
+13 -8
View File
@@ -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 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)})`) await v.evaluate(`localStorage.setItem('xenia:test-site-1:token', ${JSON.stringify(token)})`)
v = await reloadApp(v) 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) => { 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`) } }) 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) v = await stale(v)
r.check('logged in: server "moved" → found and saved', !!(await found())) 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 onScreen(async vv =>
r.check('logged in: back on /tables, live', (await v.evaluate('location.pathname')) === '/tables' && (await connectivityColor(v)) === GREEN) (await vv.evaluate('location.pathname')) === '/tables' && (await connectivityColor(vv)) === GREEN, 40_000)))
await v.evaluate("localStorage.removeItem('xenia:test-site-1:token')") await v.evaluate("localStorage.removeItem('xenia:test-site-1:token')")
v = await stale(v) v = await stale(v)
r.check('logged out: found and saved', !!(await found())) 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 onScreen(async vv =>
r.check('logged out: waiter list loads from the new address', (await v.evaluate('document.body.innerText')).includes('Manager')) (await vv.evaluate('document.body.innerText')).includes('Manager'), 40_000)))
await backend.stop() await backend.stop()
v = await stale(v) 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: 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()") 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) 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) r.check('manual search ends with "not found" guidance', !!notFound)
@@ -196,7 +201,7 @@ async function rediscovery() {
await sleep(12000) await sleep(12000)
r.check('cold start with the server down: still logged in', await v.evaluate("!!localStorage.getItem('xenia:test-site-1:token')")) 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 }) 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) r.check('server back → app lands on /tables by itself', !!recovered)
v.close() v.close()
} finally { } finally {
+11
View File
@@ -57,6 +57,17 @@ try {
r1.check(`${m.name}: IndexedDB "${m.db}"`, dbs.includes(m.db), dbs.join(',')) 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) 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('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() await page.context().close()
} }
failures += r1.done() failures += r1.done()
+1
View File
@@ -9,6 +9,7 @@ const shell = process.platform === 'win32'
const suites = [ const suites = [
['unit: local_backend (pytest)', PYTHON, ['-m', 'pytest', 'tests', '-q'], BACKEND], ['unit: local_backend (pytest)', PYTHON, ['-m', 'pytest', 'tests', '-q'], BACKEND],
['unit: waiter_pwa (node --test)', 'npm', ['test', '--silent'], WAITER], ['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/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/i18n (node --test + guard)', 'npm', ['test', '--silent', '-w', '@xenia/i18n'], CS],
['unit: packages/api (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/api'], CS], ['unit: packages/api (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/api'], CS],
+1
View File
@@ -695,6 +695,7 @@ try {
// its own address for the pairing rate limit (one per screen in a real venue) // 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()) 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 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)', 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 shown(myDisplay, 'display-idle', 15_000) && (await myDisplay.getByTestId('display-name').textContent()) === 'Taverna E2E')
await simpleCard.locator('button').first().click() await simpleCard.locator('button').first().click()
+6 -1
View File
@@ -23,7 +23,12 @@ export default defineConfig([
}, },
}, },
rules: { 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'] }],
}, },
}, },
]) ])
+2
View File
@@ -19,7 +19,9 @@
"@capacitor/core": "8.6.2", "@capacitor/core": "8.6.2",
"@capgo/capacitor-updater": "8.54.2", "@capgo/capacitor-updater": "8.54.2",
"@tanstack/react-query": "^5.107.1", "@tanstack/react-query": "^5.107.1",
"@xenia/access": "^0.0.0",
"@xenia/api": "^0.0.0", "@xenia/api": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.21.1", "axios": "^1.21.1",
"dexie": "^4.4.7", "dexie": "^4.4.7",
+43 -36
View File
@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { BrowserRouter, Routes, Route, Navigate, Outlet, useNavigate } from 'react-router-dom' import { BrowserRouter, Routes, Route, Navigate, Outlet, useNavigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { AccessProvider, useAccess, useCan } from '@xenia/access'
import { i18n } from './i18n'
import useAuthStore from './store/authStore' import useAuthStore from './store/authStore'
import useShiftStore from './store/shiftStore' import useShiftStore from './store/shiftStore'
import useThemeStore from './store/themeStore' import useThemeStore from './store/themeStore'
@@ -8,6 +10,9 @@ import useTableColourStore from './store/tableColourStore'
import useConnectionStore from './store/connectionStore' import useConnectionStore from './store/connectionStore'
import useWaiterFavoritesStore from './store/waiterFavoritesStore' import useWaiterFavoritesStore from './store/waiterFavoritesStore'
import client from './api/client' 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 LoginPage from './pages/LoginPage'
import TableListPage from './pages/TableListPage' import TableListPage from './pages/TableListPage'
import TableDetailPage from './pages/TableDetailPage' import TableDetailPage from './pages/TableDetailPage'
@@ -111,7 +116,7 @@ function StartShiftScreen({ username, onStart, onLogout }) {
try { try {
await onStart(startingCash ? parseFloat(startingCash) : null) await onStart(startingCash ? parseFloat(startingCash) : null)
} catch (e) { } catch (e) {
setError(e.response?.data?.detail || 'Σφάλμα εκκίνησης βάρδιας') setError(apiError(e, 'Σφάλμα εκκίνησης βάρδιας'))
setStarting(false) setStarting(false)
} }
} }
@@ -173,15 +178,13 @@ function AppLayout() {
const { token, user, logout } = useAuthStore() const { token, user, logout } = useAuthStore()
const navigate = useNavigate() const navigate = useNavigate()
const { const {
shift, businessDay,
setShift, setBusinessDay, setShift, setBusinessDay,
setSelfStartAllowed, setSelfEndAllowed, setSelfStartAllowed, setSelfEndAllowed,
gateStatus, setGateStatus, gateStatus, setGateStatus,
} = useShiftStore() } = useShiftStore()
// People with the manager dashboard work without a shift of their own (plan 4.1: the key,
if (!token) return <Navigate to="/login" replace /> // not the role name)
const isManager = useCan('core.dashboard.access')
const isManager = user?.role && user.role !== 'waiter'
async function checkGate() { async function checkGate() {
if (!user) return if (!user) return
@@ -203,7 +206,7 @@ function AppLayout() {
// No active shift — check self-start setting // No active shift — check self-start setting
try { try {
const settingsRes = await client.get('/api/settings/') const settingsRes = await getVenueSettings()
const canStart = settingsRes.data?.['shifts.waiter_self_start']?.value !== 'false' const canStart = settingsRes.data?.['shifts.waiter_self_start']?.value !== 'false'
const canEnd = settingsRes.data?.['shifts.waiter_self_end']?.value !== 'false' const canEnd = settingsRes.data?.['shifts.waiter_self_end']?.value !== 'false'
setSelfStartAllowed(canStart) setSelfStartAllowed(canStart)
@@ -222,7 +225,7 @@ function AppLayout() {
useEffect(() => { useEffect(() => {
if (user) checkGate() 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 // Poll every 15s to detect shift-end or business-day-close triggered by manager
useEffect(() => { useEffect(() => {
@@ -241,7 +244,7 @@ function AppLayout() {
} }
}, 15_000) }, 15_000)
return () => clearInterval(id) 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) { async function handleStartShift(startingCash) {
const res = await client.post('/api/shifts/start', { starting_cash: startingCash }) const res = await client.post('/api/shifts/start', { starting_cash: startingCash })
@@ -254,6 +257,7 @@ function AppLayout() {
navigate('/login') navigate('/login')
} }
if (!token) return <Navigate to="/login" replace />
if (!user || gateStatus === 'loading') return <Spinner /> if (!user || gateStatus === 'loading') return <Spinner />
if (gateStatus === 'closed') return <ClosedScreen onRefresh={checkGate} onLogout={handleLogout} /> if (gateStatus === 'closed') return <ClosedScreen onRefresh={checkGate} onLogout={handleLogout} />
@@ -273,34 +277,17 @@ function AppLayout() {
// ─── Global helpers ─────────────────────────────────────────────────────────── // ─── 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() { function AuthRehydrator() {
const { token, user, login, logout } = useAuthStore() const { token, user, login, logout } = useAuthStore()
const access = useAccess()
useEffect(() => { useEffect(() => {
if (!token || user) return if (!token || user) return
let cancelled = false if (access.user) login(access.user, token)
let timer = null else if (!access.offline) logout()
async function load() { }, [token, user, access.user, access.offline, login, logout])
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])
return null return null
} }
@@ -376,7 +363,7 @@ function AndroidBackGuard() {
function ColourLoader() { function ColourLoader() {
const loadFromBackend = useTableColourStore(s => s.loadFromBackend) const loadFromBackend = useTableColourStore(s => s.loadFromBackend)
useEffect(() => { useEffect(() => {
client.get('/api/settings/') getVenueSettings()
.then(r => { .then(r => {
const raw = r.data?.['ui.table_colours']?.value const raw = r.data?.['ui.table_colours']?.value
if (raw) loadFromBackend(raw) if (raw) loadFromBackend(raw)
@@ -432,7 +419,29 @@ export default function App() {
if (deliveryMode() === 'native' && !getActiveVenue()) { if (deliveryMode() === 'native' && !getActiveVenue()) {
return <VenuesPage firstRun /> 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 ( return (
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<BrowserRouter> <BrowserRouter>
@@ -448,8 +457,6 @@ export default function App() {
{/* Native builds ship their UI in the app bundle — no service worker to update */} {/* Native builds ship their UI in the app bundle — no service worker to update */}
{deliveryMode() !== 'native' && <UpdatePrompt />} {deliveryMode() !== 'native' && <UpdatePrompt />}
<InstallAppDialog /> <InstallAppDialog />
{deliveryMode() === 'native' && <ServerRediscovery />}
{deliveryMode() === 'native' && <BundleSync />}
<Routes> <Routes>
<Route path="/login" element={<LoginGuard><LoginPage /></LoginGuard>} /> <Route path="/login" element={<LoginGuard><LoginPage /></LoginGuard>} />
<Route path="/offline" element={<OfflinePage />} /> <Route path="/offline" element={<OfflinePage />} />
+8
View File
@@ -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'))
+21 -20
View File
@@ -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 axios from 'axios'
import { createApiClient } from '@xenia/api'
import { apiBase, storageKey } from '../config/server' import { apiBase, storageKey } from '../config/server'
const client = axios.create({ baseURL: apiBase() }) const client = createApiClient({
axios,
client.interceptors.request.use(config => { baseURL: () => apiBase(),
const token = localStorage.getItem(storageKey('token')) getToken: () => localStorage.getItem(storageKey('token')),
if (token) config.headers.Authorization = `Bearer ${token}` // No answer at all: the connectivity bar and the rediscovery scan listen for this
return config 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'
},
}) })
client.interceptors.response.use( // Dev builds only: lets the e2e suites drive requests through this client
res => res, if (import.meta.env.DEV) window.__xeniaClient = client
err => {
if (!err.response) {
window.dispatchEvent(new Event('backend-offline'))
} else if (err.response.status === 401) {
// Token expired or user blocked — force logout
localStorage.removeItem(storageKey('token'))
localStorage.removeItem(storageKey('savedUsername'))
window.location.href = '/login'
}
return Promise.reject(err)
}
)
export default client export default client
+12
View File
@@ -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
}
+39
View File
@@ -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 -1
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom' import { useNavigate, useLocation } from 'react-router-dom'
import UserMenu from './UserMenu' import UserMenu from './UserMenu'
import { useNotifications } from '../context/NotificationContext' import { useNotifications } from '../context/NotificationContext'
@@ -15,7 +15,6 @@ export default function ConnectivityBar() {
const isOnline = status === 'online' const isOnline = status === 'online'
const isReconnecting = status === 'reconnecting' const isReconnecting = status === 'reconnecting'
const isOffline = status === 'offline'
const color = isOnline const color = isOnline
? (liveAlive ? '#22c55e' : '#3b82f6') ? (liveAlive ? '#22c55e' : '#3b82f6')
+52 -53
View File
@@ -1,16 +1,10 @@
import { useState, useEffect, useCallback, useRef } from 'react' import { useState, useEffect, useRef } from 'react'
import useWaiterFavoritesStore from '../store/waiterFavoritesStore' import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
import client from '../api/client' import { getVenueSettings } from '../api/venueSettings'
import { assetUrl } from '../config/server' import { assetUrl } from '../config/server'
// ── Helpers ────────────────────────────────────────────────────────────────── // ── Helpers ──────────────────────────────────────────────────────────────────
function fmt(n) {
if (n === 0) return ''
const s = n > 0 ? `+${n.toFixed(2)} €` : `${n.toFixed(2)} €`
return s
}
function buildInitialState(product) { function buildInitialState(product) {
const preferenceSets = product.preference_sets || [] const preferenceSets = product.preference_sets || []
@@ -445,7 +439,7 @@ function FavoritesTab({ product, waiterOverride, quickState, setQuickState, extr
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{favorites.map((fav, fi) => { {favorites.map((fav, _fi) => {
if (fav.type === 'quick') { if (fav.type === 'quick') {
return <QuickOptionRow key={`quick-${fav.item.id}`} opt={fav.item} quickState={quickState} setQuickState={setQuickState} compact={false} /> return <QuickOptionRow key={`quick-${fav.item.id}`} opt={fav.item} quickState={quickState} setQuickState={setQuickState} compact={false} />
} }
@@ -931,49 +925,54 @@ function NotesTab({ note, setNote, quickNotes = FALLBACK_QUICK_NOTES }) {
// ── Tab: Summary ────────────────────────────────────────────────────────────── // ── Tab: Summary ──────────────────────────────────────────────────────────────
function SummaryTab({ product, summaryLines, note, onJumpTab }) { /** 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>
<button onClick={() => onJumpTab(tab)} style={{ background: 'none', border: 'none', fontSize: 12, fontWeight: 700, color: '#f59e0b', cursor: 'pointer', textTransform: 'uppercase', letterSpacing: 0.6 }}>Αλλαγή</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{lines.map((l, i) => (
<div key={i} style={{ padding: '10px 14px', background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10, minHeight: 44 }}>
<div style={{ flex: 1 }}>
{l.group === 'prefs' ? (
<>
<div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 2 }}>{l.label}</div>
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>{l.value}</div>
</>
) : l.group === 'removed' ? (
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
Χωρίς {l.label}
</div>
) : l.group === 'extras' ? (
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
{l.label}
{l.subName && <span> · {l.subName}</span>}
{l.qty > 1 && <span style={{ color: 'var(--muted)', marginLeft: 6, fontVariantNumeric: 'tabular-nums' }}>×{l.qty}</span>}
</div>
) : (
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
{l.qty > 1 && <span style={{ color: 'var(--muted)', marginRight: 6, fontVariantNumeric: 'tabular-nums' }}>{l.qty}×</span>}
{l.label}
</div>
)}
</div>
{l.price !== 0 && <div style={{ fontSize: 13, fontWeight: 600, color: l.price < 0 ? 'var(--danger)' : 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{l.price > 0 ? '+' : ''}{l.price.toFixed(2)} €</div>}
</div>
))}
</div>
</div>
)
}
function SummaryTab({ _product, summaryLines, note, onJumpTab }) {
const isEmpty = summaryLines.length === 0 && !note const isEmpty = summaryLines.length === 0 && !note
const byGroup = { quick: [], extras: [], removed: [], prefs: [] } const byGroup = { quick: [], extras: [], removed: [], prefs: [] }
summaryLines.forEach(l => byGroup[l.group]?.push(l)) summaryLines.forEach(l => byGroup[l.group]?.push(l))
const Section = ({ title, tab, lines }) => lines.length === 0 ? null : (
<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>
<button onClick={() => onJumpTab(tab)} style={{ background: 'none', border: 'none', fontSize: 12, fontWeight: 700, color: '#f59e0b', cursor: 'pointer', textTransform: 'uppercase', letterSpacing: 0.6 }}>Αλλαγή</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{lines.map((l, i) => (
<div key={i} style={{ padding: '10px 14px', background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10, minHeight: 44 }}>
<div style={{ flex: 1 }}>
{l.group === 'prefs' ? (
<>
<div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 2 }}>{l.label}</div>
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>{l.value}</div>
</>
) : l.group === 'removed' ? (
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
Χωρίς {l.label}
</div>
) : l.group === 'extras' ? (
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
{l.label}
{l.subName && <span> · {l.subName}</span>}
{l.qty > 1 && <span style={{ color: 'var(--muted)', marginLeft: 6, fontVariantNumeric: 'tabular-nums' }}>×{l.qty}</span>}
</div>
) : (
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>
{l.qty > 1 && <span style={{ color: 'var(--muted)', marginRight: 6, fontVariantNumeric: 'tabular-nums' }}>{l.qty}×</span>}
{l.label}
</div>
)}
</div>
{l.price !== 0 && <div style={{ fontSize: 13, fontWeight: 600, color: l.price < 0 ? 'var(--danger)' : 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{l.price > 0 ? '+' : ''}{l.price.toFixed(2)} €</div>}
</div>
))}
</div>
</div>
)
return ( return (
<div> <div>
@@ -983,10 +982,10 @@ function SummaryTab({ product, summaryLines, note, onJumpTab }) {
</div> </div>
) : ( ) : (
<> <>
<Section title="Προτιμήσεις" tab="prefs" lines={byGroup.prefs} /> <Section title="Προτιμήσεις" tab="prefs" lines={byGroup.prefs} onJumpTab={onJumpTab} />
<Section title="Γρήγορες Επιλογές" tab="quick" lines={byGroup.quick} /> <Section title="Γρήγορες Επιλογές" tab="quick" lines={byGroup.quick} onJumpTab={onJumpTab} />
<Section title="Extras" tab="extras" lines={byGroup.extras} /> <Section title="Extras" tab="extras" lines={byGroup.extras} onJumpTab={onJumpTab} />
<Section title="Αφαιρέθηκαν" tab="ingredients" lines={byGroup.removed} /> <Section title="Αφαιρέθηκαν" tab="ingredients" lines={byGroup.removed} onJumpTab={onJumpTab} />
{note && ( {note && (
<div style={{ marginBottom: 20 }}> <div style={{ marginBottom: 20 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 2px 8px' }}> <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) const [priceAdjAllowed, setPriceAdjAllowed] = useState(false)
useEffect(() => { useEffect(() => {
client.get('/api/settings/') getVenueSettings()
.then(r => setPriceAdjAllowed(r.data?.['orders.waiter_price_adjust_allowed']?.value === 'true')) .then(r => setPriceAdjAllowed(r.data?.['orders.waiter_price_adjust_allowed']?.value === 'true'))
.catch(() => {}) .catch(() => {})
}, []) }, [])
+1 -2
View File
@@ -208,7 +208,7 @@ const PRICING_EVENT_STYLE = {
deal_offer_accepted: { color: '#4ade80', label: null }, // label from deal_name 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 => const rows = events.filter(ev =>
ev.event_type === 'modifier_applied' || ev.event_type === 'modifier_applied' ||
ev.event_type === 'waiter_discount' || 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 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 label = ev.modifier_name || ev.deal_name || evStyle.label || ev.event_type
const delta = ev.delta_amount const delta = ev.delta_amount
const afterPrice = ev.price_after
return ( return (
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 7 }}> <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
+1 -1
View File
@@ -181,7 +181,7 @@ function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
const onDetail = useCallback(() => onShowDetail(product), [onShowDetail, product]) const onDetail = useCallback(() => onShowDetail(product), [onShowDetail, product])
const longPress = useLongPress(onDetail, 1200) const longPress = useLongPress(onDetail, 1200)
function handleClick(e) { function handleClick(_e) {
// If a long-press just fired, don't open the drawer // If a long-press just fired, don't open the drawer
if (longPress.didFire()) return if (longPress.didFire()) return
onOpen(product) onOpen(product)
+5 -6
View File
@@ -51,7 +51,6 @@ function computeKdsBadge(order) {
if (!order?.items) return null if (!order?.items) return null
const relevant = order.items.filter(i => i.status !== 'cancelled' && kds(i.kds_status) !== 'served') const relevant = order.items.filter(i => i.status !== 'cancelled' && kds(i.kds_status) !== 'served')
if (relevant.length === 0) return null 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 preparing = relevant.filter(i => kds(i.kds_status) === 'preparing').length
const done = relevant.filter(i => kds(i.kds_status) === 'done').length const done = relevant.filter(i => kds(i.kds_status) === 'done').length
const total = relevant.length const total = relevant.length
@@ -282,7 +281,7 @@ function Amount({ value, size = 22, color }) {
// ─── Card variants ──────────────────────────────────────────────────────────── // ─── Card variants ────────────────────────────────────────────────────────────
// 1x1 — square-ish, 4 per row. Badges top (up to 2 + +N), name center, KDS badge bottom (replaces status). // 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 ( return (
<div style={{ <div style={{
width: '100%', aspectRatio: '1 / 1.05', 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. // 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 ( return (
<div style={{ <div style={{
width: '100%', height: 64, 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. // 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 isFree = !order
const total = order?.items?.filter(i => i.status === 'active').reduce((s, i) => s + i.unit_price * i.quantity, 0) ?? 0 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. // 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 isFree = !order
const total = order?.items?.filter(i => i.status === 'active').reduce((s, i) => s + i.unit_price * i.quantity, 0) ?? 0 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. // 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 isFree = !order
const activeItems = order?.items?.filter(i => i.status === 'active') ?? [] const activeItems = order?.items?.filter(i => i.status === 'active') ?? []
const total = activeItems.reduce((s, i) => s + i.unit_price * i.quantity, 0) const total = activeItems.reduce((s, i) => s + i.unit_price * i.quantity, 0)
+3 -1
View File
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { useCan } from '@xenia/access'
import useAuthStore from '../store/authStore' import useAuthStore from '../store/authStore'
import useShiftStore from '../store/shiftStore' import useShiftStore from '../store/shiftStore'
import useThemeStore from '../store/themeStore' import useThemeStore from '../store/themeStore'
@@ -46,8 +47,9 @@ export default function UserMenu() {
navigate('/login') navigate('/login')
} }
const canDashboard = useCan('core.dashboard.access')
const activeBreak = shift?.breaks?.find(b => !b.ended_at) 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() { async function handleEndShift() {
if (!window.confirm('Να τελειώσει η βάρδια σου;')) return if (!window.confirm('Να τελειώσει η βάρδια σου;')) return
+1 -1
View File
@@ -164,7 +164,7 @@ export function LiveProvider({ children }) {
...o, ...o,
waiter_ids: o.waiters?.map(w => w.waiter_id) ?? [], waiter_ids: o.waiters?.map(w => w.waiter_id) ?? [],
}) })
} catch {} } catch { /* ignore */ }
useKdsReadyStore.getState().refresh() useKdsReadyStore.getState().refresh()
break break
} }
@@ -164,7 +164,7 @@ export function NotificationProvider({ children }) {
try { try {
const res = await client.get('/api/notifications/recent?limit=10') const res = await client.get('/api/notifications/recent?limit=10')
setRecentMessages(res.data) setRecentMessages(res.data)
} catch { } } catch { /* ignore */ }
}, [token, user?.id]) }, [token, user?.id])
// Initial load + 5s fallback poll (SSE is primary, poll is safety net) // 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`) await client.post(`/api/notifications/${messageId}/ack`)
setPendingMessages(prev => prev.filter(m => m.id !== messageId)) setPendingMessages(prev => prev.filter(m => m.id !== messageId))
fetchRecent() fetchRecent()
} catch { } } catch { /* ignore */ }
} }
// Mark all pending as read (used when notification panel opens in never-popup mode) // Mark all pending as read (used when notification panel opens in never-popup mode)
+4
View File
@@ -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
View File
@@ -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 }))
},
}
}
+7 -5
View File
@@ -4,6 +4,8 @@ import ProductPicker from '../components/ProductPicker'
import OrderDrawer from '../components/OrderDrawer' import OrderDrawer from '../components/OrderDrawer'
import OrderSummaryModal from '../components/OrderSummaryModal' import OrderSummaryModal from '../components/OrderSummaryModal'
import client from '../api/client' import client from '../api/client'
import { apiError } from '../api/errors'
import { getVenueSettings } from '../api/venueSettings'
import db from '../db/posdb' import db from '../db/posdb'
import { useProductCache } from '../hooks/useProductCache' import { useProductCache } from '../hooks/useProductCache'
import useOrderingSettingsStore from '../store/orderingSettingsStore' import useOrderingSettingsStore from '../store/orderingSettingsStore'
@@ -195,14 +197,14 @@ export default function AddItemsPage() {
_key: Date.now() + Math.random(), _key: Date.now() + Math.random(),
})) }))
setCart(initialCart) setCart(initialCart)
} catch {} } catch { /* ignore */ }
} }
} }
load() load()
}, [tableId, isStandalone, orderType]) }, [tableId, isStandalone, orderType])
useEffect(() => { useEffect(() => {
client.get('/api/settings/').then(r => { getVenueSettings().then(r => {
const s = r.data const s = r.data
if (s?.['orders.courses_enabled']?.value === 'true') { if (s?.['orders.courses_enabled']?.value === 'true') {
try { setCourses(JSON.parse(s?.['orders.courses']?.value || '[]')) } catch { /* ignore */ } try { setCourses(JSON.parse(s?.['orders.courses']?.value || '[]')) } catch { /* ignore */ }
@@ -348,7 +350,7 @@ export default function AddItemsPage() {
setTimeout(() => navigate('/tables'), 1200) setTimeout(() => navigate('/tables'), 1200)
} }
} catch (err) { } catch (err) {
setError(err.response?.data?.detail || 'Σφάλμα αποστολής — η παραγγελία δεν στάλθηκε') setError(apiError(err, 'Σφάλμα αποστολής — η παραγγελία δεν στάλθηκε'))
} finally { } finally {
setSending(false) setSending(false)
} }
@@ -685,7 +687,7 @@ export default function AddItemsPage() {
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}> <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' }}> <div key={group.course?.id ?? '__none__'} style={{ position: 'relative' }}>
{/* Colored left accent bar */} {/* Colored left accent bar */}
<div style={{ <div style={{
@@ -949,7 +951,7 @@ export default function AddItemsPage() {
// ── Deal Offer Modal ────────────────────────────────────────────────────────── // ── Deal Offer Modal ──────────────────────────────────────────────────────────
function DealOfferModal({ offer, products, onAccept, onDismiss }) { function DealOfferModal({ offer, _products, onAccept, onDismiss }) {
const isFreeItem = offer.action_type === 'free_item' const isFreeItem = offer.action_type === 'free_item'
const isFreeChoice = offer.action_type === 'free_choice' const isFreeChoice = offer.action_type === 'free_choice'
const isDiscount = ['set_price','add_amount','add_percent','apply_modifier'].includes(offer.action_type) const isDiscount = ['set_price','add_amount','add_percent','apply_modifier'].includes(offer.action_type)
+4 -4
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import client from '../api/client' import client from '../api/client'
import { apiError } from '../api/errors'
import useAuthStore from '../store/authStore' import useAuthStore from '../store/authStore'
import useChatStore from '../store/chatStore' import useChatStore from '../store/chatStore'
@@ -53,7 +54,6 @@ function Avatar({ label, size = 44, isGroup = false }) {
function ConvRow({ conv, currentUserId, onClick }) { function ConvRow({ conv, currentUserId, onClick }) {
const isGroup = conv.type === 'group' const isGroup = conv.type === 'group'
const isDirect = conv.type === 'direct'
const title = isGroup const title = isGroup
? (conv.name || 'Ομάδα') ? (conv.name || 'Ομάδα')
@@ -74,7 +74,7 @@ function ConvRow({ conv, currentUserId, onClick }) {
onClick={onClick} onClick={onClick}
style={{ style={{
display: 'flex', alignItems: 'center', gap: 12, 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)', background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
width: '100%', textAlign: 'left', cursor: 'pointer', width: '100%', textAlign: 'left', cursor: 'pointer',
}} }}
@@ -150,7 +150,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
}) })
onConversationCreated(res.data) onConversationCreated(res.data)
} catch (e) { } catch (e) {
setError(e.response?.data?.detail || 'Σφάλμα δημιουργίας συνομιλίας') setError(apiError(e, 'Σφάλμα δημιουργίας συνομιλίας'))
setCreating(false) setCreating(false)
} }
} }
@@ -167,7 +167,7 @@ function NewChatDrawer({ currentUserId, onClose, onConversationCreated }) {
}) })
onConversationCreated(res.data) onConversationCreated(res.data)
} catch (e) { } catch (e) {
setError(e.response?.data?.detail || 'Σφάλμα δημιουργίας ομάδας') setError(apiError(e, 'Σφάλμα δημιουργίας ομάδας'))
setCreating(false) setCreating(false)
} }
} }
+4 -5
View File
@@ -203,7 +203,6 @@ export default function ChatThreadPage() {
const displayMessages = [...rawMessages].reverse() const displayMessages = [...rawMessages].reverse()
const isGroup = conv?.type === 'group' const isGroup = conv?.type === 'group'
const isDirect = conv?.type === 'direct'
const title = isGroup const title = isGroup
? (conv?.name || 'Ομάδα') ? (conv?.name || 'Ομάδα')
@@ -215,7 +214,7 @@ export default function ChatThreadPage() {
try { try {
await client.post(`/api/chat/conversations/${conversationId}/read`) await client.post(`/api/chat/conversations/${conversationId}/read`)
markConvRead(conversationId) markConvRead(conversationId)
} catch {} } catch { /* ignore */ }
}, [conversationId, markConvRead]) }, [conversationId, markConvRead])
// ── Initial load ───────────────────────────────────────────────────────────── // ── Initial load ─────────────────────────────────────────────────────────────
@@ -229,7 +228,7 @@ export default function ChatThreadPage() {
try { try {
const r = await client.get(`/api/chat/conversations/${conversationId}`) const r = await client.get(`/api/chat/conversations/${conversationId}`)
if (!cancelled) upsertConversation(r.data) if (!cancelled) upsertConversation(r.data)
} catch {} } catch { /* ignore */ }
} }
// Load first page of messages // Load first page of messages
@@ -287,7 +286,7 @@ export default function ChatThreadPage() {
el.scrollTop = el.scrollHeight - prevScrollHeight + prevScrollTop el.scrollTop = el.scrollHeight - prevScrollHeight + prevScrollTop
} }
}) })
} catch {} } catch { /* ignore */ }
setLoadingMore(false) setLoadingMore(false)
} }
@@ -405,7 +404,7 @@ export default function ChatThreadPage() {
.reduce((s, c) => s + (c.unread_count || 0), 0), .reduce((s, c) => s + (c.unread_count || 0), 0),
})) }))
navigate('/messages', { replace: true }) navigate('/messages', { replace: true })
} catch {} } catch { /* ignore */ }
setShowLeave(false) setShowLeave(false)
} }
+3 -2
View File
@@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom'
import PinPad from '../components/PinPad' import PinPad from '../components/PinPad'
import useAuthStore from '../store/authStore' import useAuthStore from '../store/authStore'
import client from '../api/client' import client from '../api/client'
import { apiError } from '../api/errors'
import { assetUrl, deliveryMode, getActiveVenue } from '../config/server' import { assetUrl, deliveryMode, getActiveVenue } from '../config/server'
@@ -103,11 +104,11 @@ export default function LoginPage() {
setLoading(true) setLoading(true)
try { try {
// We send waiter id as identifier; backend matches by id+pin // 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) login({ id: data.user.id, username: data.user.username, role: data.user.role }, data.access_token)
navigate('/tables', { replace: true }) navigate('/tables', { replace: true })
} catch (err) { } catch (err) {
setError(err.response?.data?.detail || 'Λανθασμένο PIN') setError(apiError(err, 'Λανθασμένο PIN'))
} finally { } finally {
setLoading(false) setLoading(false)
} }
+3
View File
@@ -3,6 +3,9 @@ import { deliveryMode } from '../config/server'
import { canRediscover, rediscover } from '../native/autoRediscover' import { canRediscover, rediscover } from '../native/autoRediscover'
import { useState } from 'react' 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() { export default function OfflinePage() {
const [checking, setChecking] = useState(false) const [checking, setChecking] = useState(false)
const [search, setSearch] = useState(null) // null | { done, total } | 'not-found' const [search, setSearch] = useState(null) // null | { done, total } | 'not-found'
+14 -12
View File
@@ -812,12 +812,14 @@ function PloigisiTab() {
// ── Icon Navbar drag state ──────────────────────────────────────────────────── // ── Icon Navbar drag state ────────────────────────────────────────────────────
const dragKey = useRef(null) const dragKey = useRef(null)
const [dragging, setDragging] = useState(null) // drawn dimmed while dragged (refs aren't read in render)
const touchDragKey = useRef(null) const touchDragKey = useRef(null)
const itemRefs = useRef({}) const itemRefs = useRef({})
const [dropIndex, setDropIndex] = useState(null) const [dropIndex, setDropIndex] = useState(null)
// ── Triple Pill drag state ──────────────────────────────────────────────────── // ── Triple Pill drag state ────────────────────────────────────────────────────
const triDragKey = useRef(null) const triDragKey = useRef(null)
const [triDragging, setTriDragging] = useState(null)
const triTouchDragKey = useRef(null) const triTouchDragKey = useRef(null)
const triItemRefs = useRef({}) const triItemRefs = useRef({})
const [triDropIndex, setTriDropIndex] = useState(null) const [triDropIndex, setTriDropIndex] = useState(null)
@@ -865,45 +867,45 @@ function PloigisiTab() {
} }
// ── Icon Navbar drag handlers ──────────────────────────────────────────────── // ── Icon Navbar drag handlers ────────────────────────────────────────────────
function onDragStart(key) { dragKey.current = key } function onDragStart(key) { dragKey.current = key; setDragging(key) }
function onDragOverContainer(e, items) { function onDragOverContainer(e, items) {
e.preventDefault() e.preventDefault()
setDropIndex(computeDropIndex(e.clientY, itemRefs, items)) setDropIndex(computeDropIndex(e.clientY, itemRefs, items))
} }
function onDropContainer(items) { function onDropContainer(items) {
applyReorder(dragKey.current, dropIndex, items, setNavItems) 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 onDragEnd() { dragKey.current = null; setDragging(null); setDropIndex(null) }
function onTouchStart(e, key) { touchDragKey.current = key } function onTouchStart(e, key) { touchDragKey.current = key; setDragging(key) }
function onTouchMove(e, items) { function onTouchMove(e, items) {
e.preventDefault() e.preventDefault()
setDropIndex(computeDropIndex(e.touches[0].clientY, itemRefs, items)) setDropIndex(computeDropIndex(e.touches[0].clientY, itemRefs, items))
} }
function onTouchEnd(items) { function onTouchEnd(items) {
applyReorder(touchDragKey.current, dropIndex, items, setNavItems) applyReorder(touchDragKey.current, dropIndex, items, setNavItems)
touchDragKey.current = null; setDropIndex(null) touchDragKey.current = null; setDragging(null); setDropIndex(null)
} }
// ── Triple Pill drag handlers ──────────────────────────────────────────────── // ── Triple Pill drag handlers ────────────────────────────────────────────────
function triOnDragStart(key) { triDragKey.current = key } function triOnDragStart(key) { triDragKey.current = key; setTriDragging(key) }
function triOnDragOver(e, items) { function triOnDragOver(e, items) {
e.preventDefault() e.preventDefault()
setTriDropIndex(computeDropIndex(e.clientY, triItemRefs, items)) setTriDropIndex(computeDropIndex(e.clientY, triItemRefs, items))
} }
function triOnDrop(items) { function triOnDrop(items) {
applyReorder(triDragKey.current, triDropIndex, items, setTripleItems) 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 triOnDragEnd() { triDragKey.current = null; setTriDragging(null); setTriDropIndex(null) }
function triOnTouchStart(e, key) { triTouchDragKey.current = key } function triOnTouchStart(e, key) { triTouchDragKey.current = key; setTriDragging(key) }
function triOnTouchMove(e, items) { function triOnTouchMove(e, items) {
e.preventDefault() e.preventDefault()
setTriDropIndex(computeDropIndex(e.touches[0].clientY, triItemRefs, items)) setTriDropIndex(computeDropIndex(e.touches[0].clientY, triItemRefs, items))
} }
function triOnTouchEnd(items) { function triOnTouchEnd(items) {
applyReorder(triTouchDragKey.current, triDropIndex, items, setTripleItems) 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) const enabledItems = navItems.map(k => NAV_MAP[k]).filter(Boolean)
@@ -978,7 +980,7 @@ function PloigisiTab() {
border: '2px solid var(--accent)', border: '2px solid var(--accent)',
background: 'var(--accent)18', background: 'var(--accent)18',
cursor: 'grab', userSelect: 'none', 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', transition: 'opacity 0.1s',
}} }}
> >
@@ -1080,7 +1082,7 @@ function PloigisiTab() {
background: 'var(--accent)18', background: 'var(--accent)18',
cursor: 'grab', cursor: 'grab',
userSelect: 'none', 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', transition: 'opacity 0.1s',
}} }}
> >
+2 -1
View File
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import AppShell from '../components/AppShell' import AppShell from '../components/AppShell'
import client from '../api/client' import client from '../api/client'
import { getVenueSettings } from '../api/venueSettings'
// ── helpers ─────────────────────────────────────────────────────────────────── // ── helpers ───────────────────────────────────────────────────────────────────
@@ -144,7 +145,7 @@ export default function ShiftOverviewPage() {
const { data: settings } = useQuery({ const { data: settings } = useQuery({
queryKey: ['pos-settings'], queryKey: ['pos-settings'],
queryFn: () => client.get('/api/settings/').then(r => r.data), queryFn: () => getVenueSettings().then(r => r.data),
staleTime: 60_000, staleTime: 60_000,
}) })
+25 -26
View File
@@ -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 { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import OrderSummary from '../components/OrderSummary' import OrderSummary from '../components/OrderSummary'
import useAuthStore from '../store/authStore'
import useConnectionStore from '../store/connectionStore' import useConnectionStore from '../store/connectionStore'
import client from '../api/client' import client from '../api/client'
import { apiError } from '../api/errors'
import { getVenueSettings } from '../api/venueSettings'
import db from '../db/posdb' import db from '../db/posdb'
import { queueOfflineSplit, queueOfflinePayment as queueOfflinePaymentOp } from '../services/offlineOrders' import { queueOfflineSplit, queueOfflinePayment as queueOfflinePaymentOp } from '../services/offlineOrders'
import { TransferIcon, MergeIcon, FlagsIcon, WaiterIcon, PrintIcon } from '../components/Icons' import { TransferIcon, MergeIcon, FlagsIcon, WaiterIcon, PrintIcon } from '../components/Icons'
@@ -365,13 +366,13 @@ function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCance
// ─── Apply Discount modal ───────────────────────────────────────────────────── // ─── 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 activeItems = (order?.items ?? []).filter(i => i.status === 'active')
const [selectedIds, setSelectedIds] = useState(activeItems.map(i => i.id)) const [selectedIds, setSelectedIds] = useState(activeItems.map(i => i.id))
const [pct, setPct] = useState(10) const [pct, setPct] = useState(10)
const [note, setNote] = useState('') const [note, setNote] = useState('')
const [applying, setApplying] = useState(false) const [applying, setApplying] = useState(false)
const [remaining, setRemaining] = useState(null) // { shift, workday } const [, setRemaining] = useState(null) // { shift, workday }
const [error, setError] = useState('') const [error, setError] = useState('')
const PCT_PRESETS = [5, 10, 15, 20, 25, 50, 100] const PCT_PRESETS = [5, 10, 15, 20, 25, 50, 100]
@@ -406,7 +407,7 @@ function ApplyDiscountModal({ order, waiterId, onClose, onApplied }) {
onApplied() onApplied()
onClose() onClose()
} catch (e) { } catch (e) {
setError(e?.response?.data?.detail || 'Σφάλμα εφαρμογής έκπτωσης') setError(apiError(e, 'Σφάλμα εφαρμογής έκπτωσης'))
} finally { } finally {
setApplying(false) 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 hasOrder = !!order
const hasServable = hasOrder && order.items?.some(i => i.kds_status === 'done') const hasServable = hasOrder && order.items?.some(i => i.kds_status === 'done')
const hasActiveItems = hasOrder && order.items?.some(i => i.status === 'active') 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) ───────────────────────── // ─── 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 ( return (
<div className="modal-overlay modal-overlay--top" onClick={onClose}> <div className="modal-overlay modal-overlay--top" onClick={onClose}>
<div className="modal-sheet modal-sheet--top" onClick={e => e.stopPropagation()}> <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 ────────────────────────────────────────────────────────────── // ─── Flag picker ──────────────────────────────────────────────────────────────
function FlagPicker({ tableId, currentFlagIds, flagDefs, onSave, onClose, loading }) { function FlagPicker({ _tableId, currentFlagIds, flagDefs, onSave, onClose, loading }) {
const [selected, setSelected] = useState(currentFlagIds || []) const [selected, setSelected] = useState(currentFlagIds || [])
// Sync selected when currentFlagIds loads // Sync selected when currentFlagIds loads
@@ -1037,7 +1038,6 @@ export default function TableDetailPage() {
const { tableId, orderId: standaloneOrderId } = useParams() const { tableId, orderId: standaloneOrderId } = useParams()
const isStandalone = !!standaloneOrderId const isStandalone = !!standaloneOrderId
const [searchParams, setSearchParams] = useSearchParams() const [searchParams, setSearchParams] = useSearchParams()
const { user } = useAuthStore()
const navigate = useNavigate() const navigate = useNavigate()
const [table, setTable] = useState(null) const [table, setTable] = useState(null)
@@ -1226,7 +1226,7 @@ export default function TableDetailPage() {
client.get('/api/pricing/discount-settings/me') client.get('/api/pricing/discount-settings/me')
.then(r => setCanDiscount(!!r.data.can_apply_discounts)) .then(r => setCanDiscount(!!r.data.can_apply_discounts))
.catch(() => {}) .catch(() => {})
client.get('/api/settings/') getVenueSettings()
.then(r => { .then(r => {
setCardEnabled(r.data?.['payments.card_enabled']?.value === 'true') setCardEnabled(r.data?.['payments.card_enabled']?.value === 'true')
setRevertAllowed(r.data?.['payments.waiter_revert_allowed']?.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 client.post('/api/orders/', { table_id: Number(tableId) })
await load() await load()
} catch (err) { } 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 (res.data?.auto_closed || andClose) {
if (andClose && !res.data?.auto_closed) { if (andClose && !res.data?.auto_closed) {
// Payment succeeded, now close the order explicitly // 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 }) navigate('/tables', { replace: true })
return return
} }
await load() await load()
} catch (err) { } catch (err) {
const detail = err?.response?.data?.detail setError(apiError(err, 'Σφάλμα πληρωμής'))
setError(detail ? `Σφάλμα πληρωμής: ${detail}` : 'Σφάλμα πληρωμής')
} finally { } finally {
setPaying(false) setPaying(false)
} }
@@ -1379,7 +1378,7 @@ export default function TableDetailPage() {
setPaidSelectedIds([]) setPaidSelectedIds([])
await load() await load()
} catch (err) { } catch (err) {
setError(err.response?.data?.detail || 'Σφάλμα αναίρεσης πληρωμής') setError(apiError(err, 'Σφάλμα αναίρεσης πληρωμής'))
} }
} }
@@ -1389,7 +1388,7 @@ export default function TableDetailPage() {
setConfirmClose(false) setConfirmClose(false)
navigate('/tables') navigate('/tables')
} catch (err) { } catch (err) {
setError(err.response?.data?.detail || 'Σφάλμα κλεισίματος') setError(apiError(err, 'Σφάλμα κλεισίματος'))
} }
} }
@@ -1405,7 +1404,7 @@ export default function TableDetailPage() {
setItemActionTarget(null) setItemActionTarget(null)
await load() await load()
} catch (err) { } 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`) await client.delete(`/api/orders/${order.id}?print_cancellation=true`)
navigate('/tables') navigate('/tables')
} catch (err) { } catch (err) {
setError(err.response?.data?.detail || 'Σφάλμα ακύρωσης παραγγελίας') setError(apiError(err, 'Σφάλμα ακύρωσης παραγγελίας'))
} }
} }
@@ -1434,7 +1433,7 @@ export default function TableDetailPage() {
setPaidSelectedIds([]) setPaidSelectedIds([])
await load() await load()
} catch (err) { } 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 client.post(`/api/kds/orders/${order.id}/items/mark-all-served`)
await load() await load()
} catch (err) { } catch (err) {
setError(err.response?.data?.detail || 'Σφάλμα σήμανσης') setError(apiError(err, 'Σφάλμα σήμανσης'))
} }
} }
@@ -1493,7 +1492,7 @@ export default function TableDetailPage() {
setSelectedIds([]) setSelectedIds([])
await load() await load()
} catch (err) { } 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 }) await client.post(`/api/orders/${order.id}/transfer`, { target_table_id: targetTable.id })
navigate('/tables') navigate('/tables')
} catch (err) { } 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 }) await client.post(`/api/orders/${order.id}/merge`, { target_order_id: targetOrder.id })
navigate('/tables') navigate('/tables')
} catch (err) { } catch (err) {
setError(err.response?.data?.detail || 'Σφάλμα συγχώνευσης') setError(apiError(err, 'Σφάλμα συγχώνευσης'))
} }
} }
@@ -1540,7 +1539,7 @@ export default function TableDetailPage() {
setSelectedIds([]) setSelectedIds([])
await load() await load()
} catch (err) { } catch (err) {
setError(err.response?.data?.detail || 'Σφάλμα μεταφοράς αντικειμένων') setError(apiError(err, 'Σφάλμα μεταφοράς αντικειμένων'))
} }
} }
@@ -1778,7 +1777,7 @@ export default function TableDetailPage() {
onClick={() => setShowMergeModal(true)} onClick={() => setShowMergeModal(true)}
style={{ style={{
width: 40, flexShrink: 0, 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)', background: mergeMode !== MERGE_OFF ? 'rgba(99,102,241,0.25)' : 'var(--bg2)',
color: mergeMode !== MERGE_OFF ? '#a5b4fc' : 'var(--muted)', color: mergeMode !== MERGE_OFF ? '#a5b4fc' : 'var(--muted)',
border: mergeMode !== MERGE_OFF ? '1px solid rgba(99,102,241,0.45)' : '1px solid var(--border)', 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) { if (order) {
try { try {
await client.patch(`/api/orders/${order.id}/customer-count`, { customer_count: v }) await client.patch(`/api/orders/${order.id}/customer-count`, { customer_count: v })
} catch {} } catch { /* ignore */ }
} }
}} }}
onClose={() => setCustomerCountOpen(false)} onClose={() => setCustomerCountOpen(false)}
+6 -5
View File
@@ -6,6 +6,7 @@ import useTableColourStore from '../store/tableColourStore'
import useConnectionStore from '../store/connectionStore' import useConnectionStore from '../store/connectionStore'
import useTableViewStore from '../store/tableViewStore' import useTableViewStore from '../store/tableViewStore'
import client from '../api/client' import client from '../api/client'
import { getVenueSettings } from '../api/venueSettings'
import db from '../db/posdb' import db from '../db/posdb'
import { FlagsIcon, TransferIcon, MergeIcon, PrintIcon, WaiterIcon } from '../components/Icons' 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)' }}> <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> <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 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
{QUICK_ACTIONS.map((a, i) => { {QUICK_ACTIONS.map((a, _i) => {
const disabled = !order && a.key !== 'flags' const disabled = !order && a.key !== 'flags'
return ( return (
<button key={a.key} disabled={disabled} onClick={() => { onClose(); onAction(a.key) }} style={{ <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 [flagDefs, setFlagDefs] = useState([])
const [flagAssignments, setFlagAssignments] = useState([]) const [flagAssignments, setFlagAssignments] = useState([])
const [waiters, setWaiters] = useState([]) // waiter objects for avatar lookup const [waiters, setWaiters] = useState([]) // waiter objects for avatar lookup
const [offline, setOffline] = useState(false) const [, setOffline] = useState(false)
const [showFilters, setShowFilters] = useState(false) const [showFilters, setShowFilters] = useState(false)
const [quickModal, setQuickModal] = useState(null) const [quickModal, setQuickModal] = useState(null)
const [canCancel, setCanCancel] = useState(false) const [canCancel, setCanCancel] = useState(false)
@@ -391,7 +392,7 @@ export default function TableListPage() {
client.get('/api/tables/groups'), client.get('/api/tables/groups'),
client.get('/api/flags/defs'), client.get('/api/flags/defs'),
client.get('/api/flags/assignments'), client.get('/api/flags/assignments'),
client.get('/api/settings/'), getVenueSettings(),
client.get('/api/waiters/on-shift'), client.get('/api/waiters/on-shift'),
]) ])
@@ -452,14 +453,14 @@ export default function TableListPage() {
setCancelConfirm(null) setCancelConfirm(null)
setQuickModal(null) setQuickModal(null)
load() load()
} catch {} } catch { /* ignore */ }
} }
async function executeMarkAllServed(orderId) { async function executeMarkAllServed(orderId) {
try { try {
await client.post(`/api/kds/orders/${orderId}/items/mark-all-served`) await client.post(`/api/kds/orders/${orderId}/items/mark-all-served`)
load() load()
} catch {} } catch { /* ignore */ }
} }
// ── SSE live updates ─────────────────────────────────────────────────────── // ── SSE live updates ───────────────────────────────────────────────────────
-1
View File
@@ -129,7 +129,6 @@ export async function queueOfflinePayment({ orderId, itemIds, paymentMethod }) {
const offlineAt = new Date().toISOString() const offlineAt = new Date().toISOString()
const seq = Date.now() 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_')) const allReal = itemIds.every(id => typeof id === 'number' || !String(id).startsWith('offline_item_'))
if (allReal) { if (allReal) {
+1 -1
View File
@@ -4,7 +4,7 @@ function computeUnread(conversations) {
return conversations.reduce((sum, c) => sum + (c.unread_count || 0), 0) return conversations.reduce((sum, c) => sum + (c.unread_count || 0), 0)
} }
const useChatStore = create((set, get) => ({ const useChatStore = create((set, _get) => ({
conversations: [], conversations: [],
totalUnread: 0, totalUnread: 0,
// Messages cache: { [convId]: MessageOut[] } — newest first (API order) // Messages cache: { [convId]: MessageOut[] } — newest first (API order)
-1
View File
@@ -34,7 +34,6 @@ const useConnectionStore = create((set, get) => ({
const graceTimer = setTimeout(() => { const graceTimer = setTimeout(() => {
if (get().status !== 'reconnecting') return if (get().status !== 'reconnecting') return
const lostAt = get().lostAt
// Start the 5-min flash timer // Start the 5-min flash timer
const flashTimer = setTimeout(() => { const flashTimer = setTimeout(() => {
+1 -1
View File
@@ -104,7 +104,7 @@ const useTableColourStore = create((set) => ({
} }
set({ colours: merged }) set({ colours: merged })
} }
} catch {} } catch { /* ignore */ }
}, },
})) }))
+1 -1
View File
@@ -10,7 +10,7 @@ import { storageKey } from '../config/server'
const useTableViewStore = create( const useTableViewStore = create(
persist( persist(
(set, get) => ({ (set, _get) => ({
density: '2x2', density: '2x2',
ownerFilter: 'all', ownerFilter: 'all',
statusFilter: 'all', statusFilter: 'all',
+1 -1
View File
@@ -87,7 +87,7 @@ const useWaiterFavoritesStore = create(
try { try {
const res = await client.get('/api/auth/me/settings') const res = await client.get('/api/auth/me/settings')
existing = JSON.parse(res.data?.settings || '{}') existing = JSON.parse(res.data?.settings || '{}')
} catch {} } catch { /* ignore */ }
const { favorites, quickNotes, itemFavorites } = get() const { favorites, quickNotes, itemFavorites } = get()
const merged = { ...existing, [SETTINGS_KEY]: { favorites, quickNotes, itemFavorites } } const merged = { ...existing, [SETTINGS_KEY]: { favorites, quickNotes, itemFavorites } }
+29
View File
@@ -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)
})