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>
)
}