feat(backend,terminal): online orders on the counter POS (platform-v2 step 3.3d)

- Counter POS gets an "Online" mode (module on + connect_orders.manage): New / In
  progress / Finished, a chime on arrival (and every 30 s while one waits), badge,
  toast in any mode; the order panel offers only the next step: accept / reject with
  a reason, preparing, ready or out for delivery, then take the payment (shared
  PaymentDialog, drawer, shift) and mark delivered/served.
- connect_orders router on v2 conventions: require(connect_orders.manage), error
  codes online.not_found / online.status_changed, the cloud's step order enforced,
  audit rows, GET /api/connect/orders/board. POS device scope gains connect_orders.*;
  barista and barman get the key by default.
- Fixes: the KDS showed online orders before acceptance; accepting printed no
  kitchen tickets; a pull whose synced mark failed stored the order twice
  (store_online_orders skips known cloud ids); pulled orders lacked the business day
  and delivery type; rejected orders kept active items; delivered sets closed_at/by.
- Online orders belong to holders of connect_orders.manage (_can_access_order), so
  the counter pays them with POST /api/pos/orders/{id}/pay.
- Tests: test_pos_online.py (5), terminal unit +1, terminal.mjs +17 with a fake
  cloud (pull, synced, status mirror); fixed a timing race in a 3.3c check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 05:42:06 +02:00
