feat(backend,waiter,terminal,manager): split the bill by amount

Owner 2026-11-23 (plan 6F.6). Venue setting payments.split_amount (off | two_equal | two_custom |
multiple_equal, each level with the ones before; default off) and payments.split_max_parts (10);
key ordering.payments.split_amount (everyone who takes payments; Alembic 0050 grants it).
POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status 'split': sold, no shift,
no payment method) and adds part lines (system product split_part, "Split bill 1/3", printed and
served; equal parts with the remainder on the last, or two parts with part 1 typed). Parts are paid
like any line (cash, card, tab). POST .../split-bills/{bill}/undo while no part is paid or tabbed.
Counting (services/sales.py): settled lines are the sales, parts never (a refunded part comes off
the settled lines by share); drawers and payment methods count the parts. Older reports use
split_bills.sold_filter / counts_as_sale. Locks: parts can't be cancelled, moved, combined or
re-priced; settled lines are no longer active; closing or cancelling an order with unpaid parts is
refused. Fiscal: one receipt with the settled lines when the last part is paid, with each method's
amount (txt driver: CD per card amount, then CR for cash).
Waiter: Pay -> "Split the amount" (pre-filled from the customers), the split bill above the lines
with Undo. Counter: "By amount" in the payment (quick sale split and paid at once, Q-4; a table's
lines split then paid). Manager: the pay dialog splits, the order shows its split bills, Settings ->
Operation card. Shared rules in @xenia/ordering/split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 10:57:54 +02:00
co-authored by Claude Opus 5.5
parent 72e175ab73
commit 3eeafb565a
54 changed files with 1707 additions and 105 deletions
+80 -10
View File
@@ -3,27 +3,41 @@
// by row. The caller's `submit({ method, rowMethods, cashGiven })` makes the one call: a quick
// sale (POST /api/pos/sales, rows = cart lines) or a table's items (POST /api/pos/orders/{id}/pay,
// rows = order items). Cash with the exact amount is pre-selected: Charge → Take = two taps.
// "Split the amount" (6F.6): the total cut into equal parts (or two parts in any ratio), each paid
// now by cash or card: `submit({ method: 'amount', split: { mode, parts, first_amount, methods } })`.
import { useEffect, useRef, useState } from 'react'
import { Banknote, Check, CreditCard, Split } from 'lucide-react'
import { Banknote, Check, CreditCard, Divide, Minus, Plus, Split } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input } from '@xenia/ui'
import { defaultParts, splitAmounts } from '@xenia/ordering/split'
import { Button, Dialog, IconButton, Input } from '@xenia/ui'
import { changeFor, quickAmounts, splitPayments } from './logic/cart'
import { useDisplay } from './usePos'
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'}`
/** rows: [{ label, total }]; submit({ method: 'cash'|'card'|'split', rowMethods, payments, cashGiven })
* → the result passed to onPaid. `payments` are by row index (splitPayments). */
export default function PaymentDialog({ total, rows, submit, onPaid, onClose }) {
/** rows: [{ label, total }]; submit({ method: 'cash'|'card'|'split'|'amount', rowMethods, payments, split, cashGiven })
* → the result passed to onPaid. `payments` are by row index (splitPayments). `amountSplit`
* ({ choices, customerCount }, 6F.6) offers "Split the amount" when the venue and the key allow it. */
export default function PaymentDialog({ total, rows, submit, onPaid, onClose, amountSplit = null }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const totals = rows.map(r => r.total)
const [method, setMethod] = useState('cash')
const [split, setSplit] = useState(() => rows.map(() => 'card'))
const parts = splitPayments(split, totals)
const cashDue = method === 'cash' ? total : method === 'split' ? parts.cash : 0
// 6F.6: by amount
const maxParts = amountSplit?.choices.maxParts ?? 2
const [nParts, setNParts] = useState(() => defaultParts(amountSplit?.customerCount, maxParts))
const [shareMode, setShareMode] = useState('equal')
const [firstText, setFirstText] = useState('')
const [partMethods, setPartMethods] = useState(() => Array(50).fill('cash'))
const uneven = shareMode === 'custom' && nParts === 2
const firstAmount = firstText.trim() ? parseNumber(firstText, { decimals: 2, allowNegative: false }) : null
const amounts = method === 'amount' ? splitAmounts(total, uneven ? 'custom' : 'equal', nParts, firstAmount) : null
const amountCash = amounts ? Math.round(amounts.reduce((s, a, i) => s + (partMethods[i] === 'cash' ? a : 0), 0) * 100) / 100 : 0
const cashDue = method === 'cash' ? total : method === 'split' ? parts.cash : method === 'amount' ? amountCash : 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
@@ -43,8 +57,11 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
setBusy(true)
setError('')
const payments = method === 'split' ? parts.payments : [{ method, lines: rows.map((_, i) => i) }]
const bySplit = method === 'amount'
? { mode: uneven ? 'custom' : 'equal', parts: amounts.length, first_amount: uneven ? amounts[0] : undefined, methods: partMethods.slice(0, amounts.length) }
: undefined
try {
const result = await submit({ method, rowMethods: split, payments, cashGiven: cashDue > 0 ? (given ?? cashDue) : null })
const result = await submit({ method, rowMethods: split, payments, split: bySplit, cashGiven: cashDue > 0 ? (given ?? cashDue) : null })
paidRef.current = true
display({ mode: 'paid', total, paid: result?.cash_given ?? total, change: result?.change ?? 0 })
onPaid(result)
@@ -59,16 +76,18 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
<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))}
<Button size="lg" icon={<Check size={18} />} loading={busy}
disabled={short || (method === 'split' && (!parts.cash || !parts.card)) || (method === 'amount' && !amounts)}
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')}
: method === 'amount' ? t('pos.pay.confirmAmount', { count: amounts?.length ?? nParts })
: 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]) => (
{[['cash', Banknote], ['card', CreditCard], ['split', Split], ...(amountSplit ? [['amount', Divide]] : [])].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>
@@ -99,6 +118,57 @@ export default function PaymentDialog({ total, rows, submit, onPaid, onClose })
</div>
)}
{method === 'amount' && (
<div className="grid gap-3" data-testid="amount-split">
{maxParts > 2 && (
<div className="flex items-center justify-center gap-4">
<IconButton label={t('pos.pay.fewerParts')} variant="secondary" disabled={nParts <= 2}
onClick={() => { setNParts(n => Math.max(2, n - 1)); setShareMode('equal') }} data-testid="amount-fewer"><Minus size={18} /></IconButton>
<span className="text-display font-semibold min-w-16 text-center" data-testid="amount-parts">{nParts}</span>
<IconButton label={t('pos.pay.moreParts')} variant="secondary" disabled={nParts >= maxParts}
onClick={() => { setNParts(n => Math.min(maxParts, n + 1)); setShareMode('equal') }} data-testid="amount-more"><Plus size={18} /></IconButton>
</div>
)}
{amountSplit.choices.custom && nParts === 2 && (
<div className="flex gap-2">
{['equal', 'custom'].map(m => (
<button key={m} type="button" aria-pressed={shareMode === m} onClick={() => setShareMode(m)} data-testid={`amount-${m}`}
className={`flex-1 min-h-[var(--x-control-md)] rounded-control text-body font-medium ${shareMode === m ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
{t(`pos.pay.share.${m}`)}
</button>
))}
</div>
)}
{uneven && (
<label className="grid gap-1 text-label text-ink-2">
{t('pos.pay.firstPart')}
<Input inputMode="decimal" value={firstText} onChange={e => setFirstText(e.target.value)} data-testid="amount-first"
placeholder={formatMoney(Math.round(total * 50) / 100)} />
</label>
)}
{amounts ? (
<div className="grid gap-1 max-h-60 overflow-y-auto">
{amounts.map((a, i) => (
<div key={i} className="flex items-center gap-2 py-1 border-b border-line" data-testid="amount-part">
<span className="flex-1 text-body text-ink">{t('pos.pay.part', { n: i + 1, of: amounts.length })}</span>
<span className="text-body font-medium">{formatMoney(a)}</span>
<span className="flex gap-1">
{['cash', 'card'].map(m => (
<button key={m} type="button" aria-pressed={partMethods[i] === m} data-part={`${i}-${m}`}
onClick={() => setPartMethods(pm => pm.map((x, j) => (j === i ? m : x)))}
className={`px-3 min-h-[var(--x-control-sm)] rounded-control text-label font-medium ${partMethods[i] === m ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2'}`}>
{t(`pos.pay.${m}`)}
</button>
))}
</span>
</div>
))}
</div>
) : <p className="text-label text-danger-ink">{t('pos.pay.splitInvalid')}</p>}
<p className="text-caption text-ink-2">{t('pos.pay.amountHint')}</p>
</div>
)}
{method === 'card' && <p className="text-body text-ink-2">{t('pos.pay.cardHint', { amount: formatMoney(total) })}</p>}
{cashDue > 0 && (
+8 -3
View File
@@ -14,7 +14,8 @@
import { useEffect, useMemo, useState } from '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 { useAllowed, useCan, useModule } from '@xenia/access'
import { splitChoices as splitChoicesOf } from '@xenia/ordering/split'
import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui'
import { useLiveEvent } from '../../device/context'
import { playChime } from './chime'
@@ -65,6 +66,10 @@ function Counter({ menu, t }) {
// a discount is a price changed in the cart (6F.3): none when the venue turned that off
const mayDiscount = useCan('ordering.prices.modify')
const canDiscount = menu.settings.price_change === 'off' ? null : mayDiscount // null: no discount at all
// 6F.6: splitting a bill by amount (the venue's level, the key; a manager may approve it once)
const splitAccess = useAllowed('ordering.payments.split_amount')
const splitChoices = splitChoicesOf(menu.settings.split_amount, menu.settings.split_max_parts ?? 10)
const amountSplit = splitChoices.on && splitAccess !== 'no' ? { choices: splitChoices } : null
const toast = useToast()
const onlineModule = useModule('connect_orders')
const handlesOnline = useCan('connect_orders.manage')
@@ -249,9 +254,9 @@ function Counter({ menu, t }) {
</div>
</main>
{atTable
? <TablePanel key={table.id} table={table} cart={tableCart} setCart={setTableCart} byId={byId} canDiscount={canDiscount}
? <TablePanel key={table.id} table={table} cart={tableCart} setCart={setTableCart} byId={byId} canDiscount={canDiscount} amountSplit={amountSplit}
onBack={leaveTable} onTablesChanged={tables.reload} />
: <SaleCart cart={saleCart} setCart={setSaleCart} orderType={orderType} setOrderType={setOrderType} byId={byId} canDiscount={canDiscount} />}
: <SaleCart cart={saleCart} setCart={setSaleCart} orderType={orderType} setOrderType={setOrderType} byId={byId} canDiscount={canDiscount} amountSplit={amountSplit} />}
</>
)}
+6 -4
View File
@@ -11,7 +11,7 @@ import { setLineQty } from './logic/cart'
import PaymentDialog from './PaymentDialog'
import { useDisplay, useQuote } from './usePos'
export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount }) {
export default function SaleCart({ cart, setCart, orderType, setOrderType, byId, canDiscount, amountSplit = null }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const toast = useToast()
@@ -36,8 +36,10 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId,
}, [cart, ready, quote.quote, paying, byId, display])
useEffect(() => () => display({ mode: 'idle' }), [display])
const submit = async ({ method, payments, cashGiven }) => (await client.post('/api/pos/sales', {
order_type: orderType, lines: cart, payments: method === 'split' ? payments : [{ method }], cash_given: cashGiven,
const submit = async ({ method, payments, split, cashGiven }) => (await client.post('/api/pos/sales', {
order_type: orderType, lines: cart, cash_given: cashGiven,
// 6F.6: split by amount, every part paid now (Q-4)
...(method === 'amount' ? { payments: [], split } : { payments: method === 'split' ? payments : [{ method }] }),
})).data
return (
@@ -76,7 +78,7 @@ export default function SaleCart({ cart, setCart, orderType, setOrderType, byId,
</div>
{paying && quote.quote && (
<PaymentDialog total={quote.quote.total} submit={submit}
<PaymentDialog total={quote.quote.total} submit={submit} amountSplit={amountSplit}
rows={cart.map((l, i) => ({ label: `${l.quantity}× ${byId.get(l.product_id)?.name ?? ''}`, total: quote.quote.lines[i].total }))}
onClose={() => setPaying(false)}
onPaid={result => {
+19 -8
View File
@@ -11,13 +11,13 @@ import { Button, Dialog, EmptyState, IconButton, Spinner, useToast } from '@xeni
import client from '../../api/client'
import CartLine from './CartLine'
import { setLineQty } from './logic/cart'
import { itemPayments, orderLines, orderSums, qtyLabel, tableState, toPay } from './logic/tables'
import { itemPayments, orderLines, orderSums, partPayments, qtyLabel, tableState, toPay } from './logic/tables'
import OneMore from './OneMore'
import PaymentDialog from './PaymentDialog'
import { PaidSummary } from './SaleCart'
import { useOrder, useQuote } from './usePos'
export default function TablePanel({ table, cart, setCart, byId, canDiscount, onBack, onTablesChanged }) {
export default function TablePanel({ table, cart, setCart, byId, canDiscount, onBack, onTablesChanged, amountSplit = null }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatTime } = useFormat()
const toast = useToast()
@@ -75,11 +75,20 @@ export default function TablePanel({ table, cart, setCart, byId, canDiscount, on
reload()
})
const payRows = chosen.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/${orderId}/pay`, {
payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }],
cash_given: cashGiven,
})).data
const payRows = chosen.map(l => ({ id: l.id, label: `${qtyLabel(l.quantity, l.unitType)} ${l.name}`, total: l.total, part: l.part }))
const submitPay = async ({ method, payments, split, cashGiven }) => {
let body
if (method === 'amount') {
// 6F.6: settle the lines into a split bill, then pay every part now, each by its method
const bill = (await client.post(`/api/orders/${orderId}/split-bills`, {
item_ids: paying.map(r => r.id), mode: split.mode, parts: split.parts, first_amount: split.first_amount,
})).data
body = { payments: partPayments(bill.part_ids, split.methods) }
} else {
body = { payments: method === 'split' ? itemPayments(payments, paying) : [{ method, item_ids: paying.map(r => r.id) }] }
}
return (await client.post(`/api/pos/orders/${orderId}/pay`, { ...body, cash_given: cashGiven })).data
}
const toggle = id => setSelected(sel => (sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id]))
@@ -179,6 +188,7 @@ export default function TablePanel({ table, cart, setCart, byId, canDiscount, on
{paying && (
<PaymentDialog total={orderSums(paying).total} rows={paying} submit={submitPay}
amountSplit={amountSplit && !paying.some(r => r.part) ? { ...amountSplit, customerCount: order?.customer_count } : null}
onClose={() => setPaying(null)}
onPaid={result => {
setPaying(null)
@@ -231,7 +241,8 @@ function OrderLine({ line, selected, onToggle }) {
</span>
<span className="text-body text-right">
{formatMoney(line.total)}
{line.paid && <span className="block text-caption text-success-ink">{t(`pos.table.paidBy.${line.method === 'card' ? 'card' : 'cash'}`)}</span>}
{line.paid && !line.settled && <span className="block text-caption text-success-ink">{t(`pos.table.paidBy.${line.method === 'card' ? 'card' : 'cash'}`)}</span>}
{line.settled && <span className="block text-caption text-info-ink">{t('pos.table.settled')}</span>}
{!line.paid && line.kds === 'done' && <span className="block text-caption text-success-ink">{t('pos.table.readyItem')}</span>}
</span>
</span>
+17 -6
View File
@@ -41,25 +41,28 @@ export function optionNames(selected) {
}
/** An order's items as the counter lists them (cancelled and written-off ones left out),
* unpaid first, each with its total. */
* unpaid first, each with its total. A split bill (6F.6): its parts are lines like any other
* (`part`), the lines it settled show with the paid ones (`settled`) and add up to nothing. */
export function orderLines(order) {
if (!order?.items) return []
const lines = order.items
.filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid')
.filter(i => i.status === 'active' || i.status === 'ready' || i.status === 'paid' || i.status === 'split')
.map(i => ({
id: i.id,
name: i.product_name ?? i.product?.name ?? '',
quantity: i.quantity,
unitType: i.unit_type,
total: round2((i.unit_price + (i.price_adjustment || 0)) * i.quantity),
paid: i.status === 'paid',
paid: i.status === 'paid' || i.status === 'split',
settled: i.status === 'split',
part: i.split_bill_id != null && i.status !== 'split',
method: i.payment_method,
options: optionNames(i.selected_options),
notes: i.notes,
kds: i.kds_status ?? 'pending',
system: i.system_key ?? null, // a line the system added: 'delivery_fee' (phase 3S)
// "+1" (6F.5): the product allows it, in pieces, not a deal's line
oneMore: !!i.product?.one_more_enabled && (i.unit_type ?? 'piece') === 'piece' && !i.deal_id && !i.linked_item_id,
oneMore: !!i.product?.one_more_enabled && (i.unit_type ?? 'piece') === 'piece' && !i.deal_id && !i.linked_item_id && i.status !== 'split',
}))
return [...lines.filter(l => !l.paid), ...lines.filter(l => l.paid)]
}
@@ -67,8 +70,16 @@ export function orderLines(order) {
/** { total, paid, unpaid, unpaidIds } of the lines. */
export function orderSums(lines) {
const sum = ls => round2(ls.reduce((s, l) => s + l.total, 0))
const open = lines.filter(l => !l.paid)
return { total: sum(lines), paid: sum(lines.filter(l => l.paid)), unpaid: sum(open), unpaidIds: open.map(l => l.id) }
const counted = lines.filter(l => !l.settled) // 6F.6: the parts pay for the settled lines
const open = counted.filter(l => !l.paid)
return { total: sum(counted), paid: sum(counted.filter(l => l.paid)), unpaid: sum(open), unpaidIds: open.map(l => l.id) }
}
/** A split bill's parts paid now (6F.6): one payment per method, as POST /api/pos/orders/{id}/pay takes. */
export function partPayments(partIds, methods) {
return ['cash', 'card']
.map(method => ({ method, item_ids: partIds.filter((_, i) => (methods[i] ?? 'cash') === method) }))
.filter(p => p.item_ids.length)
}
/** What "Pay" takes: the selected unpaid lines, or every unpaid line when none is selected. */
+15
View File
@@ -129,6 +129,21 @@ test('tables at the counter: state, zones, order lines, what Pay takes (3.3c)',
assert.equal(qtyLabel(0.5, 'liter'), '0.5 L')
})
test('a split bill at the counter: parts are lines, settled lines add up to nothing (6F.6)', async () => {
const { orderLines, orderSums, partPayments, toPay } = await import('../src/apps/pos/logic/tables.js')
const order = { items: [
{ id: 1, product_name: 'Burger', quantity: 1, unit_price: 10, status: 'split', split_bill_id: 4 },
{ id: 2, product_name: 'Freddo', quantity: 2, unit_price: 2.5, status: 'split', split_bill_id: 4 },
{ id: 3, product_name: 'Split bill 1/2', quantity: 1, unit_price: 4.5, status: 'paid', payment_method: 'cash', split_bill_id: 4 },
{ id: 4, product_name: 'Split bill 2/2', quantity: 1, unit_price: 10.5, status: 'active', split_bill_id: 4 },
] }
const lines = orderLines(order)
assert.deepEqual(lines.map(l => [l.id, l.paid, !!l.settled, !!l.part]), [[4, false, false, true], [1, true, true, false], [2, true, true, false], [3, true, false, true]])
assert.deepEqual(orderSums(lines), { total: 15, paid: 4.5, unpaid: 10.5, unpaidIds: [4] })
assert.deepEqual(toPay(lines, []).map(l => l.id), [4])
assert.deepEqual(partPayments([7, 8, 9], ['cash', 'card', 'cash']), [{ method: 'cash', item_ids: [7, 9] }, { method: 'card', item_ids: [8] }])
})
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' })