feat(pos): refunds at the counter on a fiscal driver layer (platform-v2 3.3e)

- services/fiscal/: one driver interface (prepare_receipt / prepare_credit_note -> send,
  credit_notes flag, status); the dTEC100extra folder bridge moved into txt_file.py as the
  first driver, same command files. fiscal_service.py removed, callers moved.
- Refunds: models/refund.py + Alembic 0016 (refunds, refund_items; ordering.refunds for
  existing owners/managers). services/refunds.py: today's business day, the cashier's open
  shift, partial quantities, items from another shift need ordering.refunds or a manager's
  approval (check()/authorize() return the override row). Paid items are never edited.
- POS: GET /api/pos/receipts, GET /api/pos/receipts/{id}, POST /api/pos/orders/{id}/refund
  (cash opens the drawer; fiscal "manual" when the driver can't issue credit notes).
- Shift totals subtract refunds and now count discounts; day close and business-day
  reports carry refunds.
- Terminal: Receipts mode (ReceiptsView, ReceiptPanel, logic/refunds.js), en/el texts.
- Tests: test_pos_refunds.py (12), terminal unit +1, terminal.mjs +7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 09:44:17 +02:00
co-authored by Claude Opus 5.5
parent d542cf7d34
commit f2182dcb37
32 changed files with 1486 additions and 169 deletions
+29 -8
View File
@@ -1,4 +1,4 @@
// The counter POS screen (plan steps 3.3a–d). Up to three modes, switched at the top left:
// The counter POS screen (plan steps 3.3a–e). Up to four 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
@@ -7,10 +7,12 @@
// 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.
// - Receipts: today's paid orders (the cashier's shift or everyone's) and the picked one
// (ReceiptPanel) to give money back for some or all of its items (3.3e).
// 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 { useEffect, useMemo, useState } from 'react'
import { Globe, Info, LayoutGrid, Search, ShoppingBag, X } from 'lucide-react'
import { Globe, Info, LayoutGrid, Receipt, Search, ShoppingBag, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { useCan, useModule } from '@xenia/access'
import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui'
@@ -22,10 +24,12 @@ import { zoneCounts } from './logic/tables'
import OnlinePanel from './OnlinePanel'
import OnlineView from './OnlineView'
import ProductDialog from './ProductDialog'
import ReceiptPanel from './ReceiptPanel'
import ReceiptsView from './ReceiptsView'
import SaleCart from './SaleCart'
import TablePanel from './TablePanel'
import TablesView from './TablesView'
import { useMenu, useOnline, useTables } from './usePos'
import { useMenu, useOnline, useReceipts, useTables } from './usePos'
const REMIND_MS = 30_000
@@ -39,7 +43,7 @@ export default function PosScreen() {
function Counter({ menu, t }) {
const { language } = useLanguage()
const { formatMoney } = useFormat()
const [mode, setMode] = useState('sale') // sale | tables | online
const [mode, setMode] = useState('sale') // sale | tables | online | receipts
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)
@@ -60,6 +64,9 @@ function Counter({ menu, t }) {
const [now, setNow] = useState(() => Date.now())
const [chimes, setChimes] = useState(0)
const waiting = online.data?.incoming.length ?? 0
const [receiptScope, setReceiptScope] = useState('mine')
const [receiptId, setReceiptId] = useState(null)
const receipts = useReceipts(receiptScope, mode === 'receipts')
const ring = () => { playChime(); setChimes(c => c + 1) }
useLiveEvent('online_order_received', data => {
@@ -99,7 +106,7 @@ function Counter({ menu, t }) {
return (
<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 gap-1 border-b border-line ${onlineOn ? 'grid-cols-3' : 'grid-cols-2'}`} role="tablist" aria-label={t('pos.mode.label')}>
<div className={`p-2 grid gap-1 border-b border-line ${onlineOn ? 'grid-cols-2' : 'grid-cols-3'}`} 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>
@@ -107,10 +114,17 @@ function Counter({ menu, t }) {
<ModeButton active={mode === 'online'} onClick={() => setMode('online')} icon={Globe} testId="mode-online"
badge={waiting || null} alert={waiting > 0}>{t('pos.mode.online')}</ModeButton>
)}
<ModeButton active={mode === 'receipts'} onClick={() => setMode('receipts')} icon={Receipt} testId="mode-receipts">{t('pos.mode.receipts')}</ModeButton>
</div>
<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' ? (
data-testid={mode === 'online' ? 'online-lists' : mode === 'receipts' ? 'receipt-scopes' : picking ? 'pos-zones' : 'pos-categories'}>
{mode === 'receipts' ? (
['mine', 'all'].map(sc => (
<NavButton key={sc} active={receiptScope === sc} onClick={() => setReceiptScope(sc)} testId={`receipts-${sc}`}>
{t(`pos.receipts.scope.${sc}`)}
</NavButton>
))
) : 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}>
@@ -137,7 +151,14 @@ function Counter({ menu, t }) {
</div>
</nav>
{mode === 'online' ? (
{mode === 'receipts' ? (
<>
<main className="flex flex-col min-h-0 min-w-0">
<ReceiptsView data={receipts.data} scope={receiptScope} picked={receiptId} onPick={setReceiptId} />
</main>
<ReceiptPanel orderId={receiptId} />
</>
) : 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} />
+209
View File
@@ -0,0 +1,209 @@
// One paid order at the counter, to refund it (plan step 3.3e): the right column in Receipts
// mode. The cashier taps the items going back (by the piece, or all of a weighed item), picks
// how the money goes back (cash from the drawer, or to the card) and a reason, and confirms.
// Items paid in someone else's shift need a manager: the shared approval dialog asks on the
// spot. With fiscal receipts on and a machine the system can't send credit notes to yet, the
// cashier is reminded to issue the credit note on the machine itself (owner decision 2026-11-15).
import { useState } from 'react'
import { AlertTriangle, Banknote, Check, CheckSquare, CreditCard, ShieldCheck, Square, Undo2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Input, Spinner, Stepper, useToast } from '@xenia/ui'
import client from '../../api/client'
import { byPiece, defaultMethod, needsApproval, pickAll, refundLines, refundTotal, setPickQty, togglePick } from './logic/refunds'
import { qtyLabel } from './logic/tables'
import { useReceipt } from './usePos'
const REASONS = ['wrong', 'quality', 'changed', 'other']
const methodTab = on => `flex-1 min-h-[var(--x-control-lg)] rounded-control flex items-center justify-center gap-2 text-body font-medium transition-colors duration-fast
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
export default function ReceiptPanel({ orderId }) {
const { t } = useTranslation('terminal')
const { receipt, reload } = useReceipt(orderId)
if (orderId == null) {
return (
<aside className="border-l border-line bg-surface flex items-center justify-center p-6" data-testid="receipt-panel">
<EmptyState compact title={t('pos.receipts.pick')} />
</aside>
)
}
if (!receipt || receipt.id !== orderId) {
return <aside className="border-l border-line bg-surface flex items-center justify-center" data-testid="receipt-panel"><Spinner /></aside>
}
return <Receipt receipt={receipt} reload={reload} />
}
function Receipt({ receipt, reload }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const toast = useToast()
const [pick, setPick] = useState({})
const [method, setMethod] = useState(null) // null = follow the picked items
const [reason, setReason] = useState(null)
const [other, setOther] = useState('')
const [confirming, setConfirming] = useState(false)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [manual, setManual] = useState(null) // a refund whose credit note is issued by hand
const items = receipt.items
const total = refundTotal(items, pick)
const lines = refundLines(items, pick)
const how = method ?? defaultMethod(items, pick)
const left = items.some(i => i.refundable > 0)
const reasonText = reason === 'other' ? other.trim() : reason ? t(`pos.refund.reasons.${reason}`) : ''
const manualFiscal = receipt.fiscal.enabled && !receipt.fiscal.credit_notes
const submit = async () => {
setBusy(true)
setError('')
try {
const { data } = await client.post(`/api/pos/orders/${receipt.id}/refund`, { items: lines, method: how, reason: reasonText || undefined })
setConfirming(false)
setPick({})
setMethod(null)
setReason(null)
setOther('')
toast.success(t(`pos.refund.done.${data.method}`, { amount: formatMoney(data.amount) }))
if (data.drawer === 'failed') toast.error(t('pos.done.drawerFailed'))
if (data.fiscal === 'manual') setManual(data)
reload()
} catch (err) {
setError(errorMessage(err, t))
if (err?.xenia?.code === 'refund.items_changed') reload()
} finally {
setBusy(false)
}
}
return (
<aside className="border-l border-line bg-surface flex flex-col min-h-0" data-testid="receipt-panel" data-order={receipt.id}>
<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">{receipt.label}</span>
{left && receipt.today && (
<Button size="sm" variant="secondary" icon={<CheckSquare size={16} />} onClick={() => setPick(pickAll(items))} data-testid="refund-all">
{t('pos.refund.all')}
</Button>
)}
</div>
<p className="text-caption text-ink-2">{receipt.today ? t('pos.refund.tapItems') : t('pos.refund.notToday')}</p>
</div>
<div className="flex-1 overflow-y-auto">
{items.map(i => {
const q = pick[i.id] ?? 0
const on = q > 0
const can = receipt.today && i.refundable > 0
return (
<div key={i.id} className={`px-3 py-2 border-b border-line grid gap-2 ${on ? 'bg-accent-soft' : ''}`} data-testid="receipt-line" data-item={i.id}>
<button type="button" disabled={!can} onClick={() => setPick(p => togglePick(p, i))} aria-pressed={on}
className={`flex items-start gap-2 text-left ${can ? '' : 'opacity-60'}`}>
{on ? <CheckSquare size={20} className="text-accent-ink shrink-0 mt-0.5" aria-hidden="true" />
: <Square size={20} className="text-ink-3 shrink-0 mt-0.5" aria-hidden="true" />}
<span className="flex-1 min-w-0">
<span className="text-body font-medium text-ink">{qtyLabel(i.quantity, i.unit_type)} {i.name}</span>
{(i.options.length > 0 || i.notes) && (
<span className="block text-caption text-ink-2">{[...i.options, i.notes && `“${i.notes}”`].filter(Boolean).join(' · ')}</span>
)}
<span className="block text-caption text-ink-2">
{t(`pos.table.paidBy.${i.method === 'card' ? 'card' : 'cash'}`)}{i.paid_at ? ` · ${formatTime(i.paid_at)}` : ''}{i.paid_by ? ` · ${i.paid_by}` : ''}
</span>
{i.refunded > 0 && (
<span className="block text-caption font-medium text-warning-ink">{t('pos.refund.alreadyBack', { qty: qtyLabel(i.refunded, i.unit_type) })}</span>
)}
</span>
<span className="text-body text-right">{formatMoney(i.total)}</span>
</button>
{on && byPiece(i) && i.refundable > 1 && (
<div className="flex items-center justify-end gap-2">
<span className="text-caption text-ink-2">{t('pos.refund.howMany')}</span>
<Stepper value={q} min={1} max={i.refundable} onChange={v => setPick(p => setPickQty(p, i, v))} label={t('pos.refund.howMany')} data-testid="refund-qty" />
</div>
)}
</div>
)
})}
{receipt.refunds.length > 0 && (
<section className="p-3 grid gap-1" data-testid="receipt-refunds">
<h3 className="text-label font-semibold text-ink-2">{t('pos.refund.history')}</h3>
{receipt.refunds.map(r => (
<div key={r.id} className="text-caption text-ink-2 flex items-start gap-2">
<Undo2 size={14} className="mt-0.5 shrink-0" aria-hidden="true" />
<span className="flex-1">
{formatTime(r.created_at)} · {r.by}{r.approved_by ? ` (${t('pos.refund.approvedBy', { name: r.approved_by })})` : ''}
{r.reason ? ` · ${r.reason}` : ''}
{r.fiscal === 'manual' ? ` · ${t('pos.refund.fiscalManualShort')}` : ''}
</span>
<span className="text-ink font-medium">−{formatMoney(r.amount)} {t(`pos.refund.by.${r.method}`)}</span>
</div>
))}
</section>
)}
</div>
{lines.length > 0 && (
<div className="border-t border-line p-3 grid gap-2">
<div className="flex gap-2" role="radiogroup" aria-label={t('pos.refund.method')}>
<button type="button" role="radio" aria-checked={how === 'cash'} className={methodTab(how === 'cash')} onClick={() => setMethod('cash')} data-testid="refund-cash">
<Banknote size={18} aria-hidden="true" />{t('pos.refund.by.cash')}
</button>
<button type="button" role="radio" aria-checked={how === 'card'} className={methodTab(how === 'card')} onClick={() => setMethod('card')} data-testid="refund-card">
<CreditCard size={18} aria-hidden="true" />{t('pos.refund.by.card')}
</button>
</div>
<div className="flex flex-wrap gap-1" role="radiogroup" aria-label={t('pos.refund.reason')}>
{REASONS.map(r => (
<button key={r} type="button" role="radio" aria-checked={reason === r} onClick={() => setReason(reason === r ? null : r)} data-testid={`refund-reason-${r}`}
className={`px-3 min-h-[var(--x-control-sm)] rounded-full text-label transition-colors duration-fast
${reason === r ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`}>
{t(`pos.refund.reasons.${r}`)}
</button>
))}
</div>
{reason === 'other' && (
<Input value={other} onChange={e => setOther(e.target.value)} maxLength={300} autoFocus aria-label={t('pos.refund.reason')} data-testid="refund-reason-text" />
)}
{needsApproval(items, pick) && (
<p className="text-caption text-ink-2 flex items-center gap-1"><ShieldCheck size={14} aria-hidden="true" />{t('pos.refund.approval')}</p>
)}
{error && !confirming && <p role="alert" className="text-label text-danger-ink">{error}</p>}
<Button size="lg" variant="danger" icon={<Undo2 size={20} />} onClick={() => { setError(''); setConfirming(true) }} data-testid="refund-start">
{t('pos.refund.start', { amount: formatMoney(total) })}
</Button>
</div>
)}
{confirming && (
<Dialog open size="sm" title={t(`pos.refund.confirmTitle.${how}`, { amount: formatMoney(total) })} onClose={busy ? undefined : () => setConfirming(false)}
footer={<>
<Button variant="secondary" onClick={() => setConfirming(false)} disabled={busy}>{t('pos.refund.keep')}</Button>
<Button variant="danger" icon={<Check size={16} />} loading={busy} onClick={submit} data-testid="refund-confirm">{t('pos.refund.confirm')}</Button>
</>}>
<div className="grid gap-2" data-testid="refund-dialog">
<p className="text-body text-ink-2">{t(`pos.refund.confirmBody.${how}`)}</p>
{manualFiscal && (
<p className="p-2 rounded-control bg-warning-soft text-warning-ink text-label flex gap-2">
<AlertTriangle size={16} className="mt-0.5 shrink-0" aria-hidden="true" />{t('pos.refund.fiscalManualBefore')}
</p>
)}
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div>
</Dialog>
)}
{manual && (
<Dialog open size="sm" title={t('pos.refund.fiscalManualTitle')} onClose={() => setManual(null)}
footer={<Button onClick={() => setManual(null)} data-testid="manual-credit-note-ok">{t('pos.refund.fiscalManualOk')}</Button>}>
<div className="grid gap-2" data-testid="manual-credit-note">
<p className="p-2 rounded-control bg-warning-soft text-warning-ink text-body flex gap-2">
<AlertTriangle size={18} className="mt-0.5 shrink-0" aria-hidden="true" />
{t(`pos.refund.fiscalManualBody.${manual.method}`, { amount: formatMoney(manual.amount) })}
</p>
</div>
</Dialog>
)}
</aside>
)
}
+53
View File
@@ -0,0 +1,53 @@
// Today's paid orders at the counter (plan step 3.3e): the cashier's own shift or everyone's
// (picked on the left), newest payment first, each with what was paid, how, by whom and what
// was already given back. A tap shows the order on the right (ReceiptPanel) to refund it.
import { Banknote, CreditCard, Undo2 } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState, Spinner } from '@xenia/ui'
export default function ReceiptsView({ data, scope, picked, onPick }) {
const { t } = useTranslation('terminal')
if (!data) return <div className="flex-1 flex items-center justify-center"><Spinner /></div>
if (!data.orders.length) {
return (
<div className="flex-1 flex items-center justify-center p-6" data-testid="receipts">
<EmptyState title={t(`pos.receipts.empty.${scope}`)} description={t('pos.receipts.emptyBody')} />
</div>
)
}
return (
<div className="flex-1 overflow-y-auto p-3 grid content-start gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(13rem, 1fr))' }}
data-testid="receipts">
{data.orders.map(o => <ReceiptCard key={o.id} order={o} picked={picked === o.id} onPick={() => onPick(o.id)} />)}
</div>
)
}
function ReceiptCard({ order, picked, onPick }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const refunded = order.refunded > 0
return (
<button type="button" onClick={onPick} aria-pressed={picked} data-testid="receipt" data-order={order.id}
className={`min-h-28 p-3 rounded-card border bg-surface border-line shadow-raised text-left flex flex-col gap-1 active:scale-[0.98] transition-transform duration-fast
${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.label}</span>
<span className="text-label text-ink-2">{order.paid_at ? formatTime(order.paid_at) : ''}</span>
</span>
<span className="text-label text-ink-2 truncate">{order.cashier}</span>
<span className="mt-auto flex items-baseline justify-between gap-2">
<span className="text-heading font-semibold">{formatMoney(order.paid)}</span>
<span className="flex items-center gap-1 text-ink-2" aria-label={order.methods.map(m => t(`pos.table.paidBy.${m === 'card' ? 'card' : 'cash'}`)).join(', ')}>
{order.methods.includes('cash') && <Banknote size={16} aria-hidden="true" />}
{order.methods.includes('card') && <CreditCard size={16} aria-hidden="true" />}
</span>
</span>
{refunded && (
<span className="text-label font-medium text-warning-ink flex items-center gap-1" data-testid="receipt-refunded">
<Undo2 size={14} aria-hidden="true" />{t('pos.receipts.refunded', { amount: formatMoney(order.refunded) })}
</span>
)}
</button>
)
}
+53
View File
@@ -0,0 +1,53 @@
// Refunds at the counter (plan step 3.3e): what the cashier picks on a paid order and what it
// adds up to. The backend checks and computes everything again (POST /api/pos/orders/{id}/refund);
// this file only helps the screen. Pure: unit-tested in Node (tests/pos.test.mjs).
const round2 = n => Math.round(n * 100) / 100
/** Items counted by the piece can be refunded one at a time; weighed ones (kg, litre…) as a whole. */
export function byPiece(item) {
return !item.unit_type || item.unit_type === 'piece'
}
/** A new pick (item id → quantity) after tapping an item: all of what's left, or nothing. */
export function togglePick(pick, item) {
const next = { ...pick }
if (next[item.id]) delete next[item.id]
else if (item.refundable > 0) next[item.id] = item.refundable
return next
}
/** A new pick with this item's quantity set (by the piece, within what's left; 0 removes it). */
export function setPickQty(pick, item, qty) {
const next = { ...pick }
const q = Math.max(0, Math.min(item.refundable, Math.round(qty)))
if (q > 0) next[item.id] = q
else delete next[item.id]
return next
}
/** Everything still refundable on the order. */
export function pickAll(items) {
return Object.fromEntries(items.filter(i => i.refundable > 0).map(i => [i.id, i.refundable]))
}
/** The pick as the endpoint takes it: [{ item_id, quantity }] (only what's still there). */
export function refundLines(items, pick) {
return items.filter(i => pick[i.id] > 0).map(i => ({ item_id: i.id, quantity: Math.min(pick[i.id], i.refundable) }))
}
/** What the pick gives back. */
export function refundTotal(items, pick) {
return round2(items.reduce((s, i) => s + (pick[i.id] > 0 ? i.unit_total * Math.min(pick[i.id], i.refundable) : 0), 0))
}
/** The method the money goes back by, to start with: card if every picked item was paid by card. */
export function defaultMethod(items, pick) {
const picked = items.filter(i => pick[i.id] > 0)
return picked.length && picked.every(i => i.method === 'card') ? 'card' : 'cash'
}
/** Whether a manager has to approve (items paid in another shift; the backend decides). */
export function needsApproval(items, pick) {
return items.some(i => pick[i.id] > 0 && !i.mine)
}
+32 -2
View File
@@ -1,5 +1,5 @@
// 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
// 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 client from '../../api/client'
@@ -129,3 +129,33 @@ export function useOnline(enabled) {
useLiveEvents(ONLINE_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 }
}
+25
View File
@@ -148,3 +148,28 @@ test('online orders: the next step and finding an order (3.3d)', async () => {
assert.equal(minutesSince('2026-11-15T09:57:30Z', at), 2)
assert.equal(minutesSince('2026-11-15T10:01:00Z', at), 0)
})
test('refunds: picking items, quantities, total, method, approval (3.3e)', async () => {
const { byPiece, defaultMethod, needsApproval, pickAll, refundLines, refundTotal, setPickQty, togglePick } = await import('../src/apps/pos/logic/refunds.js')
const coffee = { id: 1, unit_type: 'piece', refundable: 2, unit_total: 3, method: 'cash', mine: true }
const feta = { id: 2, unit_type: 'kg', refundable: 0.25, unit_total: 12, method: 'card', mine: true }
const done = { id: 3, unit_type: 'piece', refundable: 0, unit_total: 5, method: 'card', mine: false }
const items = [coffee, feta, done]
assert.equal(byPiece(coffee), true)
assert.equal(byPiece(feta), false)
let pick = togglePick({}, coffee)
assert.deepEqual(pick, { 1: 2 })
pick = setPickQty(pick, coffee, 1)
assert.deepEqual(refundLines(items, pick), [{ item_id: 1, quantity: 1 }])
assert.equal(refundTotal(items, pick), 3)
assert.deepEqual(setPickQty(pick, coffee, 9), { 1: 2 }, 'not more than what is left')
assert.deepEqual(setPickQty(pick, coffee, 0), {}, '0 removes it')
assert.deepEqual(togglePick(pick, coffee), {}, 'a second tap removes it')
assert.deepEqual(togglePick({}, done), {}, 'nothing left to refund')
assert.deepEqual(pickAll(items), { 1: 2, 2: 0.25 })
assert.equal(refundTotal(items, pickAll(items)), 9)
assert.equal(defaultMethod(items, { 2: 0.25 }), 'card')
assert.equal(defaultMethod(items, pickAll(items)), 'cash')
assert.equal(needsApproval(items, pickAll(items)), false)
assert.equal(needsApproval([{ ...coffee, mine: false }], { 1: 1 }), true)
})