feat(backend,waiter,manager): prices changed by hand are on the record

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>
This commit is contained in:
2026-11-23 07:41:43 +02:00
co-authored by Claude Opus 5.5
parent e3f4f3eeee
commit f87f9ff23c
40 changed files with 1044 additions and 73 deletions
+23 -4
View File
@@ -4,6 +4,9 @@ import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
import { assetUrl } from '../config/server'
import { money } from '../i18n'
import { parseNumber, useTranslation } from '@xenia/i18n'
import PriceReason from './PriceReason'
import { priceReasonText } from '../logic/priceRules'
import { usePriceRules } from '../hooks/usePriceRules'
// ── Helpers ──────────────────────────────────────────────────────────────────
@@ -815,7 +818,7 @@ function QuantityTab({ unitCfg, qty, setQty }) {
const PRICE_DELTAS = [-5, -3, -2, -1, -0.5, -0.2, +0.2, +0.5, +1, +2, +3, +5]
function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) {
function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj, rules, reason, setReason, reasonMissing }) {
const { t } = useTranslation('waiter')
const [editing, setEditing] = useState(false)
const [rawInput, setRawInput] = useState('')
@@ -904,6 +907,8 @@ function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) {
</button>
))}
</div>
{/* 6F.3: the venue asks why a price changes */}
{rules?.reasonRequired && priceAdj !== 0 && <PriceReason rules={rules} state={reason} onChange={setReason} missing={reasonMissing} />}
</div>
)
}
@@ -1069,7 +1074,9 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
const itemFavorites = useWaiterFavoritesStore(s => s.itemFavorites)
// A price set before sending needs the key itself (plan 4.3); the manager-approval path for
// it comes with server-priced orders (4.4). After sending, the item's actions offer it.
const priceAdjAllowed = useCan('ordering.prices.modify')
// 6F.3: and the venue allows prices typed before sending (orders.price_change)
const priceRulesNow = usePriceRules()
const priceAdjAllowed = useCan('ordering.prices.modify') && priceRulesNow.inCart
const preferenceSets = product?.preference_sets || []
const quickOptions = product?.quick_options || []
@@ -1136,6 +1143,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
const [sharedSubs, setSharedSubs] = useState({})
const [note, setNote] = useState('')
const [priceAdj, setPriceAdj] = useState(0)
const [priceReason, setPriceReason] = useState({ choice: '', other: '' }) // 6F.3
const [addAttempted, setAddAttempted] = useState(false)
const [courseId, setCourseId] = useState(initialState?.courseId ?? null)
@@ -1153,6 +1161,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
setSharedSubs(initialState.sharedSubs ?? base.sharedSubs)
setNote(initialState.note ?? '')
setPriceAdj(initialState.priceAdj ?? 0)
setPriceReason(initialState.priceReason ?? { choice: '', other: '' })
setCourseId(initialState.courseId ?? null)
} else {
setQty(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1)
@@ -1164,6 +1173,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
setSharedSubs(base.sharedSubs)
setNote('')
setPriceAdj(0)
setPriceReason({ choice: '', other: '' })
setCourseId(null)
}
setExpandedExtra(null)
@@ -1265,6 +1275,12 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
const favTabAlert = favHasIncompletePref && (addAttempted || prefsHasMandatory)
function handleAdd() {
const reasonTxt = priceAdj !== 0 ? priceReasonText(priceRulesNow, t, priceReason) : ''
if (priceAdj !== 0 && priceRulesNow.reasonRequired && !reasonTxt) { // 6F.3: why the price changes
setAddAttempted(true)
setActiveTab('price_adjust')
return
}
if (!canAdd) {
setAddAttempted(true)
if (!allPrefsOk) {
@@ -1341,8 +1357,9 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
removed_ingredients: removedNames,
notes: note,
price_adjustment: priceAdj !== 0 ? priceAdj : undefined,
price_reason: reasonTxt || undefined,
course_id: courseId ?? undefined,
_drawerState: { qty, quickState, extrasState, removedState, prefs, subChoices, sharedSubs, note, priceAdj, courseId },
_drawerState: { qty, quickState, extrasState, removedState, prefs, subChoices, sharedSubs, note, priceAdj, priceReason, courseId },
})
onClose()
}
@@ -1507,7 +1524,9 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
{activeTab === 'quantity' && isDecimal && <QuantityTab unitCfg={unitCfg} qty={qty} setQty={setQty} />}
{activeTab === 'courses' && courses?.length > 0 && <CoursesTab courses={courses} courseId={courseId} setCourseId={setCourseId} />}
{activeTab === 'notes' && <NotesTab note={note} setNote={setNote} quickNotes={quickNotes ?? undefined} />}
{activeTab === 'price_adjust' && <PriceAdjustTab basePrice={product.base_price} priceAdj={priceAdj} setPriceAdj={setPriceAdj} />}
{activeTab === 'price_adjust' && <PriceAdjustTab basePrice={product.base_price} priceAdj={priceAdj} setPriceAdj={setPriceAdj}
rules={priceRulesNow} reason={priceReason} setReason={setPriceReason}
reasonMissing={addAttempted && priceRulesNow.reasonRequired && !priceReasonText(priceRulesNow, t, priceReason)} />}
{activeTab === 'summary' && <SummaryTab product={product} summaryLines={summaryLines} note={note} onJumpTab={setActiveTab} />}
</div>
@@ -0,0 +1,49 @@
// A line's price changes (plan 6F.3), for people with ordering.prices.view_changes: each change,
// from → to, where it happened (before sending / after sending / after serving), who, the
// manager who approved it, why. GET /api/orders/{id}/price-changes.
import { useEffect, useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import client from '../api/client'
import { apiError } from '../api/errors'
export default function PriceHistory({ orderId, item, onClose }) {
const { t } = useTranslation('waiter')
const { formatDateTime, formatMoney } = useFormat()
const [rows, setRows] = useState(null)
const [error, setError] = useState('')
useEffect(() => {
let alive = true
client.get(`/api/orders/${orderId}/price-changes`)
.then(r => { if (alive) setRows(r.data.filter(c => c.item_id === item.id)) })
.catch(err => { if (alive) setError(apiError(err, t('price.historyFailed'))) })
return () => { alive = false }
}, [orderId, item.id, t])
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="price-history">
<div className="modal-handle" />
<h2 className="modal-title">{t('price.history')}</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>{item.product_name || item.product?.name}</p>
{error && <p role="alert" style={{ color: 'var(--x-danger)', fontSize: 13, textAlign: 'center' }}>{error}</p>}
{!error && rows === null && <p style={{ textAlign: 'center', color: 'var(--muted)' }}>…</p>}
{rows?.length === 0 && <p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>{t('price.historyNone')}</p>}
<div style={{ display: 'grid', gap: 8 }}>
{rows?.map(c => (
<div key={c.id} data-testid="price-history-row" style={{ padding: '10px 12px', borderRadius: 12, background: 'var(--bg3)', border: '1px solid var(--border)', display: 'grid', gap: 2 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, fontWeight: 700 }}>
<span>{formatMoney(c.before)} → {formatMoney(c.after)}</span>
<span style={{ color: c.delta < 0 ? 'var(--x-danger)' : 'var(--x-success)' }}>{formatMoney(c.delta, { signDisplay: 'exceptZero' })}</span>
</div>
<div style={{ fontSize: 12, color: 'var(--muted)' }}>
{formatDateTime(c.at, 'datetimeShort')} · {t(`price.stage.${c.stage || 'cart'}`)}{c.by ? ` · ${c.by}` : ''}
{c.approved_by ? ` · ${t('price.approvedBy', { name: c.approved_by })}` : ''}
</div>
{c.reason && <div style={{ fontSize: 13 }}>{c.reason}</div>}
</div>
))}
</div>
<button className="btn btn--secondary" style={{ width: '100%', marginTop: 16 }} onClick={onClose}>{t('common.close')}</button>
</div>
</div>
)
}
+20
View File
@@ -0,0 +1,20 @@
// Why a price changes (plan 6F.3): the venue's quick reasons (or the built-in ones) or a typed one.
// Shown when the venue asks for a reason; the parent keeps { choice, other } and sends
// priceReasonText(rules, t, state) (logic/priceRules.js).
import { useTranslation } from '@xenia/i18n'
import { ReasonPicker } from '@xenia/ui'
import { priceReasonOptions } from '../logic/priceRules'
export default function PriceReason({ rules, state, onChange, missing = false }) {
const { t } = useTranslation('waiter')
return (
<div style={{ display: 'grid', gap: 8 }} data-testid="price-reason">
<div style={{ fontSize: 13, fontWeight: 700, color: missing ? 'var(--x-danger)' : 'var(--muted)' }}>
{missing ? t('price.reasonMissing') : t('price.reason')}
</div>
<ReasonPicker options={priceReasonOptions(rules, t)} value={state.choice} onChange={choice => onChange({ ...state, choice })}
other={state.other} onOther={other => onChange({ ...state, other })} otherLabel={t('price.reasons.other')}
ariaLabel={t('price.reason')} testIdPrefix="price-reason" />
</div>
)
}
+14
View File
@@ -0,0 +1,14 @@
// The venue's price-change rules (6F.3, logic/priceRules.js), from the shared settings request.
import { useEffect, useState } from 'react'
import { getVenueSettings } from '../api/venueSettings'
import { priceRules } from '../logic/priceRules'
export function usePriceRules() {
const [rules, setRules] = useState(() => priceRules(null))
useEffect(() => {
let alive = true
getVenueSettings().then(r => { if (alive) setRules(priceRules(r.data)) }).catch(() => {})
return () => { alive = false }
}, [])
return rules
}
+37
View File
@@ -0,0 +1,37 @@
// The venue's rules for prices changed by hand (plan 6F.3), from its settings:
// orders.price_change off | before_sending | anytime (default anytime)
// orders.price_change_reason 'true' → a typed price needs a reason
// orders.price_change_reasons JSON list of quick reasons ([] → the built-in ones)
// Plain JS so Node tests can import it.
export const BUILT_IN_REASONS = ['regular', 'mistake', 'compensation', 'manager', 'happyHour']
export function priceRules(settings) {
const v = k => settings?.[k]?.value
const mode = ['off', 'before_sending', 'anytime'].includes(v('orders.price_change')) ? v('orders.price_change') : 'anytime'
let reasons = []
try {
const list = JSON.parse(v('orders.price_change_reasons') || '[]')
if (Array.isArray(list)) reasons = list.filter(x => typeof x === 'string' && x.trim()).map(x => x.trim())
} catch { /* a broken list: the built-in ones */ }
return {
mode,
inCart: mode !== 'off', // a price typed before sending
afterSending: mode === 'anytime', // a sent or served line
reasonRequired: v('orders.price_change_reason') === 'true',
reasons,
}
}
/** The choices of the reason picker: the venue's own quick reasons, else the built-in ones. */
export function priceReasonOptions(rules, t) {
return rules.reasons.length
? rules.reasons.map((r, i) => ({ value: `v${i}`, label: r }))
: BUILT_IN_REASONS.map(k => ({ value: k, label: t(`price.reasons.${k}`) }))
}
/** The reason to send for { choice, other } ('' = none): a quick reason's text or what was typed. */
export function priceReasonText(rules, t, state) {
if (!state?.choice) return ''
if (state.choice === 'other') return (state.other || '').trim()
return priceReasonOptions(rules, t).find(o => o.value === state.choice)?.label ?? ''
}
+54 -10
View File
@@ -16,6 +16,10 @@ import { TransferIcon, MergeIcon, FlagsIcon, WaiterIcon, PrintIcon } from '../co
import usePaymentSettingsStore from '../store/paymentSettingsStore'
import useTableViewStore from '../store/tableViewStore'
import { parseNumber, useTranslation } from '@xenia/i18n'
import PriceReason from '../components/PriceReason'
import { priceReasonText } from '../logic/priceRules'
import PriceHistory from '../components/PriceHistory'
import { usePriceRules } from '../hooks/usePriceRules'
import { fade } from '../logic/colour'
import SeatsHint from '../components/SeatsHint'
@@ -119,8 +123,10 @@ function SplitModal({ item, onConfirm, onClose }) {
// ─── Price adjust modal ───────────────────────────────────────────────────────
function PriceAdjustModal({ item, onConfirm, onClose }) {
function PriceAdjustModal({ item, rules, error, onConfirm, onClose }) {
const { t } = useTranslation('waiter')
const [reason, setReason] = useState({ choice: '', other: '' }) // 6F.3
const [tried, setTried] = useState(false)
const basePrice = item.unit_price ?? 0
const [adj, setAdj] = useState(item.price_adjustment ?? 0)
const [editing, setEditing] = useState(false)
@@ -225,6 +231,13 @@ function PriceAdjustModal({ item, onConfirm, onClose }) {
))}
</div>
{rules.reasonRequired && adj !== (item.price_adjustment ?? 0) && (
<div style={{ marginBottom: 14 }}>
<PriceReason rules={rules} state={reason} onChange={setReason} missing={tried && !priceReasonText(rules, t, reason)} />
</div>
)}
{error && <p role="alert" style={{ color: 'var(--x-danger)', fontSize: 13, textAlign: 'center', margin: '0 0 10px' }}>{error}</p>}
{/* Reset */}
{adj !== 0 && (
<button
@@ -241,7 +254,7 @@ function PriceAdjustModal({ item, onConfirm, onClose }) {
<div style={{ display: 'flex', gap: 10 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>{t('common.cancel')}</button>
<button className="btn btn--primary" style={{ flex: 1 }} onClick={() => onConfirm(adj)}>
<button className="btn btn--primary" style={{ flex: 1 }} onClick={() => (() => { const r = priceReasonText(rules, t, reason); if (adj !== (item.price_adjustment ?? 0) && rules.reasonRequired && !r) { setTried(true); return } onConfirm(adj, r) })()}>
{t('common.apply')}
</button>
</div>
@@ -252,7 +265,7 @@ function PriceAdjustModal({ item, onConfirm, onClose }) {
// ─── Item action modal (long-press) ──────────────────────────────────────────
function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, onClose }) {
function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCancel, onCombine, canCancel, cancelNeedsApproval, priceAdjAllowed, priceNeedsApproval, canMove, onAdjustPrice, canSeePriceHistory, onPriceHistory, onClose }) {
const { t } = useTranslation('waiter')
const { items, singleStacked, multiSelect } = target
const label = multiSelect
@@ -260,6 +273,22 @@ function ItemActionModal({ target, onOrderAgain, onSplit, onMoveToTable, onCance
: items[0]?.product?.name || `#${items[0]?.product_id}`
const actionRows = [
// 6F.3: who changed this line's price, when, from what, why (ordering.prices.view_changes)
...(!multiSelect && canSeePriceHistory && items[0]?.price_adjustment ? [{
key: 'price_history',
color: 'var(--x-warning)',
iconBg: 'rgb(var(--x-warning-rgb) / 0.15)',
label: t('price.history'),
sub: t('price.historySub'),
icon: (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="9" stroke="var(--x-warning)" strokeWidth="2" />
<path d="M12 7v5l3 2" stroke="var(--x-warning)" strokeWidth="2" strokeLinecap="round" />
</svg>
),
onClick: onPriceHistory,
enabled: true,
}] : []),
...(!multiSelect && priceAdjAllowed ? [{
key: 'adjust_price',
color: 'var(--x-warning)',
@@ -1097,10 +1126,15 @@ export default function TableDetailPage() {
// manager's PIN on the phone, the approval dialog opens by itself) or 'no'
const cancelAccess = useAllowed('ordering.orders.cancel')
const revertAccess = useAllowed('ordering.payments.revert')
const priceAccess = useAllowed('ordering.prices.modify')
// a sent line's price (6F.3): its own key, and the venue allows changes after sending
const priceAccess = useAllowed('ordering.prices.modify_sent')
const priceRulesNow = usePriceRules()
const seesPriceChanges = useCan('ordering.prices.view_changes')
const [priceError, setPriceError] = useState('')
const [historyItem, setHistoryItem] = useState(null)
const canCancel = cancelAccess !== 'no'
const revertAllowed = revertAccess !== 'no'
const priceAdjAllowed = priceAccess !== 'no'
const priceAdjAllowed = priceAccess !== 'no' && priceRulesNow.afterSending
const canDiscount = useCan('pricing.discounts.apply')
const canPay = useCan('ordering.orders.close')
const canMove = useCan('ordering.orders.open')
@@ -2201,6 +2235,12 @@ export default function TableDetailPage() {
setItemActionTarget(null)
setPriceAdjustItem(item)
}}
canSeePriceHistory={seesPriceChanges && !isOffline}
onPriceHistory={() => {
const item = itemActionTarget.items[0]
setItemActionTarget(null)
setHistoryItem(item)
}}
onCancel={() => {
const ids = itemActionTarget.items.map(i => i.id)
setItemActionTarget(null)
@@ -2226,22 +2266,26 @@ export default function TableDetailPage() {
{priceAdjustItem && (
<PriceAdjustModal
item={priceAdjustItem}
onConfirm={async (adj) => {
rules={priceRulesNow}
error={priceError}
onConfirm={async (adj, reason) => {
try {
setPriceError('')
await client.patch(`/api/orders/${order.id}/items/${priceAdjustItem.id}/price-adjust`, {
price_adjustment: adj,
price_adjustment: adj, reason: reason || undefined,
})
setPriceAdjustItem(null)
await load()
} catch (err) {
console.error('[price-adjust] failed:', err)
setPriceAdjustItem(null)
setPriceError(apiError(err, t('detail.err.price'))) // stays open: the reason or a manager's PIN
}
}}
onClose={() => setPriceAdjustItem(null)}
onClose={() => { setPriceAdjustItem(null); setPriceError('') }}
/>
)}
{historyItem && <PriceHistory orderId={order.id} item={historyItem} onClose={() => setHistoryItem(null)} />}
{/* Cancel confirmation */}
{cancelConfirm && (
<CancelConfirmModal
+27
View File
@@ -0,0 +1,27 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { priceRules } from '../src/logic/priceRules.js'
const set = o => Object.fromEntries(Object.entries(o).map(([k, value]) => [k, { value }]))
test('the venue rules for prices changed by hand (6F.3)', () => {
assert.deepEqual(priceRules(null), { mode: 'anytime', inCart: true, afterSending: true, reasonRequired: false, reasons: [] })
const off = priceRules(set({ 'orders.price_change': 'off' }))
assert.equal(off.inCart, false); assert.equal(off.afterSending, false)
const cart = priceRules(set({ 'orders.price_change': 'before_sending', 'orders.price_change_reason': 'true' }))
assert.equal(cart.inCart, true); assert.equal(cart.afterSending, false); assert.equal(cart.reasonRequired, true)
assert.deepEqual(priceRules(set({ 'orders.price_change_reasons': '[" Friend ", "", 3]' })).reasons, ['Friend'])
assert.deepEqual(priceRules(set({ 'orders.price_change_reasons': 'not json' })).reasons, [])
assert.equal(priceRules(set({ 'orders.price_change': 'weird' })).mode, 'anytime')
})
test('the reason sent: a quick reason, a typed one, or none', async () => {
const { priceReasonText } = await import('../src/logic/priceRules.js')
const t = k => `T:${k}`
const builtIn = priceRules(null)
assert.equal(priceReasonText(builtIn, t, { choice: 'regular', other: '' }), 'T:price.reasons.regular')
assert.equal(priceReasonText(builtIn, t, { choice: 'other', other: ' burnt ' }), 'burnt')
assert.equal(priceReasonText(builtIn, t, { choice: '', other: 'x' }), '')
const own = priceRules(set({ 'orders.price_change_reasons': '["Friend"]' }))
assert.equal(priceReasonText(own, t, { choice: 'v0' }), 'Friend')
})