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
@@ -69,9 +69,36 @@ function OrderingSettings() {
</SettingsCard>
<PriceChangeSettings s={s} />
<QuantitySettings s={s} />
<SplitSettings s={s} />
</>)
}
/** Splitting a bill by amount (6F.6), each level with the ones before. Who may:
* ordering.payments.split_amount ("What each role may do", a person's permissions). */
function SplitSettings({ s }) {
const { t } = useTranslation('manager')
const q = k => t(`settings.split.${k}`)
const id = useId()
const maxId = useId()
const level = s.get('payments.split_amount', 'off')
return (
<SettingsCard title={q('title')} description={q('intro')} testId="settings-split">
<SettingRow label={q('when')} hint={q('whenHint')} tip={q('whenTip')} htmlFor={id}>
<Select id={id} value={level} disabled={s.saving} data-testid="setting-payments.split_amount"
onChange={e => s.save('payments.split_amount', e.target.value)}
options={['off', 'two_equal', 'two_custom', 'multiple_equal'].map(v => ({ value: v, label: q(`levels.${v}`) }))} />
</SettingRow>
{level === 'multiple_equal' && (
<SettingRow label={q('max')} hint={q('maxHint')} htmlFor={maxId}>
<Select id={maxId} value={String(s.get('payments.split_max_parts', '10'))} disabled={s.saving} data-testid="setting-payments.split_max_parts"
onChange={e => s.save('payments.split_max_parts', e.target.value)}
options={[3, 4, 5, 6, 8, 10, 12, 15, 20].map(n => ({ value: String(n), label: String(n) }))} />
</SettingRow>
)}
</SettingsCard>
)
}
/** A sent line's quantity changed without a new ticket (6F.5). Who may: ordering.items.change_quantity;
* lowering also needs ordering.orders.cancel ("What each role may do", a person's permissions). */
function QuantitySettings({ s }) {
@@ -22,7 +22,9 @@ import OrderPeople from './OrderPeople'
import PayDialog from './PayDialog'
import PrintProblemsCard from './PrintProblemsCard'
import { AuditList, MoveList, PriceEventList } from './OrderHistory'
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
import { closeStep, isSplitPart, totals, unpaidIds, venueRules } from './orderLogic'
import { SplitBillsCard } from './SplitAmount'
import { useCan } from '@xenia/access'
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
@@ -78,6 +80,7 @@ function OrderView({ orderId }) {
const venue = useVenue()
const [tab, setTab] = useState('order')
const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after }
const maySplit = useCan('ordering.payments.split_amount') // 6F.6
const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel'
const [printerId, setPrinterId] = useState('')
@@ -156,6 +159,7 @@ function OrderView({ orderId }) {
</div>
<PrintProblemsCard orderId={order.id} />
<SplitBillsCard order={order} canUndo={maySplit} onChanged={refresh} />
{tab === 'order' && (
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
@@ -172,6 +176,9 @@ function OrderView({ orderId }) {
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
split={venue.split.on && maySplit && !paying.thenClose && !order.items.some(i => paying.ids.includes(i.id) && isSplitPart(i))
? { choices: venue.split, customerCount: order.customer_count } : null}
onSplit={() => { toast.success(t('orders.split.done')); paying.after?.(); setPaying(null); refresh() }}
onClose={() => setPaying(null)}
onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
@@ -3,17 +3,20 @@
// "instant-pay close": the rest is paid and the order closed in one go, for venues that don't
// close with unpaid items (orders.close_with_unpaid, 4.8).
import { useState } from 'react'
import { Banknote, CreditCard } from 'lucide-react'
import { Banknote, CreditCard, Divide } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog } from '@xenia/ui'
import client from '../../api/client'
import { SplitAmountForm } from './SplitAmount'
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, onClose, onDone }) {
/** `split` ({ choices, customerCount }, 6F.6): offers "Split the amount" instead of paying now. */
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, split = null, onSplit, onClose, onDone }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [busy, setBusy] = useState(null)
const [error, setError] = useState(null)
const [splitting, setSplitting] = useState(false)
async function pay(method) {
setBusy(method)
@@ -44,6 +47,13 @@ export default function PayDialog({ orderId, itemIds, amount, card = true, thenC
</Button>
</div>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
{split && !splitting && (
<Button variant="ghost" icon={<Divide size={18} />} disabled={!!busy} onClick={() => setSplitting(true)} data-testid="pay-split">{t('orders.split.button')}</Button>
)}
{split && splitting && (
<SplitAmountForm orderId={orderId} itemIds={itemIds} amount={amount} choices={split.choices} customerCount={split.customerCount}
onCancel={() => setSplitting(false)} onDone={onSplit} />
)}
</div>
</Dialog>
)
@@ -0,0 +1,113 @@
// Splitting a bill by amount in the manager (plan 6F.6), as the phones and the counter do: the chosen
// lines are settled into a split bill and cut into equal parts (pre-filled from the customers) or, for
// two parts, any amounts; each part is then paid like any line. Undo while no part is paid.
import { useState } from 'react'
import { Minus, Plus, Undo2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { defaultParts, splitAmounts } from '@xenia/ordering/split'
import { Button, IconButton, Input } from '@xenia/ui'
import toast from 'react-hot-toast'
import client from '../../api/client'
/** The part of the pay dialog that splits instead of paying (choices from splitChoices()). */
export function SplitAmountForm({ orderId, itemIds, amount, choices, customerCount, onDone, onCancel }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [parts, setParts] = useState(() => defaultParts(customerCount, choices.maxParts))
const [mode, setMode] = useState('equal')
const [first, setFirst] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState(null)
const uneven = mode === 'custom' && parts === 2
const typed = first.trim() ? parseNumber(first, { decimals: 2, allowNegative: false }) : null
const amounts = splitAmounts(amount, uneven ? 'custom' : 'equal', parts, typed)
const step = d => { setParts(p => Math.max(2, Math.min(choices.maxParts, p + d))); setMode('equal') }
async function split() {
setBusy(true)
setError(null)
try {
await client.post(`/api/orders/${orderId}/split-bills`, uneven
? { item_ids: itemIds, mode: 'custom', parts: 2, first_amount: amounts[0] }
: { item_ids: itemIds, mode: 'equal', parts })
onDone()
} catch (err) {
setError(errorMessage(err, t))
} finally { setBusy(false) }
}
return (
<div className="grid gap-3 border-t border-line pt-3" data-testid="split-form">
{choices.maxParts > 2 && (
<div className="flex items-center justify-center gap-4">
<IconButton label={t('orders.split.fewer')} variant="secondary" disabled={parts <= 2} onClick={() => step(-1)}><Minus size={18} /></IconButton>
<span className="text-display font-semibold min-w-16 text-center tabular-nums" data-testid="split-parts">{parts}</span>
<IconButton label={t('orders.split.more')} variant="secondary" disabled={parts >= choices.maxParts} onClick={() => step(1)} data-testid="split-more"><Plus size={18} /></IconButton>
</div>
)}
{choices.custom && parts === 2 && (
<div className="grid grid-cols-2 gap-2">
{['equal', 'custom'].map(m => (
<Button key={m} size="sm" variant={mode === m ? 'primary' : 'secondary'} aria-pressed={mode === m} onClick={() => setMode(m)} data-testid={`split-${m}`}>
{t(`orders.split.${m}`)}
</Button>
))}
</div>
)}
{uneven && (
<label className="grid gap-1 text-label text-ink-2">
{t('orders.split.first')}
<Input inputMode="decimal" value={first} onChange={e => setFirst(e.target.value)} placeholder={formatMoney(Math.round(amount * 50) / 100)} data-testid="split-first" />
</label>
)}
{amounts ? (
<ul className="grid gap-0.5 text-body" data-testid="split-preview">
{amounts.map((a, i) => (
<li key={i} className="flex justify-between"><span>{t('orders.split.part', { n: i + 1, of: amounts.length })}</span><span className="tabular-nums font-medium">{formatMoney(a)}</span></li>
))}
</ul>
) : <p className="text-label text-danger-ink">{t('orders.split.invalid')}</p>}
<p className="text-caption text-ink-2">{t('orders.split.hint')}</p>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={onCancel} disabled={busy}>{t('orders.back')}</Button>
<Button loading={busy} disabled={!amounts} onClick={split} data-testid="split-confirm">{t('orders.split.confirm', { count: amounts?.length ?? parts })}</Button>
</div>
</div>
)
}
/** The order's split bills: parts, paid so far, and Undo while nothing is paid. */
export function SplitBillsCard({ order, canUndo, onChanged }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [busy, setBusy] = useState(null)
const bills = order.split_bills ?? []
if (!bills.length) return null
async function undo(bill) {
setBusy(bill.id)
try {
await client.post(`/api/orders/${order.id}/split-bills/${bill.id}/undo`)
toast.success(t('orders.split.undone'))
onChanged()
} catch (err) {
toast.error(errorMessage(err, t))
} finally { setBusy(null) }
}
return (
<section className="rounded-card border border-line bg-surface shadow-raised p-3 grid gap-2" data-testid="split-bills">
{bills.map(b => (
<div key={b.id} className="flex flex-wrap items-center gap-3" data-testid="split-bill">
<span className="flex-1 min-w-0">
<span className="block text-body font-medium text-ink">{t('orders.split.bill', { count: b.parts, total: formatMoney(b.total) })}</span>
<span className="block text-label text-ink-2">{t('orders.split.paid', { paid: formatMoney(b.paid), due: formatMoney(Math.max(0, b.total - b.paid)) })}</span>
</span>
{canUndo && b.can_undo && (
<Button size="sm" variant="secondary" icon={<Undo2 size={16} />} loading={busy === b.id} onClick={() => undo(b)} data-testid="split-undo">{t('orders.split.undo')}</Button>
)}
</div>
))}
</section>
)
}
@@ -3,6 +3,8 @@
// items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise
// the rest is paid first.
import { splitChoices, splitLevel, splitMax } from '@xenia/ordering/split'
export const OPEN_STATUSES = ['open', 'partially_paid', 'paid']
export const isOpen = order => !!order && OPEN_STATUSES.includes(order.status)
@@ -59,9 +61,13 @@ export function closeStep(order, closeWithUnpaid) {
/** The venue's settings rows (GET /api/settings/) → the two that matter here. */
export function venueRules(settings) {
const v = key => settings?.[key]?.value
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false' }
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false',
split: splitChoices(splitLevel(settings), splitMax(settings)) } // 6F.6
}
/** A split bill's part line (6F.6): paid on its own, never split again. */
export const isSplitPart = item => item?.split_bill_id != null && item.status !== 'split'
/** The cart's lines as the server takes them, plus the order's note (POST /api/orders/{id}/items). */
export function sendBody(cart, note) {
return { lines: cart.map(c => c.line), order_note: note?.trim() || null }