// The counter POS's server data (plan steps 3.3a, 3.3c–e): the cashier's session (shift gate), // the menu, the cart priced by the backend, the tables, a table's order, online orders and receipts. Kept fresh by the // live connection, so a waiter's phone and the counter see each other's changes at once. import { useCallback, useEffect, useRef, useState } from 'react' import { useModule } from '@xenia/access' import client from '../../api/client' import { useLiveEvent, useLiveEvents } from '../../device/context' const quiet = { xenia: { noOverride: true } } const MENU_REFRESH_MS = 5 * 60_000 // prices can change with the time (happy hours) const QUOTE_DELAY_MS = 120 /** GET /api/pos/session: { business_day, shift, self_start, day_openers } (null while loading). */ export function usePosSession() { const [session, setSession] = useState(null) const [error, setError] = useState(null) const load = useCallback(async () => { try { setSession((await client.get('/api/pos/session', quiet)).data) setError(null) } catch (err) { setError(err) } }, []) useEffect(() => { load() }, [load]) useLiveEvent('ready', load) useLiveEvents(['shift_changed', 'business_day_changed'], load) return { session, error, reload: load } } /** GET /api/pos/menu: { settings, categories, products } (null while loading). */ export function useMenu() { const [menu, setMenu] = useState(null) const load = useCallback(async () => { try { setMenu((await client.get('/api/pos/menu', quiet)).data) } catch { /* the shell shows offline */ } }, []) useEffect(() => { load() }, [load]) useEffect(() => { const id = setInterval(load, MENU_REFRESH_MS) return () => clearInterval(id) }, [load]) useLiveEvent('ready', load) useLiveEvents(['products_changed', 'device.updated'], load) return { menu, reload: load } } /** The cart priced by POST /api/pos/quote whenever it changes (latest answer wins). With * `orderId` (a table's order) the order's items count for deals, as when it's sent. * → { quote, pending, error } */ export function useQuote(lines, orderType, orderId = null) { const [state, setState] = useState({ quote: null, pending: false, error: null }) const seq = useRef(0) const key = JSON.stringify([lines, orderType, orderId]) useEffect(() => { const mine = ++seq.current if (!lines.length) { setState({ quote: { lines: [], total: 0 }, pending: false, error: null }); return undefined } setState(s => ({ ...s, pending: true })) const id = setTimeout(async () => { try { const { data } = await client.post('/api/pos/quote', { order_type: orderType, lines, order_id: orderId ?? undefined }, quiet) if (mine === seq.current) setState({ quote: data, pending: false, error: null }) } catch (err) { if (mine === seq.current) setState(s => ({ ...s, pending: false, error: err })) } }, QUOTE_DELAY_MS) return () => clearTimeout(id) }, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is lines + orderType + orderId return state } const TABLE_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'table_flags_changed', 'table_list_changed', 'kds_order_updated', 'kds_item_updated'] const COALESCE_MS = 150 /** Calls `load` once for a burst of events (a payment sends several). */ function useCoalesced(load) { const timer = useRef(null) useEffect(() => () => clearTimeout(timer.current), []) return useCallback(() => { clearTimeout(timer.current) timer.current = setTimeout(load, COALESCE_MS) }, [load]) } /** GET /api/pos/tables: { groups, tables } (null while loading); live. */ export function useTables() { const [data, setData] = useState(null) const load = useCallback(async () => { try { setData((await client.get('/api/pos/tables', quiet)).data) } catch { /* the shell shows offline */ } }, []) const soon = useCoalesced(load) useEffect(() => { load() }, [load]) useLiveEvent('ready', load) useLiveEvents(TABLE_EVENTS, soon) return { data, reload: load } } /** GET /api/orders/{id} for one order (null id → null); reloads on that order's events. * → { order, gone, reload } (gone: closed or removed meanwhile). */ export function useOrder(orderId) { const [order, setOrder] = useState(null) const [gone, setGone] = useState(false) const load = useCallback(async () => { if (orderId == null) { setOrder(null); setGone(false); return } try { const { data } = await client.get(`/api/orders/${orderId}`, quiet) setOrder(data) setGone(data.status === 'closed' || data.status === 'cancelled') } catch (err) { if (err?.xenia?.status === 404) setGone(true) } }, [orderId]) const soon = useCoalesced(load) useEffect(() => { load() }, [load]) useLiveEvent('ready', load) useLiveEvents(TABLE_EVENTS, (_type, data) => { if (data?.order_id === orderId) soon() }) return { order, gone, reload: load } } const ONLINE_EVENTS = ['online_order_received', 'online_order_updated', 'order_paid', 'order_closed'] /** GET /api/connect/orders/board: { incoming, in_progress, finished } (null while loading or * when `enabled` is false: the module is off or the cashier doesn't handle online orders). */ export function useOnline(enabled) { const [data, setData] = useState(null) const load = useCallback(async () => { if (!enabled) { setData(null); return } try { setData((await client.get('/api/connect/orders/board', quiet)).data) } catch { /* the shell shows offline */ } }, [enabled]) const soon = useCoalesced(load) useEffect(() => { load() }, [load]) useLiveEvent('ready', load) useLiveEvents(ONLINE_EVENTS, soon) return { data, reload: load } } // The customer display (plan step 3.4): what this counter's customer should see. One timer for // the whole screen, so the last thing said wins; "paid" goes at once, the rest after a moment // (a burst of cart changes is one message). Nothing is sent while the module is off. let displayTimer = null /** push({ mode: 'idle' | 'cart' | 'paid', lines?, total?, paid?, change? }) → POST /api/display/state. */ export function useDisplay() { const on = useModule('customer_display') return useCallback(state => { if (!on) return clearTimeout(displayTimer) displayTimer = setTimeout(() => { client.post('/api/display/state', state, quiet).catch(() => {}) }, state.mode === 'paid' ? 0 : 200) }, [on]) } const BOOKING_EVENTS = ['reservation_requested', 'reservation_updated'] /** GET /api/connect/bookings: { requested, upcoming } (null while loading); live (S.6). */ export function useBookings(enabled) { const [data, setData] = useState(null) const load = useCallback(async () => { if (!enabled) { setData(null); return } try { setData((await client.get('/api/connect/bookings', quiet)).data) } catch { /* the shell shows offline */ } }, [enabled]) const soon = useCoalesced(load) useEffect(() => { load() }, [load]) useLiveEvent('ready', load) useLiveEvents(BOOKING_EVENTS, soon) return { data, reload: load } } const RECEIPT_EVENTS = ['order_paid', 'order_refunded', 'order_closed'] /** GET /api/pos/receipts: today's paid orders ({ orders }, null while loading); live. */ export function useReceipts(scope, enabled) { const [data, setData] = useState(null) const load = useCallback(async () => { if (!enabled) return try { setData((await client.get('/api/pos/receipts', { ...quiet, params: { scope } })).data) } catch { /* the shell shows offline */ } }, [scope, enabled]) const soon = useCoalesced(load) useEffect(() => { load() }, [load]) useLiveEvent('ready', load) useLiveEvents(RECEIPT_EVENTS, soon) return { data, reload: load } } /** GET /api/pos/receipts/{id}: one paid order with what's refundable (null id → null); live. */ export function useReceipt(orderId) { const [receipt, setReceipt] = useState(null) const load = useCallback(async () => { if (orderId == null) { setReceipt(null); return } try { setReceipt((await client.get(`/api/pos/receipts/${orderId}`, quiet)).data) } catch { /* the shell shows offline */ } }, [orderId]) const soon = useCoalesced(load) useEffect(() => { load() }, [load]) useLiveEvent('ready', load) useLiveEvents(RECEIPT_EVENTS, (_type, data) => { if (data?.order_id === orderId) soon() }) return { receipt, reload: load } }