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 { 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 (
{t('common.loading')}
) } // ─── Gate Screens ───────────────────────────────────────────────────────────── function GateCard({ emoji, title, subtitle, children }) { return (
{emoji}

{title}

{subtitle &&

{subtitle}

}
{children}
) } 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: '#0f172a' }, secondary: { background: 'var(--bg3)', color: 'var(--text)' }, danger: { background: 'var(--danger)', color: '#fff' }, } return } function ClosedScreen({ onRefresh, onLogout }) { const { t } = useTranslation('waiter') return (
{t('common.refresh')} {t('common.signOut')}
) } function WaitingManagerScreen({ onRefresh, onLogout }) { const { t } = useTranslation('waiter') return (
{t('common.refresh')} {t('common.signOut')}
) } 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 (
€ 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', }} />
{error && (

{error}

)} {starting ? t('gate.starting') : `▶ ${t('gate.startShift')}`}
) } // ─── 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 if (!user || gateStatus === 'loading') return if (gateStatus === 'closed') return if (gateStatus === 'waiting_manager') return if (gateStatus === 'needs_start') { return ( ) } return } /** 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 && } {token && locked && } ) } // ─── 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 } function ThemeApplier() { const dark = useThemeStore(s => s.dark) useEffect(() => { document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light') }, [dark]) 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 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 return ( ) } // ─── TableListPage wrapper ──────────────────────────────────────────────────── function TableListRoute() { return ( ) } // ─── 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 } return ( <> {/* outside the bootstrap: they must run even when the server can't be reached yet */} {deliveryMode() === 'native' && } {deliveryMode() === 'native' && } ) } /** 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 ( } autoRetryMs={5000} failed={error => (error.offline || error.status >= 500 ? : undefined)}> {children} ) } function Routed() { return ( {/* Native builds ship their UI in the app bundle — no service worker to update */} {deliveryMode() !== 'native' && } } /> } /> : } /> }> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> ) }