co-authored by Claude Opus 5.5
parent 988d413d8e
commit d542cf7d34
20 changed files with 1052 additions and 176 deletions
+176
View File
@@ -0,0 +1,176 @@
// One online order at the counter (plan step 3.3d): the right column in Online mode. It shows
// the customer (phone, address, their note) and the items, and offers the next step only:
// accept (kitchen tickets, KDS) or reject (with a reason the customer sees), start preparing,
// ready or out for delivery, then finish: take what's unpaid (the counter's ordinary payment,
// cash/card/split with the drawer) and mark it delivered. Someone else's change meanwhile is
// refused by the backend and the order shows where it is now.
import { useState } from 'react'
import { Ban, Banknote, Bike, Check, ChefHat, MapPin, MessageSquare, PackageCheck, Phone, Utensils } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Input } from '@xenia/ui'
import client from '../../api/client'
import { nextStep } from './logic/online'
import { itemPayments, orderLines, orderSums, qtyLabel } from './logic/tables'
import PaymentDialog from './PaymentDialog'
const REASONS = ['busy', 'unavailable', 'closing', 'area']
const STEP_ICON = { preparing: ChefHat, ready: PackageCheck, out_for_delivery: Bike }
export default function OnlinePanel({ order, onChanged }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [paying, setPaying] = useState(null) // rows being paid
const [rejecting, setRejecting] = useState(false)
if (!order) {
return (
<aside className="border-l border-line bg-surface flex items-center justify-center p-6" data-testid="online-panel">
<EmptyState compact title={t('pos.online.pick')} />
</aside>
)
}
const lines = orderLines(order)
const sums = orderSums(lines)
const step = nextStep(order)
const delivery = order.type === 'delivery'
const finishWord = delivery ? 'delivered' : 'served'
const run = async (fn) => {
setBusy(true)
setError('')
try { return await fn() } catch (err) { setError(errorMessage(err, t)); onChanged(); return null } finally { setBusy(false) }
}
const post = (path, body) => client.post(`/api/connect/orders/${order.id}/${path}`, body)
const accept = () => run(async () => { await post('accept'); onChanged(null, { list: 'in_progress' }) })
const advance = to => run(async () => { await post('status', { status: to }); onChanged() })
const payRows = lines.filter(l => !l.paid).map(l => ({ id: l.id, label: `${qtyLabel(l.quantity, l.unitType)} ${l.name}`, total: l.total }))
const submitPay = async ({ method, payments, cashGiven }) => (await client.post(`/api/pos/orders/${order.id}/pay`, {
payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }],
cash_given: cashGiven,
})).data
return (
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="online-panel" data-order={order.id} data-status={order.status}>
<div className="p-3 border-b border-line grid gap-1">
<div className="flex items-center gap-2">
<span className="flex-1 text-title font-semibold">{order.ref}</span>
<span className="text-label font-medium text-ink-2 flex items-center gap-1">
{delivery ? <Bike size={16} aria-hidden="true" /> : <Utensils size={16} aria-hidden="true" />}
{t(`pos.online.type.${delivery ? 'delivery' : 'dine_in'}`)}
</span>
</div>
<div className="text-caption text-ink-2">{t(`pos.online.status.${order.status}`)} · {formatTime(order.opened_at)}</div>
</div>
<div className="flex-1 overflow-y-auto">
<section className="p-3 border-b border-line grid gap-1.5 text-body" data-testid="online-customer">
<div className="text-body-lg font-semibold">{order.customer.name}</div>
{order.customer.phone && <Detail icon={Phone}>{order.customer.phone}</Detail>}
{order.customer.address && <Detail icon={MapPin}>{order.customer.address}</Detail>}
{order.customer.notes && (
<div className="p-2 rounded-control bg-warning-soft text-warning-ink flex gap-2">
<MessageSquare size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span>{order.customer.notes}</span>
</div>
)}
</section>
<section data-testid="online-lines">
{lines.map(l => (
<div key={l.id} className={`px-3 py-2 border-b border-line flex items-start gap-2 ${l.paid ? 'text-ink-3' : 'text-ink'}`} data-testid="online-line">
<span className="flex-1 min-w-0">
<span className="text-body font-medium">{qtyLabel(l.quantity, l.unitType)} {l.name}</span>
{(l.options.length > 0 || l.notes) && (
<span className="block text-caption text-ink-2">{[...l.options, l.notes && `“${l.notes}”`].filter(Boolean).join(' · ')}</span>
)}
</span>
<span className="text-body text-right">
{formatMoney(l.total)}
{l.paid && <span className="block text-caption text-success-ink">{t(`pos.table.paidBy.${l.method === 'card' ? 'card' : 'cash'}`)}</span>}
</span>
</div>
))}
</section>
</div>
<div className="border-t border-line p-3 grid gap-2">
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
<div className="flex items-baseline justify-between">
<span className="text-body-lg text-ink-2">{sums.unpaid > 0 ? t('pos.table.due') : t('pos.total')}</span>
<span className="text-display font-semibold" data-testid="online-total">{formatMoney(sums.unpaid > 0 ? sums.unpaid : sums.total)}</span>
</div>
{step?.kind === 'answer' && (
<>
<Button size="lg" icon={<Check size={20} />} loading={busy} onClick={accept} data-testid="online-accept">{t('pos.online.accept')}</Button>
<Button variant="secondary" icon={<Ban size={16} />} disabled={busy} onClick={() => setRejecting(true)} data-testid="online-reject">{t('pos.online.reject')}</Button>
</>
)}
{step?.kind === 'status' && (() => {
const Icon = STEP_ICON[step.to]
return <Button size="lg" icon={<Icon size={20} />} loading={busy} onClick={() => advance(step.to)} data-testid="online-next">{t(`pos.online.to.${step.to}`)}</Button>
})()}
{step?.kind === 'finish' && (step.pay ? (
<Button size="lg" icon={<Banknote size={20} />} disabled={busy} onClick={() => setPaying(payRows)} data-testid="online-finish">
{t(`pos.online.payAnd.${finishWord}`, { amount: formatMoney(sums.unpaid) })}
</Button>
) : (
<Button size="lg" icon={<PackageCheck size={20} />} loading={busy} onClick={() => advance('delivered')} data-testid="online-finish">
{t(`pos.online.mark.${finishWord}`)}
</Button>
))}
</div>
{paying && (
<PaymentDialog total={orderSums(paying).total} rows={paying} submit={submitPay}
onClose={() => setPaying(null)}
onPaid={result => {
setPaying(null)
run(async () => { await post('status', { status: 'delivered' }); onChanged(result) })
}} />
)}
{rejecting && <RejectDialog busy={busy} error={error} onClose={() => setRejecting(false)}
onReject={reason => run(async () => { await post('reject', { reason }); setRejecting(false); onChanged(null, { clear: true }) })} />}
</aside>
)
}
function Detail({ icon: Icon, children }) {
return <div className="flex items-start gap-2 text-ink-2"><Icon size={16} className="mt-0.5 shrink-0" aria-hidden="true" /><span className="text-ink">{children}</span></div>
}
function RejectDialog({ busy, error, onClose, onReject }) {
const { t } = useTranslation('terminal')
const [choice, setChoice] = useState(null)
const [other, setOther] = useState('')
const reason = choice === 'other' ? other.trim() : choice ? t(`pos.online.reasons.${choice}`) : ''
return (
<Dialog open size="sm" title={t('pos.online.rejectTitle')} onClose={busy ? undefined : onClose}
footer={<>
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('pos.online.keep')}</Button>
<Button variant="danger" icon={<Ban size={16} />} loading={busy} disabled={!reason} onClick={() => onReject(reason)} data-testid="reject-confirm">
{t('pos.online.rejectConfirm')}
</Button>
</>}>
<div className="grid gap-2">
<p className="text-body text-ink-2">{t('pos.online.rejectBody')}</p>
<div className="grid gap-1" role="radiogroup" aria-label={t('pos.online.reason')}>
{[...REASONS, 'other'].map(r => (
<button key={r} type="button" role="radio" aria-checked={choice === r} onClick={() => setChoice(r)} data-testid={`reason-${r}`}
className={`min-h-[var(--x-control-md)] px-3 rounded-control text-left text-body transition-colors duration-fast
${choice === r ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink hover:bg-surface-3'}`}>
{t(`pos.online.reasons.${r}`)}
</button>
))}
</div>
{choice === 'other' && (
<Input value={other} onChange={e => setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.online.reason')} data-testid="reason-text" />
)}
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div>
</Dialog>
)
}
+63
View File
@@ -0,0 +1,63 @@
// Online orders at the counter (plan step 3.3d): one list at a time (new, in progress,
// finished; picked on the left), each order as a card with its reference, delivery or at the
// venue, the customer, how long it has waited and what it costs. New orders stand out until
// someone answers them. A tap shows the order on the right (OnlinePanel).
import { Bike, Clock, Utensils } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState, Spinner } from '@xenia/ui'
import { minutesSince } from './logic/online'
const LOOK = {
pending_acceptance: 'bg-warning-soft border-warning text-warning-ink',
accepted: 'bg-info-soft border-info text-info-ink',
preparing: 'bg-info-soft border-info text-info-ink',
ready: 'bg-success-soft border-success text-success-ink',
out_for_delivery: 'bg-success-soft border-success text-success-ink',
delivered: 'bg-surface border-line text-ink-2',
rejected: 'bg-surface border-line text-ink-3',
}
export default function OnlineView({ data, list, picked, onPick, now }) {
const { t } = useTranslation('terminal')
if (!data) return <div className="flex-1 flex items-center justify-center"><Spinner /></div>
const orders = data[list] ?? []
if (!orders.length) {
return (
<div className="flex-1 flex items-center justify-center p-6" data-testid="online-orders">
<EmptyState title={t(`pos.online.empty.${list}`)} description={list === 'incoming' ? t('pos.online.emptyBody') : undefined} />
</div>
)
}
return (
<div className="flex-1 overflow-y-auto p-3 grid content-start gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(14rem, 1fr))' }}
data-testid="online-orders">
{orders.map(o => <OrderCard key={o.id} order={o} picked={picked === o.id} onPick={() => onPick(o.id)} now={now} />)}
</div>
)
}
function OrderCard({ order, picked, onPick, now }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const Icon = order.type === 'delivery' ? Bike : Utensils
const waiting = order.status === 'pending_acceptance'
return (
<button type="button" onClick={onPick} aria-pressed={picked} data-testid="online-order" data-order={order.id} data-status={order.status}
className={`min-h-32 p-3 rounded-card border-2 shadow-raised text-left flex flex-col gap-1 active:scale-[0.98] transition-transform duration-fast
${LOOK[order.status] ?? LOOK.delivered} ${picked ? 'ring-2 ring-accent ring-offset-2 ring-offset-canvas' : ''}`}>
<span className="flex items-center gap-2">
<span className="flex-1 min-w-0 text-title font-semibold truncate">{order.ref}</span>
<Icon size={18} aria-label={t(`pos.online.type.${order.type === 'delivery' ? 'delivery' : 'dine_in'}`)} />
</span>
<span className="text-body font-medium truncate">{order.customer.name}</span>
<span className="text-label font-medium">{t(`pos.online.status.${order.status}`)}</span>
<span className="mt-auto flex items-baseline justify-between gap-2">
<span className="text-heading font-semibold">{formatMoney(order.total)}</span>
<span className="text-label flex items-center gap-1 opacity-80">
<Clock size={14} aria-hidden="true" />
{waiting ? t('pos.online.waiting', { count: minutesSince(order.opened_at, now) }) : formatTime(order.opened_at)}
</span>
</span>
</button>
)
}
+80 -16
View File
@@ -1,22 +1,33 @@
// The counter POS screen (plan steps 3.3a–c). Two modes, switched at the top left:
// The counter POS screen (plan steps 3.3a–d). Up to three modes, switched at the top left:
// - Sale: categories on the left, the product grid with a search, the quick-sale cart on the
// right (SaleCart: Charge → payment, 3.3b).
// - Tables: the zones on the left and the table list (TablesView); a table opens with the
// product grid again and the table's order on the right (TablePanel).
// - Online (when online orders are on and the cashier handles them): new / in progress /
// finished on the left, the orders (OnlineView) and the picked one (OnlinePanel). A new
// order rings (and again every 30 s while one waits for an answer) and shows a notice in any
// mode; the mode's badge counts the orders waiting.
// A tap adds a product (or opens its choices when it has preferences to pick); the (i) button
// checks its price without adding it. Every price is the backend's.
import { useMemo, useState } from 'react'
import { Info, LayoutGrid, Search, ShoppingBag, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { Globe, Info, LayoutGrid, Search, ShoppingBag, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { useCan } from '@xenia/access'
import { EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
import { useCan, useModule } from '@xenia/access'
import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui'
import { useLiveEvent } from '../../device/context'
import { playChime } from './chime'
import { addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart'
import { findOnline, ONLINE_LISTS } from './logic/online'
import { zoneCounts } from './logic/tables'
import OnlinePanel from './OnlinePanel'
import OnlineView from './OnlineView'
import ProductDialog from './ProductDialog'
import SaleCart from './SaleCart'
import TablePanel from './TablePanel'
import TablesView from './TablesView'
import { useMenu, useTables } from './usePos'
import { useMenu, useOnline, useTables } from './usePos'
const REMIND_MS = 30_000
export default function PosScreen() {
const { t } = useTranslation('terminal')
@@ -27,7 +38,8 @@ export default function PosScreen() {
function Counter({ menu, t }) {
const { language } = useLanguage()
const [mode, setMode] = useState('sale') // sale | tables
const { formatMoney } = useFormat()
const [mode, setMode] = useState('sale') // sale | tables | online
const [tableId, setTableId] = useState(null) // the open table (tables mode)
const [zone, setZone] = useState(null)
const [category, setCategory] = useState(() => menu.settings.start_category_id ?? null)
@@ -38,11 +50,37 @@ function Counter({ menu, t }) {
const [dialog, setDialog] = useState(null) // product
const tables = useTables()
const canDiscount = useCan('ordering.prices.modify')
const toast = useToast()
const onlineModule = useModule('connect_orders')
const handlesOnline = useCan('connect_orders.manage')
const onlineOn = onlineModule && handlesOnline
const online = useOnline(onlineOn)
const [onlineList, setOnlineList] = useState('incoming')
const [onlineId, setOnlineId] = useState(null)
const [now, setNow] = useState(() => Date.now())
const [chimes, setChimes] = useState(0)
const waiting = online.data?.incoming.length ?? 0
const ring = () => { playChime(); setChimes(c => c + 1) }
useLiveEvent('online_order_received', data => {
if (!onlineOn) return
ring()
if (mode !== 'online') toast.info(t('pos.online.arrived', { count: data?.count ?? 1 }))
})
// a reminder while an order waits for an answer; the waiting minutes move on too
useEffect(() => {
const id = setInterval(() => {
setNow(Date.now())
if (waiting > 0) { playChime(); setChimes(c => c + 1) }
}, REMIND_MS)
return () => clearInterval(id)
}, [waiting])
// a table that left the cashier's list (zone changed) shows the list again
const table = tableId != null ? tables.data?.tables.find(x => x.id === tableId) ?? null : null
const atTable = mode === 'tables' && table != null
const picking = mode === 'tables' && !atTable
const onlineOrder = findOnline(online.data, onlineId)
const setCart = atTable ? setTableCart : setSaleCart
const leaveTable = () => { setTableId(null); setTableCart([]) }
@@ -59,15 +97,27 @@ function Counter({ menu, t }) {
}
return (
<div className="absolute inset-0 grid grid-cols-[13rem_1fr_24rem] bg-canvas text-ink" data-testid="pos-screen" lang={language}>
<div className="absolute inset-0 grid grid-cols-[13rem_1fr_24rem] bg-canvas text-ink" data-testid="pos-screen" data-chimes={chimes} lang={language}>
<nav className="border-r border-line bg-surface min-h-0 flex flex-col">
<div className="p-2 grid grid-cols-2 gap-1 border-b border-line" role="tablist" aria-label={t('pos.mode.label')}>
<div className={`p-2 grid gap-1 border-b border-line ${onlineOn ? 'grid-cols-3' : 'grid-cols-2'}`} role="tablist" aria-label={t('pos.mode.label')}>
<ModeButton active={mode === 'sale'} onClick={() => setMode('sale')} icon={ShoppingBag} testId="mode-sale">{t('pos.mode.sale')}</ModeButton>
<ModeButton active={mode === 'tables'} onClick={() => { setMode('tables'); leaveTable() }} icon={LayoutGrid} testId="mode-tables"
badge={counts.all.busy || null}>{t('pos.mode.tables')}</ModeButton>
{onlineOn && (
<ModeButton active={mode === 'online'} onClick={() => setMode('online')} icon={Globe} testId="mode-online"
badge={waiting || null} alert={waiting > 0}>{t('pos.mode.online')}</ModeButton>
)}
</div>
<div className="flex-1 overflow-y-auto p-2 grid content-start gap-1" data-testid={picking ? 'pos-zones' : 'pos-categories'}>
{picking ? (
<div className="flex-1 overflow-y-auto p-2 grid content-start gap-1"
data-testid={mode === 'online' ? 'online-lists' : picking ? 'pos-zones' : 'pos-categories'}>
{mode === 'online' ? (
ONLINE_LISTS.map(list => (
<NavButton key={list} active={onlineList === list} onClick={() => setOnlineList(list)} testId={`online-list-${list}`}
tally={list === 'finished' ? null : online.data?.[list].length}>
{t(`pos.online.lists.${list}`)}
</NavButton>
))
) : picking ? (
<>
<NavButton active={zone == null} onClick={() => setZone(null)} count={counts.all}>{t('pos.tables.allZones')}</NavButton>
{(tables.data?.groups ?? []).map(g => (
@@ -87,7 +137,20 @@ function Counter({ menu, t }) {
</div>
</nav>
{picking ? (
{mode === 'online' ? (
<>
<main className="flex flex-col min-h-0 min-w-0">
<OnlineView data={online.data} list={onlineList} picked={onlineId} onPick={setOnlineId} now={now} />
</main>
<OnlinePanel key={onlineOrder?.id ?? 'none'} order={onlineOrder}
onChanged={(result, move) => {
online.reload()
if (move?.list) setOnlineList(move.list)
if (move?.clear) setOnlineId(null)
if (result?.change > 0) toast.success(t('pos.done.toastChange', { change: formatMoney(result.change) }))
}} />
</>
) : picking ? (
<main className="col-span-2 flex flex-col min-h-0 min-w-0">
<TablesView data={tables.data} zone={zone} onPick={id => { setTableId(id); setTableCart([]) }} />
</main>
@@ -126,18 +189,18 @@ function Counter({ menu, t }) {
)
}
function ModeButton({ active, onClick, icon: Icon, badge, children, testId }) {
function ModeButton({ active, onClick, icon: Icon, badge, alert, children, testId }) {
return (
<button type="button" role="tab" aria-selected={active} onClick={onClick} data-testid={testId}
<button type="button" role="tab" aria-selected={active} onClick={onClick} data-testid={testId} data-badge={badge ?? 0}
className={`relative min-h-[var(--x-control-lg)] rounded-control flex flex-col items-center justify-center gap-0.5 text-label font-semibold transition-colors duration-fast
${active ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`}>
<Icon size={18} aria-hidden="true" />{children}
{badge ? <span className="absolute top-1 right-1 min-w-5 h-5 px-1 rounded-full bg-warning text-warning-fg text-caption font-bold flex items-center justify-center">{badge}</span> : null}
{badge ? <span className={`absolute top-1 right-1 min-w-5 h-5 px-1 rounded-full bg-warning text-warning-fg text-caption font-bold flex items-center justify-center ${alert ? 'animate-pulse' : ''}`}>{badge}</span> : null}
</button>
)
}
function NavButton({ active, colour, onClick, children, testId, count }) {
function NavButton({ active, colour, onClick, children, testId, count, tally }) {
return (
<button type="button" onClick={onClick} data-testid={testId} aria-pressed={active}
className={`min-h-[var(--x-control-lg)] px-3 rounded-control text-left text-body font-medium flex items-center gap-2 transition-colors duration-fast
@@ -145,6 +208,7 @@ function NavButton({ active, colour, onClick, children, testId, count }) {
{colour && <span className="size-2.5 rounded-full shrink-0" style={{ background: colour }} aria-hidden="true" />}
<span className="flex-1 truncate">{children}</span>
{count && <span className="text-caption text-ink-3">{count.busy}/{count.total}</span>}
{tally != null && <span className="text-caption text-ink-3">{tally}</span>}
</button>
)
}
+24
View File
@@ -0,0 +1,24 @@
// The counter's "new online order" sound (plan step 3.3d): a short two-note chime made with
// Web Audio, so there is no sound file to ship. Browsers only play sound after the page was
// touched; a counter screen always is (the PIN pad), and a failure is silent.
let ctx = null
export function playChime() {
try {
ctx = ctx ?? new (window.AudioContext || window.webkitAudioContext)()
if (ctx.state === 'suspended') ctx.resume()
const start = ctx.currentTime + 0.02
;[[880, 0], [1320, 0.18]].forEach(([freq, at]) => {
const osc = ctx.createOscillator()
const gain = ctx.createGain()
osc.type = 'sine'
osc.frequency.value = freq
gain.gain.setValueAtTime(0.0001, start + at)
gain.gain.exponentialRampToValueAtTime(0.4, start + at + 0.02)
gain.gain.exponentialRampToValueAtTime(0.0001, start + at + 0.35)
osc.connect(gain).connect(ctx.destination)
osc.start(start + at)
osc.stop(start + at + 0.4)
})
} catch { /* no sound on this device */ }
}
+34
View File
@@ -0,0 +1,34 @@
// Online orders at the counter (plan step 3.3d): what the list shows and which step comes next.
// The orders come from GET /api/connect/orders/board; the steps follow the backend's (and the
// cloud's) order: accept or reject → preparing → ready (at the venue) or out for delivery →
// delivered. Pure: unit-tested in Node (tests/pos.test.mjs).
export const ONLINE_LISTS = ['incoming', 'in_progress', 'finished']
/** The next step of an order: { kind: 'answer' } (accept / reject), { kind: 'status', to },
* { kind: 'finish', pay } (take what's unpaid, then delivered) or null (finished). */
export function nextStep(order) {
switch (order.status) {
case 'pending_acceptance': return { kind: 'answer' }
case 'accepted': return { kind: 'status', to: 'preparing' }
case 'preparing': return { kind: 'status', to: order.type === 'delivery' ? 'out_for_delivery' : 'ready' }
case 'ready':
case 'out_for_delivery': return { kind: 'finish', pay: order.unpaid > 0.004 }
default: return null
}
}
/** The order with this id in any of the board's lists (null when gone). */
export function findOnline(board, id) {
if (!board || id == null) return null
for (const list of ONLINE_LISTS) {
const hit = (board[list] ?? []).find(o => o.id === id)
if (hit) return hit
}
return null
}
/** Whole minutes since an ISO time (never negative). */
export function minutesSince(iso, now = Date.now()) {
return Math.max(0, Math.floor((now - Date.parse(iso)) / 60_000))
}
+19 -2
View File
@@ -1,5 +1,5 @@
// The counter POS's server data (plan steps 3.3a, 3.3c): the cashier's session (shift gate),
// the menu, the cart priced by the backend, the tables and a table's order. Kept fresh by the
// The counter POS's server data (plan steps 3.3a, 3.3c, 3.3d): the cashier's session (shift gate),
// the menu, the cart priced by the backend, the tables, a table's order and online orders. 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 client from '../../api/client'
@@ -112,3 +112,20 @@ export function useOrder(orderId) {
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 }
}
+20
View File
@@ -128,3 +128,23 @@ test('tables at the counter: state, zones, order lines, what Pay takes (3.3c)',
assert.equal(qtyLabel(2, 'piece'), '2×')
assert.equal(qtyLabel(0.5, 'liter'), '0.5 L')
})
test('online orders: the next step and finding an order (3.3d)', async () => {
const { findOnline, minutesSince, nextStep } = await import('../src/apps/pos/logic/online.js')
assert.deepEqual(nextStep({ status: 'pending_acceptance' }), { kind: 'answer' })
assert.deepEqual(nextStep({ status: 'accepted' }), { kind: 'status', to: 'preparing' })
assert.deepEqual(nextStep({ status: 'preparing', type: 'delivery' }), { kind: 'status', to: 'out_for_delivery' })
assert.deepEqual(nextStep({ status: 'preparing', type: 'dine_in' }), { kind: 'status', to: 'ready' })
assert.deepEqual(nextStep({ status: 'out_for_delivery', unpaid: 22 }), { kind: 'finish', pay: true })
assert.deepEqual(nextStep({ status: 'ready', unpaid: 0 }), { kind: 'finish', pay: false })
assert.equal(nextStep({ status: 'delivered' }), null)
assert.equal(nextStep({ status: 'rejected' }), null)
const board = { incoming: [{ id: 1 }], in_progress: [{ id: 2 }], finished: [{ id: 3 }] }
assert.equal(findOnline(board, 2).id, 2)
assert.equal(findOnline(board, 3).id, 3)
assert.equal(findOnline(board, 9), null)
assert.equal(findOnline(null, 1), null)
const at = Date.parse('2026-11-15T10:00:00Z')
assert.equal(minutesSince('2026-11-15T09:57:30Z', at), 2)
assert.equal(minutesSince('2026-11-15T10:01:00Z', at), 0)
})