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
+10 -2
View File
@@ -5,6 +5,7 @@ import { useTranslation } from '@xenia/i18n'
import { fade } from '../logic/colour'
import OneMore from './OneMore'
import { canOneMore } from '../logic/lines'
import { countsInTotal, isPart, isSettled } from '../logic/split'
const fmtPrice = money
@@ -403,7 +404,14 @@ function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast, kd
].filter(Boolean).join(' ')}
style={nameColor ? { color: nameColor } : undefined}
>
{item.product?.name || `#${item.product_id}`}
{(isPart(item) ? item.product_name : item.product?.name) || `#${item.product_id}`}
{isSettled(item) && (
<span data-testid="item-settled" title={t('split.settledHint')}
style={{ marginLeft: 6, fontSize: 10, fontWeight: 800, padding: '1px 5px', borderRadius: 4, verticalAlign: 'middle',
background: 'rgb(var(--x-info-rgb) / 0.15)', color: 'var(--x-info)', border: '1px solid rgb(var(--x-info-rgb) / 0.35)' }}>
➗ {t('split.settled')}
</span>
)}
{courseBadge}
{sourceBadge}
{moved && (
@@ -696,7 +704,7 @@ export default function OrderSummary({ order, selectable = false, selectedIds =
const orderItemLayout = useTableViewStore(s => s.orderItemLayout || 'compact')
const activeItems = order.items?.filter(i => i.status !== 'cancelled') || []
const total = activeItems
.filter(i => i.status !== 'cancelled')
.filter(countsInTotal) // 6F.6: a split bill's settled lines are counted through its parts
.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
const paidTotal = activeItems
.filter(i => i.status === 'paid')
@@ -0,0 +1,113 @@
// Split the bill by amount (plan 6F.6): the chosen lines become one amount, cut into equal parts
// (pre-filled with the table's customers) or, for two parts, any ratio (a slider or part 1 typed).
// The server settles the lines and adds the parts; each part is then paid like any line.
import { useState } from 'react'
import { parseNumber, useTranslation } from '@xenia/i18n'
import { money } from '../i18n'
import { defaultParts, splitAmounts } from '../logic/split'
export default function SplitAmountModal({ total, count, choices, customerCount, busy, error, onSplit, onClose }) {
const { t } = useTranslation('waiter')
const [parts, setParts] = useState(() => defaultParts(customerCount, choices.maxParts))
const [mode, setMode] = useState('equal')
const [pct, setPct] = useState(50)
const [typed, setTyped] = useState('')
const custom = mode === 'custom' && parts === 2
const typedAmount = typed.trim() ? parseNumber(typed, { decimals: 2, allowNegative: false }) : null
const first = custom ? (typedAmount ?? Math.round(total * pct) / 100) : null
const amounts = splitAmounts(total, custom ? 'custom' : 'equal', parts, first)
const step = d => { setParts(p => Math.max(2, Math.min(choices.maxParts, p + d))); setMode('equal') }
const round = { width: 48, height: 48, borderRadius: '50%', border: '1.5px solid var(--border)', background: 'var(--bg3)', fontSize: 24, fontWeight: 700, color: 'var(--text)', cursor: 'pointer' }
const tab = on => ({
flex: 1, padding: '9px 0', borderRadius: 10, fontSize: 13, fontWeight: 700, cursor: 'pointer',
border: `2px solid ${on ? 'var(--x-info)' : 'rgb(var(--x-ink-rgb) / 0.1)'}`,
background: on ? 'rgb(var(--x-info-rgb) / 0.18)' : 'rgb(var(--x-ink-rgb) / 0.04)',
color: on ? 'var(--x-info-ink)' : 'var(--x-ink-2)',
})
return (
<div className="modal-overlay" onClick={busy ? undefined : onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="split-sheet">
<div className="modal-handle" />
<h2 className="modal-title">{t('split.title')}</h2>
<p style={{ textAlign: 'center', color: 'var(--x-ink-2)', margin: '0 0 2px' }}>{t('split.items', { count })}</p>
<p style={{ textAlign: 'center', color: 'var(--x-warning)', fontSize: 26, fontWeight: 800, margin: '0 0 14px' }}>{money(total)}</p>
{choices.maxParts > 2 && (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, marginBottom: 12 }}>
<button type="button" style={round} onClick={() => step(-1)} disabled={parts <= 2} aria-label={t('split.fewer')} data-testid="split-fewer">−</button>
<div style={{ textAlign: 'center', minWidth: 90 }}>
<div style={{ fontSize: 34, fontWeight: 800 }} data-testid="split-parts">{parts}</div>
<div style={{ fontSize: 12, color: 'var(--muted)', fontWeight: 700 }}>{t('split.partsLabel')}</div>
</div>
<button type="button" style={round} onClick={() => step(1)} disabled={parts >= choices.maxParts} aria-label={t('split.more')} data-testid="split-more">+</button>
</div>
)}
{choices.custom && parts === 2 && (
<div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
<button type="button" style={tab(mode === 'equal')} onClick={() => setMode('equal')} data-testid="split-equal">{t('split.equal')}</button>
<button type="button" style={tab(mode === 'custom')} onClick={() => setMode('custom')} data-testid="split-custom">{t('split.custom')}</button>
</div>
)}
{custom && (
<div style={{ marginBottom: 12 }}>
<input type="range" min={1} max={99} value={pct} aria-label={t('split.ratio')} data-testid="split-ratio"
onChange={e => { setPct(Number(e.target.value)); setTyped('') }} style={{ width: '100%' }} />
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--muted)', fontWeight: 700 }}>
<span>{typedAmount == null ? `${pct}%` : ''}</span><span>{typedAmount == null ? `${100 - pct}%` : ''}</span>
</div>
<label style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8, fontSize: 14 }}>
<span style={{ flex: 1 }}>{t('split.firstAmount')}</span>
<input type="text" inputMode="decimal" value={typed} onChange={e => setTyped(e.target.value)} placeholder="0,00"
data-testid="split-first" style={{ width: 110, padding: '8px 10px', borderRadius: 10, border: '1px solid var(--border)', background: 'var(--bg3)', color: 'var(--text)', fontSize: 16, textAlign: 'right' }} />
</label>
</div>
)}
<div style={{ background: 'var(--bg3)', border: '1px solid var(--border)', borderRadius: 12, padding: '8px 12px', marginBottom: 12 }} data-testid="split-preview">
{amounts ? amounts.map((a, n) => (
<div key={n} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, padding: '3px 0' }}>
<span>{t('split.part', { n: n + 1, of: amounts.length })}</span><strong>{money(a)}</strong>
</div>
)) : <p style={{ margin: 0, fontSize: 13, color: 'var(--x-danger)' }}>{t('split.invalid')}</p>}
</div>
<p style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center', margin: '0 0 12px' }}>{t('split.howItWorks')}</p>
{error && <p role="alert" style={{ color: 'var(--x-danger)', fontSize: 13, textAlign: 'center', margin: '0 0 10px' }}>{error}</p>}
<div style={{ display: 'flex', gap: 10 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose} disabled={busy}>{t('common.cancel')}</button>
<button className="btn btn--primary" style={{ flex: 1 }} disabled={busy || !amounts} data-testid="split-confirm"
onClick={() => onSplit(custom ? { mode: 'custom', parts: 2, first_amount: amounts[0] } : { mode: 'equal', parts })}>
{t('split.confirm', { count: amounts?.length ?? parts })}
</button>
</div>
</div>
</div>
)
}
/** The order's split bills above its lines: the parts, how much is paid, and Undo while nothing is. */
export function SplitBills({ bills, canUndo, onUndo }) {
const { t } = useTranslation('waiter')
if (!bills?.length) return null
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, margin: '8px 12px' }}>
{bills.map(b => (
<div key={b.id} data-testid="split-bill" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 12,
background: 'rgb(var(--x-info-rgb) / 0.1)', border: '1px solid rgb(var(--x-info-rgb) / 0.3)' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 700, fontSize: 14 }}>{t('split.bill', { count: b.parts, total: money(b.total) })}</div>
<div style={{ fontSize: 12, color: 'var(--x-ink-2)' }}>
{t('split.billPaid', { paid: money(b.paid), due: money(Math.max(0, b.total - b.paid)) })}
</div>
</div>
{canUndo && b.can_undo && (
<button type="button" className="btn btn--secondary" style={{ padding: '6px 12px', fontSize: 13 }} onClick={() => onUndo(b)} data-testid="split-undo">
{t('split.undo')}
</button>
)}
</div>
))}
</div>
)
}
+14
View File
@@ -0,0 +1,14 @@
// The venue's payments.split_amount / split_max_parts (6F.6, logic/split.js), from the shared settings request.
import { useEffect, useState } from 'react'
import { getVenueSettings } from '../api/venueSettings'
import { splitChoices, splitLevel, splitMax } from '../logic/split'
export function useSplitChoices() {
const [choices, setChoices] = useState(() => splitChoices('off', 10))
useEffect(() => {
let alive = true
getVenueSettings().then(r => { if (alive) setChoices(splitChoices(splitLevel(r.data), splitMax(r.data))) }).catch(() => {})
return () => { alive = false }
}, [])
return choices
}
+2
View File
@@ -0,0 +1,2 @@
// Split the bill by amount (plan 6F.6): the shared rules, @xenia/ordering/split.
export * from '@xenia/ordering/split'
+52 -2
View File
@@ -23,6 +23,9 @@ import MoveHistory, { MovedOrderBanner } from '../components/MoveHistory'
import QuantityModal from '../components/QuantityModal'
import { useQuantityMode } from '../hooks/useQuantityMode'
import { canChangeQuantity } from '../logic/lines'
import SplitAmountModal, { SplitBills } from '../components/SplitAmountModal'
import { useSplitChoices } from '../hooks/useSplitChoices'
import { isPart, isSettled } from '../logic/split'
import { usePriceRules } from '../hooks/usePriceRules'
import { fade } from '../logic/colour'
import SeatsHint from '../components/SeatsHint'
@@ -42,6 +45,7 @@ function combineIds(items) {
// Returns a stable string key for grouping under MERGE_IDENTICAL
function identicalKey(item) {
if (isPart(item)) return `part|${item.id}` // 6F.6: each part is paid on its own
const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4)
const opts = (() => { try { return item.selected_options ?? '[]' } catch { return '[]' } })()
const removed = (() => { try { return item.removed_ingredients ?? '[]' } catch { return '[]' } })()
@@ -51,6 +55,7 @@ function identicalKey(item) {
// Returns a grouping key for MERGE_SAME_ITEM (ignores options/removed/notes, only product + price)
function sameItemKey(item) {
if (isPart(item)) return `part|${item.id}`
const effPrice = ((item.unit_price ?? 0) + (item.price_adjustment ?? 0)).toFixed(4)
return `${item.product_id}|${effPrice}`
}
@@ -964,7 +969,7 @@ function CancelConfirmModal({ itemCount, onConfirm, onClose }) {
)
}
function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, onConfirm, onClose }) {
function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, onConfirm, onSplit, onClose }) {
const { t } = useTranslation('waiter')
const { paymentSafety } = usePaymentSettingsStore()
const [method, setMethod] = useState('cash')
@@ -1033,6 +1038,14 @@ function PayConfirmModal({ payAll, payIds, activeItems, andClose, cardEnabled, o
</div>
)}
{/* 6F.6: split the amount instead of paying it all now */}
{onSplit && (
<button type="button" className="btn btn--secondary" data-testid="pay-split"
style={{ width: '100%', marginBottom: 12 }} onClick={() => onSplit(payTotal)}>
➗ {t('split.button')}
</button>
)}
<div style={{ display: 'flex', gap: 12 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>
{t('common.cancel')}
@@ -1209,6 +1222,12 @@ export default function TableDetailPage() {
const [qtyItem, setQtyItem] = useState(null)
const [qtyError, setQtyError] = useState('')
const [qtyBusy, setQtyBusy] = useState(false)
// 6F.6: split the bill by amount
const splitChoices = useSplitChoices()
const splitAccess = useAllowed('ordering.payments.split_amount')
const [splitTarget, setSplitTarget] = useState(null) // { ids, total }
const [splitBusy, setSplitBusy] = useState(false)
const [splitError, setSplitError] = useState('')
const [cancelConfirm, setCancelConfirm] = useState(null) // null | { mode: 'items', ids: [...] } | { mode: 'order' }
const [paidSelectedIds, setPaidSelectedIds] = useState([])
@@ -1415,7 +1434,7 @@ export default function TableDetailPage() {
}
const activeItems = order?.items?.filter(i => i.status === 'active') || []
const paidItems = order?.items?.filter(i => i.status === 'paid') || []
const paidItems = order?.items?.filter(i => i.status === 'paid' || isSettled(i)) || [] // 6F.6: settled by a split bill
const allPaid = order && activeItems.length === 0
const canInteract = !!order
@@ -1955,6 +1974,13 @@ export default function TableDetailPage() {
{activeTab === 'active' && (
<>
<MovedOrderBanner moves={moves.order} onOpen={() => setMoveSheet({ title: t('moves.orderTitle'), moves: moves.order })} />
<SplitBills bills={order.split_bills} canUndo={splitAccess !== 'no' && !isOffline} onUndo={async bill => {
try {
await client.post(`/api/orders/${order.id}/split-bills/${bill.id}/undo`)
setSelectedIds([])
await load()
} catch (err) { setError(apiError(err, t('split.err.undo'))) }
}} />
<OrderSummary
order={{ ...order, items: displayActiveItems }}
selectable={canInteract && !paying}
@@ -2423,10 +2449,34 @@ export default function TableDetailPage() {
activeItems={displayActiveItems}
cardEnabled={cardEnabled}
onConfirm={(method) => paySelected(method, false)}
onSplit={splitChoices.on && splitAccess !== 'no' && !isOffline
&& !expandIds(selectedIds.length === 0 ? displayActiveItems.map(i => i.id) : selectedIds).some(id => isPart(activeItems.find(i => i.id === id)))
? total => {
setConfirmPay(false)
setSplitError('')
setSplitTarget({ ids: expandIds(selectedIds.length === 0 ? displayActiveItems.map(i => i.id) : selectedIds), total })
} : undefined}
onClose={() => setConfirmPay(false)}
/>
)}
{/* 6F.6: split the amount into parts */}
{splitTarget && (
<SplitAmountModal total={splitTarget.total} count={splitTarget.ids.length} choices={splitChoices}
customerCount={customerCount} busy={splitBusy} error={splitError}
onClose={() => setSplitTarget(null)}
onSplit={async body => {
setSplitBusy(true); setSplitError('')
try {
await client.post(`/api/orders/${order.id}/split-bills`, { item_ids: splitTarget.ids, ...body })
setSplitTarget(null)
setSelectedIds([])
setVirtualItems(null)
await load()
} catch (err) { setSplitError(apiError(err, t('split.err.split'))) } finally { setSplitBusy(false) }
}} />
)}
{/* Pay-and-close confirmation */}
{confirmPayAndClose && (
<PayConfirmModal