feat(terminal): quick sale at the counter: cash/card/split, change, cash drawer, fiscal (platform-v2 3.3b)
- POST /api/pos/sales: all checks first (shift, lines, payment split, cash given, discount → ordering.prices.modify or manager approval, fiscal VAT groups), then the existing open_order / add_items / pay_items functions, so tickets, KDS, price events, shift totals and the fiscal receipt work as for any order. - Cash drawer: printer_service.open_cash_drawer (ESC @ + ESC p 0 25 250) to the screen's receipt printer on cash, logged and audited (DRAWER_OPENED / DRAWER_FAILED). - orders._can_access_order: the people assigned to an order may act on it (a cashier's own takeaway order); pos_cart prices a batch with the lines before it, as add_items does. - Terminal: Charge → payment dialog (exact cash pre-selected, quick amounts, change, card, split by line), per-line discounts, sale summary and "Same again". - Tests: backend +6 (socket printer receives the drawer kick, fiscal file in the bridge folder), terminal unit +1, terminal.mjs +9. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
// Taking the payment at the counter (plan step 3.3b, D-26): cash (amount given → change,
|
||||
// quick amounts), card (typed on the card terminal, recorded as card), or split between them
|
||||
// by line. One call does the whole sale (POST /api/pos/sales): order, kitchen tickets,
|
||||
// payment(s) on the cashier's shift, fiscal receipt, cash drawer. Cash with the exact amount
|
||||
// is pre-selected: Charge → Cash → Take = three taps.
|
||||
import { useState } from 'react'
|
||||
import { Banknote, Check, CreditCard, Split } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Input } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { changeFor, quickAmounts, splitPayments } from './logic/cart'
|
||||
|
||||
const tab = on => `flex-1 min-h-[var(--x-control-lg)] rounded-control flex items-center justify-center gap-2 text-body-lg 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 PaymentDialog({ cart, quote, orderType, names, onPaid, onClose }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
const total = quote.total
|
||||
const totals = quote.lines.map(l => l.total)
|
||||
const [method, setMethod] = useState('cash')
|
||||
const [split, setSplit] = useState(() => cart.map(() => 'card'))
|
||||
const parts = splitPayments(split, totals)
|
||||
const cashDue = method === 'cash' ? total : method === 'split' ? parts.cash : 0
|
||||
const [givenText, setGivenText] = useState('') // empty = the exact amount
|
||||
const given = givenText.trim() === '' ? null : parseNumber(givenText, { decimals: 2, allowNegative: false })
|
||||
const change = cashDue > 0 ? changeFor(given ?? cashDue, cashDue) : null
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const short = cashDue > 0 && change == null
|
||||
|
||||
const pay = async () => {
|
||||
if (busy || short) return
|
||||
setBusy(true)
|
||||
setError('')
|
||||
const payments = method === 'split' ? parts.payments : [{ method }]
|
||||
try {
|
||||
const { data } = await client.post('/api/pos/sales', {
|
||||
order_type: orderType, lines: cart, payments, cash_given: cashDue > 0 ? (given ?? cashDue) : null,
|
||||
})
|
||||
onPaid(data)
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, t))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onClose={busy ? undefined : onClose} size="md" title={t('pos.pay.title', { total: formatMoney(total) })}
|
||||
footer={<>
|
||||
<Button variant="secondary" size="lg" onClick={onClose} disabled={busy}>{t('pos.dialog.close')}</Button>
|
||||
<Button size="lg" icon={<Check size={18} />} loading={busy} disabled={short || (method === 'split' && (!parts.cash || !parts.card))}
|
||||
onClick={pay} data-testid="pay-confirm">
|
||||
{method === 'card' ? t('pos.pay.confirmCard', { amount: formatMoney(total) })
|
||||
: method === 'cash' ? t('pos.pay.confirmCash', { amount: formatMoney(total) })
|
||||
: t('pos.pay.confirmSplit')}
|
||||
</Button>
|
||||
</>}>
|
||||
<div className="grid gap-4" data-testid="payment-dialog">
|
||||
<div className="flex gap-2" role="radiogroup" aria-label={t('pos.pay.method')}>
|
||||
{[['cash', Banknote], ['card', CreditCard], ['split', Split]].map(([m, Icon]) => (
|
||||
<button key={m} type="button" role="radio" aria-checked={method === m} className={tab(method === m)} onClick={() => { setMethod(m); setGivenText('') }} data-testid={`pay-${m}`}>
|
||||
<Icon size={18} />{t(`pos.pay.${m}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{method === 'split' && (
|
||||
<div className="grid gap-1" data-testid="split-lines">
|
||||
{cart.map((line, i) => (
|
||||
<div key={i} className="flex items-center gap-2 py-1 border-b border-line">
|
||||
<span className="flex-1 min-w-0 text-body text-ink truncate">{line.quantity}× {names[i]}</span>
|
||||
<span className="text-body text-ink-2">{formatMoney(totals[i])}</span>
|
||||
<span className="flex gap-1">
|
||||
{['cash', 'card'].map(m => (
|
||||
<button key={m} type="button" aria-pressed={split[i] === m} data-split={`${i}-${m}`}
|
||||
onClick={() => setSplit(s => s.map((x, j) => (j === i ? m : x)))}
|
||||
className={`px-3 min-h-[var(--x-control-sm)] rounded-control text-label font-medium ${split[i] === m ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
|
||||
{t(`pos.pay.${m}`)}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex justify-between text-body pt-1">
|
||||
<span>{t('pos.pay.cashPart', { amount: formatMoney(parts.cash) })}</span>
|
||||
<span>{t('pos.pay.cardPart', { amount: formatMoney(parts.card) })}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{method === 'card' && <p className="text-body text-ink-2">{t('pos.pay.cardHint', { amount: formatMoney(total) })}</p>}
|
||||
|
||||
{cashDue > 0 && (
|
||||
<div className="grid gap-2">
|
||||
<label className="grid gap-1 text-label text-ink-2">
|
||||
{t('pos.pay.given')}
|
||||
<Input inputMode="decimal" size="lg" value={givenText} onChange={e => setGivenText(e.target.value)} data-testid="cash-given"
|
||||
placeholder={t('pos.pay.exact', { amount: formatMoney(cashDue) })} />
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{quickAmounts(cashDue).map(a => (
|
||||
<Button key={a} variant="secondary" onClick={() => setGivenText(a.toFixed(2))} data-testid="quick-amount">{formatMoney(a)}</Button>
|
||||
))}
|
||||
</div>
|
||||
<div className={`text-heading font-semibold ${short ? 'text-danger-ink' : 'text-ink'}`} data-testid="change">
|
||||
{short ? t('pos.pay.short') : t('pos.pay.change', { amount: formatMoney(change) })}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,14 +1,17 @@
|
||||
// The counter POS screen (plan step 3.3a): categories on the left, the product grid with a
|
||||
// search on top, the cart on the right. 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: the menu's and the cart's quote. Paying comes in 3.3b.
|
||||
// the backend's: the menu's and the cart's quote. Charge → PaymentDialog (3.3b); after a sale
|
||||
// the cart shows what happened and "Same again".
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Info, Minus, Plus, Search, ShoppingBag, Trash2, Utensils, X } from 'lucide-react'
|
||||
import { Banknote, Info, Minus, Plus, Repeat, Search, ShoppingBag, Trash2, Utensils, X } from 'lucide-react'
|
||||
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
|
||||
import { Button, EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
|
||||
import { useCan } from '@xenia/access'
|
||||
import { Button, EmptyState, IconButton, Input, Select, Spinner, useToast } from '@xenia/ui'
|
||||
import {
|
||||
addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf,
|
||||
DISCOUNTS, addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf,
|
||||
} from './logic/cart'
|
||||
import PaymentDialog from './PaymentDialog'
|
||||
import ProductDialog from './ProductDialog'
|
||||
import { useMenu, useQuote } from './usePos'
|
||||
|
||||
@@ -27,7 +30,12 @@ function Counter({ menu, t }) {
|
||||
const [orderType, setOrderType] = useState(menu.settings.default_order_type)
|
||||
const [cart, setCart] = useState([])
|
||||
const [dialog, setDialog] = useState(null) // product
|
||||
const [paying, setPaying] = useState(false)
|
||||
const [lastSale, setLastSale] = useState(null) // { lines, orderType, result }
|
||||
const quote = useQuote(cart, orderType)
|
||||
const toast = useToast()
|
||||
const canDiscount = useCan('ordering.prices.modify')
|
||||
const ready = cart.length > 0 && !quote.pending && !quote.error && quote.quote?.lines?.length === cart.length
|
||||
|
||||
const byId = useMemo(() => new Map(menu.products.map(p => [p.id, p])), [menu.products])
|
||||
const categories = useMemo(() => categoriesWithProducts(menu.categories, menu.products), [menu])
|
||||
@@ -84,11 +92,13 @@ function Counter({ menu, t }) {
|
||||
))}
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{cart.length === 0 && lastSale && <SaleDone sale={lastSale} onAgain={() => { setCart(lastSale.lines); setOrderType(lastSale.orderType); setLastSale(null) }} />}
|
||||
{cart.length === 0
|
||||
? <EmptyState compact title={t('pos.cartEmpty')} description={t('pos.cartEmptyBody')} />
|
||||
? !lastSale && <EmptyState compact title={t('pos.cartEmpty')} description={t('pos.cartEmptyBody')} />
|
||||
: cart.map((line, i) => (
|
||||
<CartLine key={i} line={line} priced={quote.quote?.lines?.[i]} product={byId.get(line.product_id)}
|
||||
onQty={q => setCart(c => setLineQty(c, i, q))} />
|
||||
<CartLine key={i} line={line} priced={quote.quote?.lines?.[i]} product={byId.get(line.product_id)} canDiscount={canDiscount}
|
||||
onQty={q => setCart(c => setLineQty(c, i, q))}
|
||||
onDiscount={pct => setCart(c => c.map((l, j) => (j === i ? { ...l, discount_pct: pct || undefined } : l)))} />
|
||||
))}
|
||||
</div>
|
||||
<div className="border-t border-line p-3 grid gap-3">
|
||||
@@ -99,10 +109,24 @@ function Counter({ menu, t }) {
|
||||
{formatMoney(quote.quote?.total ?? 0)}
|
||||
</span>
|
||||
</div>
|
||||
<Button size="lg" icon={<Banknote size={20} />} disabled={!ready} onClick={() => setPaying(true)} data-testid="charge">
|
||||
{t('pos.charge', { total: formatMoney(quote.quote?.total ?? 0) })}
|
||||
</Button>
|
||||
<Button variant="secondary" icon={<Trash2 size={16} />} disabled={!cart.length} onClick={() => setCart([])}>{t('pos.clearCart')}</Button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{paying && quote.quote && (
|
||||
<PaymentDialog cart={cart} quote={quote.quote} orderType={orderType} names={cart.map(l => byId.get(l.product_id)?.name ?? '')}
|
||||
onClose={() => setPaying(false)}
|
||||
onPaid={result => {
|
||||
setPaying(false)
|
||||
setLastSale({ lines: cart, orderType, result })
|
||||
setCart([])
|
||||
toast.success(result.change != null ? t('pos.done.toastChange', { change: formatMoney(result.change) }) : t('pos.done.toast'))
|
||||
}} />
|
||||
)}
|
||||
|
||||
{dialog && (
|
||||
<ProductDialog product={dialog} orderType={orderType} onClose={() => setDialog(null)}
|
||||
onAdd={line => setCart(c => addLine(c, line))} />
|
||||
@@ -145,7 +169,26 @@ function ProductCard({ product, onTap, onInfo }) {
|
||||
)
|
||||
}
|
||||
|
||||
function CartLine({ line, priced, product, onQty }) {
|
||||
function SaleDone({ sale, onAgain }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
const r = sale.result
|
||||
return (
|
||||
<div className="m-3 p-4 rounded-card bg-success-soft text-success-ink grid gap-2" data-testid="sale-done" data-order={r.order_id}>
|
||||
<div className="text-title font-semibold">{t('pos.done.paid', { total: formatMoney(r.total) })}</div>
|
||||
{r.change != null && <div className="text-heading font-semibold" data-testid="sale-change">{t('pos.pay.change', { amount: formatMoney(r.change) })}</div>}
|
||||
<div className="text-label">
|
||||
{r.payments.map(p => t(`pos.done.${p.method}`, { amount: formatMoney(p.amount) })).join(' · ')}
|
||||
{r.drawer === 'opened' && ` · ${t('pos.done.drawerOpened')}`}
|
||||
{r.drawer === 'failed' && <span className="text-danger-ink"> · {t('pos.done.drawerFailed')}</span>}
|
||||
{r.fiscal === 'pending' && ` · ${t('pos.done.fiscal')}`}
|
||||
</div>
|
||||
<Button variant="secondary" icon={<Repeat size={16} />} onClick={onAgain} data-testid="same-again">{t('pos.done.again')}</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CartLine({ line, priced, product, canDiscount, onQty, onDiscount }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { formatMoney } = useFormat()
|
||||
const unit = product ? unitOf(product) : null
|
||||
@@ -169,7 +212,12 @@ function CartLine({ line, priced, product, onQty }) {
|
||||
<span className="min-w-12 text-center text-body font-semibold" data-testid="line-qty">{qtyText}</span>
|
||||
<IconButton size="sm" variant="secondary" label={t('pos.more')} onClick={() => onQty(line.quantity + step)}><Plus size={16} /></IconButton>
|
||||
{priced && line.quantity !== 1 && <span className="text-caption text-ink-3">{t('pos.each', { price: formatMoney(priced.unit_price) })}</span>}
|
||||
<span className="flex-1" />
|
||||
<Select size="sm" value={String(line.discount_pct ?? 0)} onChange={e => onDiscount(Number(e.target.value))} aria-label={t('pos.discount')}
|
||||
title={canDiscount ? undefined : t('pos.discountNeedsApproval')} data-testid="line-discount" className="w-36"
|
||||
options={DISCOUNTS.map(d => ({ value: String(d), label: d ? `−${d}%` : t('pos.noDiscount') }))} />
|
||||
</div>
|
||||
{priced?.discount ? <span className="text-label text-success-ink">{t('pos.discountLine', { pct: priced.discount_pct, amount: formatMoney(priced.discount) })}</span> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -187,3 +187,37 @@ export const UNITS = {
|
||||
}
|
||||
|
||||
export const unitOf = product => UNITS[product.unit_type] ?? null
|
||||
|
||||
// ── paying (3.3b) ───────────────────────────────────────────────────────────
|
||||
|
||||
/** Amounts a customer typically hands over for `total`: the exact amount, then the next
|
||||
* round amounts above it (notes of 5, 10, 20, 50, 100), at most five. */
|
||||
export function quickAmounts(total) {
|
||||
const out = [round2(total)]
|
||||
for (const step of [5, 10, 20, 50, 100]) {
|
||||
const v = Math.ceil((total + 0.0001) / step) * step
|
||||
if (v > total + 0.004 && !out.includes(v)) out.push(v)
|
||||
}
|
||||
return out.slice(0, 5)
|
||||
}
|
||||
|
||||
/** Change to give back (null when not enough was given). */
|
||||
export function changeFor(given, due) {
|
||||
if (given == null || Number.isNaN(given)) return null
|
||||
const c = round2(given - due)
|
||||
return c < 0 ? null : c
|
||||
}
|
||||
|
||||
/** Cash and card parts of a split: methods[i] is 'cash' | 'card' for line i, totals from the
|
||||
* quote. → { cash, card, payments } (payments as POST /api/pos/sales takes them). */
|
||||
export function splitPayments(methods, totals) {
|
||||
const lines = { cash: [], card: [] }
|
||||
methods.forEach((m, i) => lines[m].push(i))
|
||||
const sum = idx => round2(idx.reduce((s, i) => s + (totals[i] ?? 0), 0))
|
||||
const payments = ['card', 'cash'].filter(m => lines[m].length).map(m => ({ method: m, lines: lines[m] }))
|
||||
return { cash: sum(lines.cash), card: sum(lines.card), payments }
|
||||
}
|
||||
|
||||
export const DISCOUNTS = [0, 5, 10, 15, 20, 25, 50, 100]
|
||||
|
||||
const round2 = n => Math.round(n * 100) / 100
|
||||
|
||||
@@ -87,3 +87,14 @@ test('cart: the same choices add up, different choices are separate lines; 0 rem
|
||||
assert.deepEqual(setLineQty(cart, 0, 0).map(l => l.product_id), [1, 1])
|
||||
assert.equal(setLineQty(cart, 0, 0.30000000000000004)[0].quantity, 0.3)
|
||||
})
|
||||
|
||||
test('paying: quick amounts, change, split parts (3.3b)', async () => {
|
||||
const { changeFor, quickAmounts, splitPayments } = await import('../src/apps/pos/logic/cart.js')
|
||||
assert.deepEqual(quickAmounts(12.2), [12.2, 15, 20, 50, 100])
|
||||
assert.deepEqual(quickAmounts(20), [20, 25, 30, 40, 50])
|
||||
assert.equal(changeFor(20, 16), 4)
|
||||
assert.equal(changeFor(15, 16), null)
|
||||
assert.equal(changeFor(16, 16), 0)
|
||||
assert.deepEqual(splitPayments(['card', 'cash', 'cash'], [10, 3, 2.5]),
|
||||
{ cash: 5.5, card: 10, payments: [{ method: 'card', lines: [0] }, { method: 'cash', lines: [1, 2] }] })
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user