Files
xenia-pos-local/terminal/src/apps/pos/usePos.js
T
bonaminandClaude Opus 5.5 88a9703902 feat(terminal): the customer display, with an idle screen each venue designs
Plan step 3.4. Owner (2026-11-16): the idle screen is configurable per venue.
- routers/customer_display.py (module customer_display, /api/display): the counter POS
  pushes its state (POST /api/display/state: idle | cart | paid with lines, total, paid,
  change); only the displays linked to that POS get `display.state`; the last state is kept
  in memory for a display that reconnects (GET /api/display/state). pos_counter's device
  scope includes customer_display.state.
- The idle screen: setting customer_display.idle (name, logo, logo + name, blank, one
  image, slideshow, QR code to the online ordering / QR menu / any link; a line of text;
  dark or light); images uploaded to /app/data/display_media (JPG/PNG/WebP/GIF ≤ 5 MB,
  random names, served publicly on the LAN); a change sends `display.settings` to every
  display. New key customer_display.manage (owners, store managers; migration 0022).
- Terminal: CustomerDisplayApp (cart with a large total, "Thank you" with the change for
  12 s, the venue's idle screen, its theme), logic.js (unit-tested); the POS pushes from the
  sale cart and the payment dialog (tables, online orders too) via useDisplay().
  qrcode.react added to the terminal (already in the workspace).
- Manager: Settings → Customer display (style cards, venue name, text, look, slide seconds,
  QR target/link/caption, image upload/pick/order/delete).
- Tests: tests/test_customer_display.py (3), terminal display.test.mjs (3); e2e terminal
  (linked vs unlinked display, < 1 s, paid, QR and slideshow idle screens), manager (the
  settings tab).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:34:05 +02:00

194 lines
8.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 }
}