Files
xenia-pos-local/manager_dashboard/src/pages/orders/OrderPage.jsx
T
bonaminandClaude Opus 5.5 3eeafb565a 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>
2026-11-23 10:57:54 +02:00

207 lines
13 KiB
React

// A table's order in the manager (plan step 6.9; replaces the v1 order page and its desktop
// ordering tab). Taken, changed, paid and closed by the phones' rules: lines go by id and the
// server prices them (4.4); paying asks cash or card; "Close" with unpaid lines either takes
// the payment first or, when the venue allows it (orders.close_with_unpaid), writes them off
// after saying so. `/orders/new?table=5` is a table without an order: the first "Send" opens it.
import { useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowLeft, Ban, CheckCheck, CreditCard, Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Page, Select, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { useDuration } from '../overview/hooks'
import { tableName } from '../overview/overviewLogic'
import { Money, Pill } from '../overview/parts'
import AddItems from './AddItems'
import OrderLines from './OrderLines'
import OrderPeople from './OrderPeople'
import PayDialog from './PayDialog'
import PrintProblemsCard from './PrintProblemsCard'
import { AuditList, MoveList, PriceEventList } from './OrderHistory'
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' }
const TABS = ['order', 'prices', 'moves', 'history']
export default function OrderPage() {
const { orderId } = useParams()
const [params] = useSearchParams()
if (orderId === 'new') return <NewOrder tableId={Number(params.get('table')) || null} />
return <OrderView orderId={Number(orderId)} />
}
function useVenue() {
const { data } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
return venueRules(data)
}
function Back() {
const { t } = useTranslation('manager')
const navigate = useNavigate()
return <Button size="sm" variant="ghost" icon={<ArrowLeft size={16} />} onClick={() => navigate('/tables')}>{t('orders.toTables')}</Button>
}
function NewOrder({ tableId }) {
const { t } = useTranslation('manager')
const navigate = useNavigate()
const qc = useQueryClient()
const { data: tables = [] } = useLiveQuery({ queryKey: ['tables'], queryFn: () => client.get('/api/tables/').then(r => r.data), events: ['table_list_changed'] })
const table = tables.find(x => x.id === tableId)
const open = async () => (await client.post('/api/orders/', { table_id: tableId, order_type: 'here' })).data.id
return (
<Page testId="order-new">
<header className="flex flex-wrap items-center gap-3">
<Back />
<h1 className="text-title font-semibold text-ink">{t('orders.newTitle', { table: table ? tableName(table) : tableId ?? '' })}</h1>
<Pill tone="neutral">{t('overview.tableState.free')}</Pill>
</header>
<p className="text-label text-ink-2">{t('orders.newHint')}</p>
<AddItems orderId={null} openOrder={open} onSent={id => {
qc.invalidateQueries({ queryKey: ['orders-active'] })
navigate(`/orders/${id}`, { replace: true })
}} />
</Page>
)
}
function OrderView({ orderId }) {
const { t } = useTranslation('manager')
const { formatTime, formatMoney } = useFormat()
const since = useDuration()
const navigate = useNavigate()
const qc = useQueryClient()
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('')
const { data: order, isPending, error } = useLiveQuery({
queryKey: ['order', orderId], queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data), events: ORDER_EVENTS,
})
const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
const { data: printers = [] } = useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 60_000 })
const { data: priceEvents = [] } = useLiveQuery({
queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), events: ['order_updated'],
})
const { data: moves = { order: [], items: {} } } = useLiveQuery({ // 6F.4
queryKey: ['order-moves', orderId], queryFn: () => client.get(`/api/orders/${orderId}/moves`).then(r => r.data), events: ['order_updated'],
})
const refresh = () => {
qc.invalidateQueries({ queryKey: ['order', orderId] })
qc.invalidateQueries({ queryKey: ['price-events', orderId] })
qc.invalidateQueries({ queryKey: ['order-moves', orderId] })
qc.invalidateQueries({ queryKey: ['orders-active'] })
}
const onError = err => toast.error(errorMessage(err, t))
const close = useMutation({ mutationFn: () => client.post(`/api/orders/${orderId}/close`), onSuccess: () => { setConfirm(null); toast.success(t('orders.closed')); refresh() }, onError })
const cancel = useMutation({
mutationFn: print => client.delete(`/api/orders/${orderId}`, { params: { print_cancellation: print } }),
onSuccess: () => { setConfirm(null); toast.success(t('orders.cancelled')); refresh(); navigate('/tables') }, onError,
})
const print = useMutation({ mutationFn: pid => client.post(`/api/orders/${orderId}/print`, { printer_id: pid }), onSuccess: () => toast.success(t('orders.printing')), onError })
if (isPending) return <div className="h-full grid place-items-center"><Spinner /></div>
if (error || !order) {
return <div className="p-6 grid gap-3 justify-items-center"><EmptyState title={t('orders.notFound')} description={error ? errorMessage(error, t) : undefined} /><Back /></div>
}
const editable = ['open', 'partially_paid', 'paid'].includes(order.status)
const sums = totals(order)
const due = unpaidIds(order)
function startClose() {
const step = closeStep(order, venue.closeWithUnpaid)
if (step === 'payFirst') setPaying({ ids: due, amount: sums.due, thenClose: true })
else setConfirm(step)
}
return (
<Page testId="order-page" data-status={order.status}>
<header className="flex flex-wrap items-center gap-3">
<Back />
<h1 className="text-title font-semibold text-ink">{order.table_name ? t('orders.title', { table: order.table_name }) : t('orders.titleNoTable', { id: order.id })}</h1>
<Pill tone={STATUS_TONE[order.status] ?? 'neutral'} data-testid="order-status">{t(`overview.orderStatus.${order.status}`, { defaultValue: order.status })}</Pill>
<span className="text-label text-ink-2">{t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at, order.closed_at ? new Date(order.closed_at).getTime() : undefined) })}</span>
<span className="flex-1" />
<span className="flex items-baseline gap-4 text-label text-ink-2">
{sums.paid > 0 && <span>{t('orders.paid')} <Money value={sums.paid} className="font-semibold text-success-ink" /></span>}
{sums.paid > 0 && sums.due > 0 && <span>{t('orders.due')} <Money value={sums.due} className="font-semibold text-ink" data-testid="order-due" /></span>}
<span>{t('orders.total')} <Money value={sums.total} className="text-title font-semibold text-ink" data-testid="order-total" /></span>
</span>
</header>
<div className="flex flex-wrap items-center gap-2">
<span className="flex gap-1" role="tablist">
{TABS.map(k => <Button key={k} size="sm" variant={tab === k ? 'primary' : 'ghost'} role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`order-tab-${k}`}>{t(`orders.tabs.${k}`)}</Button>)}
</span>
<span className="flex-1" />
{editable && due.length > 0 && <Button icon={<CreditCard size={16} />} onClick={() => setPaying({ ids: due, amount: sums.due })} data-testid="order-pay-all">{t('orders.payAll')}</Button>}
{editable && <Button variant="secondary" icon={<CheckCheck size={16} />} onClick={startClose} data-testid="order-close">{t('orders.close')}</Button>}
{editable && <Button variant="danger" icon={<Ban size={16} />} onClick={() => setConfirm('cancel')} data-testid="order-cancel">{t('orders.cancel')}</Button>}
{printers.length > 0 && (
<span className="flex items-center gap-2">
<Select size="sm" value={printerId} onChange={e => setPrinterId(e.target.value)} aria-label={t('orders.printer')}
placeholder={t('orders.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
<Button size="sm" variant="secondary" icon={<Printer size={16} />} disabled={!printerId} loading={print.isPending} onClick={() => print.mutate(Number(printerId))}>{t('orders.print')}</Button>
</span>
)}
</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)]')}>
<div className="grid gap-4 min-w-0">
<OrderLines order={order} open={editable} priceEvents={priceEvents} moves={moves.items} onChanged={refresh}
onPay={(ids, amount, after) => setPaying({ ids, amount, after })} />
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
</div>
{editable && <AddItems orderId={order.id} onSent={refresh} />}
</div>
)}
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
{tab === 'moves' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><MoveList moves={moves} order={order} /></section>}
{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() }} />}
{(confirm === 'close' || confirm === 'writeOff') && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t(confirm === 'close' ? 'orders.confirmClose' : 'orders.writeOffTitle')}
description={confirm === 'writeOff' ? t('orders.writeOffBody', { count: due.length, amount: formatMoney(sums.due) }) : undefined}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
{confirm === 'writeOff' && <Button variant="secondary" onClick={() => { setConfirm(null); setPaying({ ids: due, amount: sums.due, thenClose: true }) }}>{t('orders.payAndClose')}</Button>}
<Button variant={confirm === 'writeOff' ? 'danger' : 'primary'} loading={close.isPending} onClick={() => close.mutate()} data-testid="order-close-confirm">
{confirm === 'writeOff' ? t('orders.writeOff') : t('orders.close')}
</Button>
</>} />
)}
{confirm === 'cancel' && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t('orders.cancelTitle')} description={t('orders.cancelBody')}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
<Button variant="secondary" loading={cancel.isPending && cancel.variables === false} onClick={() => cancel.mutate(false)} data-testid="order-cancel-confirm">{t('orders.lines.cancelNoPrint')}</Button>
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
</>} />
)}
</Page>
)
}