Files
xenia-pos-local/waiter_pwa/src/App.jsx
T
bonaminandClaude Opus 5.5 f57894dcb7 feat(waiter): table bookings on the phone; shared ReasonPicker (platform-v2 step 4.8c)
- Waiter: Bookings (side drawer, for whoever has connect_orders.manage or
  reservations.manage, with the online-orders app on): requests made online are
  confirmed or declined with a reason the guest sees; confirmed ones are seated at a free
  table (its seats shown, a warning mark when the party is bigger) or cancelled / marked
  as a no-show; the food ordered ahead and its kitchen time; live updates.
- Backend: the bookings routes take reservations.manage too (require_any).
- @xenia/ui ReasonPicker + reasonText (gallery, unit test), first piece moved from the
  terminal (4.6 → 4.8): the counter's online reject and booking decline dialogs use it;
  the waiter loads @xenia/ui styles.css (the .x-* components; tokens as before).
- Tests: waiter e2e +2 (request listed with the key, confirmed and seated from the phone);
  terminal.mjs and qr_table.mjs green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:10:14 +02:00

520 lines
20 KiB
React

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, useModule } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { i18n } from './i18n'
import useAuthStore from './store/authStore'
import useShiftStore from './store/shiftStore'
import useThemeStore from './store/themeStore'
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'
import AddItemsPage from './pages/AddItemsPage'
import OfflinePage from './pages/OfflinePage'
import SettingsPage from './pages/SettingsPage'
import FavoritesSetupPage from './pages/FavoritesSetupPage'
import ChatListPage from './pages/ChatListPage'
import ChatThreadPage from './pages/ChatThreadPage'
import ShiftOverviewPage from './pages/ShiftOverviewPage'
import OrderLogPage from './pages/OrderLogPage'
import BookingsPage from './pages/BookingsPage'
import { NotificationProvider } from './context/NotificationContext'
import { LiveProvider } from './context/LiveContext'
import ConnectivityBar from './components/ConnectivityBar'
import RefusedLines from './components/RefusedLines'
import AppShell from './components/AppShell'
import UpdatePrompt from './components/UpdatePrompt'
import InstallAppDialog from './components/InstallAppDialog'
import VenuesPage from './pages/VenuesPage'
import ServerRediscovery from './components/ServerRediscovery'
import BundleSync from './components/BundleSync'
import LockScreen, { IdleGuard } from './components/LockScreen'
import { deliveryMode, getActiveVenue } from './config/server'
// ─── Utility ─────────────────────────────────────────────────────────────────
function Spinner() {
const { t } = useTranslation('waiter')
return (
<div className="page page--centered" style={{ gap: 12 }}>
<div style={{
width: 36, height: 36,
border: '3px solid var(--border)',
borderTopColor: 'var(--accent)',
borderRadius: '50%',
animation: 'gate-spin 0.7s linear infinite',
}} />
<span style={{ color: 'var(--muted)', fontSize: 14 }}>{t('common.loading')}</span>
</div>
)
}
// ─── Gate Screens ─────────────────────────────────────────────────────────────
function GateCard({ emoji, title, subtitle, children }) {
return (
<div className="page page--centered" style={{ gap: 24, padding: 32 }}>
<div style={{ textAlign: 'center' }}>
<div style={{ fontSize: 52, marginBottom: 12 }}>{emoji}</div>
<p style={{ fontSize: 20, fontWeight: 700, color: 'var(--text)', marginBottom: 6 }}>{title}</p>
{subtitle && <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.5 }}>{subtitle}</p>}
</div>
{children}
</div>
)
}
function GateBtn({ onClick, disabled, variant = 'primary', children }) {
const base = {
height: 44, padding: '0 24px', borderRadius: 12, border: 'none',
fontSize: 15, fontWeight: 600, cursor: disabled ? 'not-allowed' : 'pointer',
opacity: disabled ? 0.6 : 1, transition: 'opacity 120ms',
}
const styles = {
primary: { background: 'var(--accent)', color: 'var(--x-canvas)' },
secondary: { background: 'var(--bg3)', color: 'var(--text)' },
danger: { background: 'var(--danger)', color: 'var(--x-danger-fg)' },
}
return <button style={{ ...base, ...styles[variant] }} onClick={onClick} disabled={disabled}>{children}</button>
}
function ClosedScreen({ onRefresh, onLogout }) {
const { t } = useTranslation('waiter')
return (
<GateCard emoji="🔒" title={t('gate.closedTitle')}
subtitle={t('gate.closedBody')}>
<div style={{ display: 'flex', gap: 12 }}>
<GateBtn variant="secondary" onClick={onRefresh}>{t('common.refresh')}</GateBtn>
<GateBtn variant="danger" onClick={onLogout}>{t('common.signOut')}</GateBtn>
</div>
</GateCard>
)
}
function WaitingManagerScreen({ onRefresh, onLogout }) {
const { t } = useTranslation('waiter')
return (
<GateCard emoji="⏳" title={t('gate.waitingTitle')}
subtitle={t('gate.waitingBody')}>
<div style={{ display: 'flex', gap: 12 }}>
<GateBtn variant="secondary" onClick={onRefresh}>{t('common.refresh')}</GateBtn>
<GateBtn variant="danger" onClick={onLogout}>{t('common.signOut')}</GateBtn>
</div>
</GateCard>
)
}
function StartShiftScreen({ username, onStart, onLogout }) {
const { t } = useTranslation('waiter')
const [startingCash, setStartingCash] = useState('')
const [starting, setStarting] = useState(false)
const [error, setError] = useState(null)
async function handleStart() {
setStarting(true)
setError(null)
try {
await onStart(startingCash ? parseFloat(startingCash) : null)
} catch (e) {
setError(apiError(e, t('gate.startFailed')))
setStarting(false)
}
}
return (
<GateCard emoji="👋" title={t('gate.welcome', { name: username })}
subtitle={t('gate.startQuestion')}>
<div style={{
width: '100%', maxWidth: 320,
background: 'var(--bg2)', border: '1px solid var(--border)',
borderRadius: 16, padding: 20,
display: 'flex', flexDirection: 'column', gap: 16,
}}>
<div>
<label style={{ fontSize: 13, fontWeight: 600, color: 'var(--muted)', display: 'block', marginBottom: 6 }}>
{t('gate.startingCash')}
</label>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ color: 'var(--muted)', fontWeight: 700 }}>€</span>
<input
type="number" step="0.01" min="0" placeholder="0.00"
value={startingCash}
onChange={e => setStartingCash(e.target.value)}
onKeyDown={e => e.key === 'Enter' && handleStart()}
style={{
flex: 1, background: 'var(--bg3)', border: '1px solid var(--border)',
borderRadius: 10, padding: '10px 12px',
color: 'var(--text)', fontSize: 16, outline: 'none',
}}
/>
</div>
</div>
{error && (
<p style={{
fontSize: 13, color: 'var(--danger)',
background: 'var(--danger-dim)', borderRadius: 8, padding: '8px 12px',
}}>{error}</p>
)}
<GateBtn onClick={handleStart} disabled={starting}>
{starting ? t('gate.starting') : `▶ ${t('gate.startShift')}`}
</GateBtn>
</div>
<button
style={{ fontSize: 13, color: 'var(--muted)', background: 'none', border: 'none', cursor: 'pointer' }}
onClick={onLogout}
>
{t('common.signOut')}
</button>
</GateCard>
)
}
// ─── Protected Layout with Shift Gate ────────────────────────────────────────
function AppLayout() {
const { token, user, logout } = useAuthStore()
const navigate = useNavigate()
const {
setShift, setBusinessDay,
setSelfStartAllowed, setSelfEndAllowed,
gateStatus, setGateStatus,
} = useShiftStore()
// 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
if (isManager) { setGateStatus('ready'); return }
setGateStatus('loading')
try {
const dayRes = await client.get('/api/business-day/current')
const day = dayRes.data
setBusinessDay(day)
if (!day) { setGateStatus('closed'); return }
const shiftRes = await client.get('/api/shifts/my')
if (shiftRes.data) {
setShift(shiftRes.data)
setGateStatus('ready')
return
}
// No active shift — check self-start setting
try {
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)
setSelfEndAllowed(canEnd)
setGateStatus(canStart ? 'needs_start' : 'waiting_manager')
} catch {
setSelfStartAllowed(true)
setSelfEndAllowed(true)
setGateStatus('needs_start')
}
} catch {
setBusinessDay(null)
setGateStatus('closed')
}
}
useEffect(() => {
if (user) checkGate()
}, [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(() => {
if (!user || isManager || gateStatus !== 'ready') return
const id = setInterval(async () => {
try {
const dayRes = await client.get('/api/business-day/current')
if (!dayRes.data) { setGateStatus('closed'); return }
const shiftRes = await client.get('/api/shifts/my')
if (!shiftRes.data) {
// Shift was ended by manager — rerun full gate check
checkGate()
}
} catch {
// network error — ignore, don't lock
}
}, 15_000)
return () => clearInterval(id)
}, [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 })
setShift(res.data)
setGateStatus('ready')
}
function handleLogout() {
logout()
navigate('/login')
}
if (!token) return <Navigate to="/login" replace />
if (!user || gateStatus === 'loading') return <Spinner />
if (gateStatus === 'closed') return <ClosedScreen onRefresh={checkGate} onLogout={handleLogout} />
if (gateStatus === 'waiting_manager') return <WaitingManagerScreen onRefresh={checkGate} onLogout={handleLogout} />
if (gateStatus === 'needs_start') {
return (
<StartShiftScreen
username={user.username}
onStart={handleStartShift}
onLogout={handleLogout}
/>
)
}
return <Outlet />
}
/** Signed-in screens with the idle guard and the lock screen over them (plan step 4.2): the
* lock covers everything, the shift gates included, and what was open stays underneath. */
function ProtectedLayout() {
const token = useAuthStore(s => s.token)
const locked = useAuthStore(s => s.locked)
return (
<>
{token && <IdleGuard />}
{token && locked && <LockScreen />}
<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, restore, logout } = useAuthStore()
const access = useAccess()
useEffect(() => {
if (!token || user) return
if (access.user) restore(access.user)
else if (!access.offline) logout()
}, [token, user, access.user, access.offline, restore, logout])
return null
}
function OfflineListener() {
const navigate = useNavigate()
const { token } = useAuthStore()
const { status } = useConnectionStore()
useEffect(() => {
function handler() {
// The venue switcher must stay usable while the current venue is unreachable
if (window.location.pathname === '/venues') return
// If user is logged in, ConnectivityBar handles it — don't redirect to /offline
if (token && status !== 'online') return
// Not logged in and server is down → redirect to offline page
if (!token) navigate('/offline')
}
window.addEventListener('backend-offline', handler)
return () => window.removeEventListener('backend-offline', handler)
}, [navigate, token, status])
return null
}
// Light / dark from the user menu (per phone), the accent colour from the venue (bootstrap
// venue.theme, Settings → Venue; plan step 4.6). The waiter's colours are @xenia/ui tokens.
function ThemeApplier() {
const dark = useThemeStore(s => s.dark)
const venueTheme = useAccess()?.venue?.theme || 'amber'
useEffect(() => {
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light')
}, [dark])
useEffect(() => {
document.documentElement.setAttribute('data-venue-theme', venueTheme)
}, [venueTheme])
return null
}
// Prevents the Android back gesture/button from exiting the PWA.
//
// Strategy: whenever the browser lands on /tables (the root screen), immediately
// push a sentinel entry so there is always one history entry behind it. If the
// user backs into the sentinel we push it again — they can never back past /tables.
//
// Only active when running as an installed PWA (standalone display mode) or in
// the native app, where the hardware back button would otherwise close the app.
function AndroidBackGuard() {
useEffect(() => {
const isStandalone = window.matchMedia('(display-mode: standalone)').matches
|| window.navigator.standalone === true
|| deliveryMode() === 'native'
if (!isStandalone) return
function pushSentinel() {
history.pushState({ pwaGuard: true }, '')
}
// If we're already on the root screen at mount time, push the sentinel now.
if (window.location.pathname === '/tables' || window.location.pathname === '/') {
pushSentinel()
}
function onPopState(e) {
if (e.state?.pwaGuard) {
// User backed into the sentinel — push it again so there's always one more.
pushSentinel()
return
}
// User backed to /tables (the real root screen) — push the sentinel behind it.
if (window.location.pathname === '/tables' || window.location.pathname === '/') {
pushSentinel()
}
}
window.addEventListener('popstate', onPopState)
return () => window.removeEventListener('popstate', onPopState)
}, [])
return null
}
function ColourLoader() {
const loadFromBackend = useTableColourStore(s => s.loadFromBackend)
useEffect(() => {
getVenueSettings()
.then(r => {
const raw = r.data?.['ui.table_colours']?.value
if (raw) loadFromBackend(raw)
})
.catch(() => {})
}, [])
return null
}
function FavoritesLoader() {
const { token } = useAuthStore()
const loadFromServer = useWaiterFavoritesStore(s => s.loadFromServer)
useEffect(() => {
if (token) loadFromServer()
}, [token])
return null
}
// ─── Login guard — redirect to /tables if already authenticated ───────────────
function LoginGuard({ children }) {
const { token } = useAuthStore()
if (token) return <Navigate to="/tables" replace />
return children
}
// ─── ChatListPage wrapper — owns showNewChat state so pencil can live in AppShell ──
function ChatListRoute() {
// plan 4.3: staff chat needs the module and chat.use
const chatModule = useModule('chat')
const chatKey = useCan('chat.use')
if (!chatModule || !chatKey) return <Navigate to="/tables" replace />
return (
<AppShell>
<ChatListPage />
</AppShell>
)
}
// ─── TableListPage wrapper ────────────────────────────────────────────────────
function TableListRoute() {
return (
<AppShell>
<TableListPage />
</AppShell>
)
}
// ─── App ──────────────────────────────────────────────────────────────────────
const queryClient = new QueryClient()
export default function App() {
// Native app with no paired venue yet: nothing else can work, show pairing only
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>
<ThemeApplier />
<AndroidBackGuard />
<ColourLoader />
<FavoritesLoader />
<AuthRehydrator />
<OfflineListener />
<LiveProvider>
<NotificationProvider>
<ConnectivityBar />
<RefusedLines />
{/* Native builds ship their UI in the app bundle — no service worker to update */}
{deliveryMode() !== 'native' && <UpdatePrompt />}
<InstallAppDialog />
<Routes>
<Route path="/login" element={<LoginGuard><LoginPage /></LoginGuard>} />
<Route path="/offline" element={<OfflinePage />} />
<Route path="/venues" element={deliveryMode() === 'native' ? <VenuesPage /> : <Navigate to="/" replace />} />
<Route element={<ProtectedLayout />}>
<Route index element={<Navigate to="/tables?tab=tables" replace />} />
<Route path="/tables" element={<TableListRoute />} />
<Route path="/tables/:tableId" element={<TableDetailPage />} />
<Route path="/tables/:tableId/add" element={<AddItemsPage />} />
<Route path="/standalone/:orderType/add" element={<AddItemsPage />} />
<Route path="/orders/:orderId" element={<TableDetailPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/settings/favorites" element={<FavoritesSetupPage />} />
<Route path="/shift-overview" element={<ShiftOverviewPage />} />
<Route path="/order-log" element={<OrderLogPage />} />
<Route path="/bookings" element={<BookingsPage />} />
<Route path="/messages" element={<ChatListRoute />} />
<Route path="/messages/:conversationId" element={<ChatThreadPage />} />
</Route>
<Route path="*" element={<Navigate to="/tables?tab=tables" replace />} />
</Routes>
</NotificationProvider>
</LiveProvider>
</BrowserRouter>
</QueryClientProvider>
)
}