)
}
// ─── 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' && }
} />
} />
: } />
}>
} />
} />
} />
} />
} />
} />
} />
} />
} />
} />
} />
} />
} />
)
}