Owner 2026-11-23 (plan 6F.3). services/price_changes.py: the venue's switch orders.price_change (off | before_sending | anytime, default anytime as before), orders.price_change_reason and its quick reasons; keys ordering.prices.modify (the cart), new modify_sent (a sent or served line) and view_changes (who sees them). Every by-hand price (waiter cart, a sent line, the counter's % discount) writes a manual_price PriceEventLog row (before, after, quantity, who, approving manager, stage, reason) plus a PRICE_CHANGED audit row; before, the sent-line change overwrote the price with no record. Alembic 0047: event columns; modify_sent for everyone holding modify (and the venues' role overrides), view_changes for owners and store managers. Waiter: the reason picker when the venue asks, a sent line's price on modify_sent and the venue's switch, the line's price history. Manager: Settings -> Operation 'Prices changed by hand', the changes on the order's lines and history, Reports -> Cancellations, discounts and price changes (+ export). Counter: no discount when the venue turned price changes off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
193 lines
12 KiB
React
193 lines
12 KiB
React
// A table's order at a glance, opened from the overview's table chips and the waiting prints
|
||
// (plan step 6.2): its lines with price changes, pay a line or everything, close or cancel it
|
||
// (a cancel asks whether to print a cancellation ticket), print it on a chosen printer, or open
|
||
// the full order page.
|
||
import { useState } from 'react'
|
||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||
import toast from 'react-hot-toast'
|
||
import { ArrowRight, Printer, X } from 'lucide-react'
|
||
import { errorMessage } from '@xenia/api'
|
||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||
import { Button, Dialog, Dropdown, EmptyState, IconButton, Spinner, cx } from '@xenia/ui'
|
||
import client from '../../api/client'
|
||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||
import { lineTotal, orderTotal } from './overviewLogic'
|
||
import { Money, Pill } from './parts'
|
||
import { useDuration } from './hooks'
|
||
import PayDialog from '../orders/PayDialog'
|
||
import { closeStep, selectedAmount, unpaidIds, venueRules } from '../orders/orderLogic'
|
||
|
||
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
|
||
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
|
||
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink' }
|
||
|
||
export default function OrderDialog({ orderId, tableName, onClose, onOpenFull }) {
|
||
const { t } = useTranslation('manager')
|
||
const { formatTime, formatMoney } = useFormat()
|
||
const since = useDuration()
|
||
const qc = useQueryClient()
|
||
const [confirm, setConfirm] = useState(null) // { kind: 'cancelItem', itemId } | { kind: 'cancelOrder' } | { kind: 'close' }
|
||
const [printCancel, setPrintCancel] = useState(null) // the same, after "yes": ask about the ticket
|
||
const [printerId, setPrinterId] = useState('')
|
||
const [paying, setPaying] = useState(null) // { ids, thenClose } (6.9: cash or card, the venue's close rule)
|
||
const { data: settings } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
|
||
const venue = venueRules(settings)
|
||
|
||
const { data: order, isPending } = 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 eventsOf = id => priceEvents.filter(ev => ev.order_item_id === id)
|
||
const nameOf = id => { const w = staff.find(x => x.id === id); return w ? (w.nickname || w.full_name || w.username) : `#${id}` }
|
||
|
||
const refresh = () => {
|
||
qc.invalidateQueries({ queryKey: ['order', orderId] })
|
||
qc.invalidateQueries({ queryKey: ['orders-active'] })
|
||
}
|
||
const run = (fn, done, after) => ({
|
||
mutationFn: fn,
|
||
onSuccess: () => { toast.success(done); refresh(); after?.() },
|
||
onError: err => toast.error(errorMessage(err, t)),
|
||
})
|
||
const pay = ids => setPaying({ ids })
|
||
const startClose = () => {
|
||
const step = closeStep(order, venue.closeWithUnpaid)
|
||
if (step === 'payFirst') setPaying({ ids: unpaidIds(order), thenClose: true })
|
||
else setConfirm({ kind: step === 'writeOff' ? 'writeOff' : 'close' })
|
||
}
|
||
const cancelItem = useMutation(run(({ itemId, print }) => client.delete(`/api/orders/${orderId}/items/${itemId}`, { params: { print_cancellation: print } }), t('overview.order.lineCancelled')))
|
||
const cancelOrder = useMutation(run(({ print }) => client.delete(`/api/orders/${orderId}`, { params: { print_cancellation: print } }), t('overview.order.cancelled'), onClose))
|
||
const close = useMutation(run(() => client.post(`/api/orders/${orderId}/close`), t('overview.order.closed'), onClose))
|
||
const print = useMutation(run(pid => client.post(`/api/orders/${orderId}/print`, { printer_id: pid }), t('overview.order.printing')))
|
||
|
||
const isOpen = order ? ['open', 'partially_paid'].includes(order.status) : false
|
||
const active = order ? order.items.filter(i => i.status === 'active') : []
|
||
|
||
const confirmed = () => {
|
||
const c = confirm
|
||
setConfirm(null)
|
||
if (c.kind === 'close' || c.kind === 'writeOff') close.mutate()
|
||
else setPrintCancel(c)
|
||
}
|
||
const cancelWith = printIt => {
|
||
const c = printCancel
|
||
setPrintCancel(null)
|
||
if (c.kind === 'cancelItem') cancelItem.mutate({ itemId: c.itemId, print: printIt })
|
||
else cancelOrder.mutate({ print: printIt })
|
||
}
|
||
|
||
return (
|
||
<Dialog open size="lg" onClose={onClose}
|
||
title={<span className="flex flex-wrap items-center gap-2">
|
||
{t('overview.order.title', { table: tableName })}
|
||
{order && <Pill tone={STATUS_TONE[order.status] ?? 'neutral'}>{t(`overview.orderStatus.${order.status}`, { defaultValue: order.status })}</Pill>}
|
||
{order && <Money value={orderTotal(order.items)} className="ml-auto text-title font-semibold text-ink" data-testid="order-total" />}
|
||
</span>}
|
||
description={order ? t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at) }) : undefined}
|
||
footer={order && <div className="flex flex-wrap items-center gap-2 w-full">
|
||
{isOpen && active.length > 0 && <Button onClick={() => pay(active.map(i => i.id))} data-testid="order-pay-all">{t('overview.order.payAll')}</Button>}
|
||
{isOpen && <Button variant="secondary" onClick={startClose} data-testid="order-close">{t('overview.order.close')}</Button>}
|
||
{isOpen && <Button variant="danger" onClick={() => setConfirm({ kind: 'cancelOrder' })}>{t('overview.order.cancel')}</Button>}
|
||
<span className="flex-1" />
|
||
{printers.length > 0 && (
|
||
<span className="flex items-center gap-2">
|
||
<Dropdown size="sm" value={printerId} onChange={setPrinterId} aria-label={t('overview.order.printer')}
|
||
placeholder={t('overview.order.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('overview.order.print')}</Button>
|
||
</span>
|
||
)}
|
||
<Button size="sm" variant="ghost" iconEnd={<ArrowRight size={16} />} onClick={onOpenFull}>{t('overview.order.full')}</Button>
|
||
</div>}>
|
||
{isPending && <div className="py-10 flex justify-center"><Spinner /></div>}
|
||
{order && (
|
||
<div className="grid gap-3 -mx-2" data-testid="order-dialog">
|
||
{order.waiters.length > 0 && (
|
||
<div className="flex flex-wrap items-center gap-2 px-2">
|
||
<span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('overview.order.staff')}</span>
|
||
{order.waiters.map(w => <Pill key={w.waiter_id} tone="accent">{nameOf(w.waiter_id)}</Pill>)}
|
||
</div>
|
||
)}
|
||
{order.items.length === 0 ? <EmptyState compact title={t('overview.order.empty')} /> : (
|
||
<ul className="divide-y divide-line">
|
||
{order.items.map(item => {
|
||
const evs = eventsOf(item.id).filter(ev => EVENT_TONE[ev.event_type])
|
||
const cancelled = item.status === 'cancelled'
|
||
return (
|
||
<li key={item.id} className={cx('px-2 py-2', cancelled && 'opacity-50')} data-testid="order-line">
|
||
<div className="flex items-center gap-3">
|
||
<div className={cx('flex-1 min-w-0', cancelled && 'line-through')}>
|
||
<div className="flex flex-wrap items-center gap-1.5 text-body font-semibold text-ink">
|
||
{item.product?.name ?? `#${item.product_id}`}
|
||
<span className="font-normal text-ink-3">×{item.quantity}</span>
|
||
{item.deal_id && <Pill tone="accent">{t('overview.order.free')}</Pill>}
|
||
</div>
|
||
{item.notes && <div className="text-caption text-ink-3">{item.notes}</div>}
|
||
{item.paid_by && <div className="text-caption font-semibold text-success-ink">{t('overview.order.linePaid')}</div>}
|
||
</div>
|
||
<Money value={lineTotal(item)} className={cx('text-body font-semibold min-w-16 text-right', item.price_adjustment ? 'text-info-ink' : 'text-ink')} />
|
||
{isOpen && item.status === 'active' && (<>
|
||
<Button size="sm" variant="secondary" onClick={() => pay([item.id])}>{t('overview.order.pay')}</Button>
|
||
<IconButton size="sm" variant="ghost" label={t('overview.order.cancelLine')} onClick={() => setConfirm({ kind: 'cancelItem', itemId: item.id })}><X size={16} /></IconButton>
|
||
</>)}
|
||
</div>
|
||
{evs.map((ev, i) => (
|
||
<div key={i} className={cx('flex items-center gap-2 pl-4 text-caption', EVENT_TONE[ev.event_type])}>
|
||
<span aria-hidden="true">↳</span>
|
||
<span className="flex-1">{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}{ev.event_type === 'manual_price' && ev.waiter_note ? ` · ${ev.waiter_note}` : ''}</span>
|
||
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
|
||
{ev.price_after != null && <span className="text-ink-3">→ {formatMoney(ev.price_after)}</span>}
|
||
</div>
|
||
))}
|
||
</li>
|
||
)
|
||
})}
|
||
</ul>
|
||
)}
|
||
</div>
|
||
)}
|
||
|
||
{confirm && (
|
||
<Dialog open size="sm" onClose={() => setConfirm(null)} title={confirm.kind === 'writeOff' ? t('orders.writeOffTitle') : t(`overview.order.confirm.${confirm.kind}`)}
|
||
footer={<>
|
||
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('overview.back')}</Button>
|
||
<Button variant={confirm.kind === 'close' ? 'primary' : 'danger'} onClick={confirmed} data-testid="order-confirm">
|
||
{confirm.kind === 'close' ? t('overview.order.close') : confirm.kind === 'writeOff' ? t('orders.writeOff') : t('overview.order.cancel')}
|
||
</Button>
|
||
</>}>
|
||
{confirm.kind === 'cancelOrder' && <p>{t('overview.order.confirm.cancelOrderBody')}</p>}
|
||
{confirm.kind === 'writeOff' && <p>{t('orders.writeOffBody', { count: unpaidIds(order).length, amount: formatMoney(selectedAmount(order, unpaidIds(order))) })}</p>}
|
||
</Dialog>
|
||
)}
|
||
{paying && order && (
|
||
<PayDialog orderId={orderId} itemIds={paying.ids} amount={selectedAmount(order, paying.ids)} card={venue.card} thenClose={!!paying.thenClose}
|
||
onClose={() => setPaying(null)}
|
||
onDone={() => {
|
||
toast.success(paying.thenClose ? t('overview.order.closed') : t('overview.order.paidDone'))
|
||
const closed = paying.thenClose
|
||
setPaying(null)
|
||
refresh()
|
||
if (closed) onClose()
|
||
}} />
|
||
)}
|
||
{printCancel && (
|
||
<Dialog open size="sm" onClose={() => setPrintCancel(null)} title={t('overview.order.printCancel')}
|
||
footer={<>
|
||
<Button variant="secondary" onClick={() => cancelWith(false)} data-testid="cancel-no-print">{t('overview.order.printCancelNo')}</Button>
|
||
<Button variant="danger" icon={<Printer size={16} />} onClick={() => cancelWith(true)}>{t('overview.order.printCancelYes')}</Button>
|
||
</>}>
|
||
<p>{t('overview.order.printCancelBody')}</p>
|
||
</Dialog>
|
||
)}
|
||
</Dialog>
|
||
)
|
||
}
|