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
@@ -4,14 +4,14 @@
// table flags, quick messages to the staff, and sending the digital menu to the cloud now.
// Each part shows only with its app on. Dropped from v1: "automatic store schedule" (its switches
// were kept in the browser only and nothing ever read them).
import { useState } from 'react'
import { useId, useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp, Plus, RefreshCw, Trash2 } from 'lucide-react'
import { useModule } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Columns, IconButton, InfoTip, Input, Spinner, Switch } from '@xenia/ui'
import { Button, Columns, IconButton, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
import client from '../../../api/client'
import QuickMessages from './QuickMessages'
import RolePermissions from './RolePermissions'
@@ -64,11 +64,36 @@ function OrderingSettings() {
<Toggle s={s} k="orders.bypass_kds_serve" label={o('bypassKds')} hint={o('bypassKdsHint')} tip={o('bypassKdsTip')} />
<Toggle s={s} k="orders.courses_enabled" label={o('courses')} hint={o('coursesHint')} tip={o('coursesTip')} />
{s.get('orders.courses_enabled') === 'true' && <Courses s={s} />}
<QuickNotes s={s} />
<TextList s={s} k="orders.quick_notes" title={o('quickNotes')} hint={o('quickNotesHint')} tip={o('quickNotesTip')}
itemLabel={o('quickNote')} placeholder={o('newQuickNote')} testId="settings-quick-notes" newTestId="quick-note" />
</SettingsCard>
<PriceChangeSettings s={s} />
</>)
}
/** Prices changed by hand (6F.3): the venue's switch, the reason, the quick reasons. Who may: the
* keys ordering.prices.modify / modify_sent ("What each role may do", a person's permissions). */
function PriceChangeSettings({ s }) {
const { t } = useTranslation('manager')
const p = k => t(`settings.prices.${k}`)
const id = useId()
const reasonOn = s.get('orders.price_change_reason', 'false') === 'true'
return (
<SettingsCard title={p('title')} description={p('intro')} testId="settings-price-changes">
<SettingRow label={p('when')} hint={p('whenHint')} tip={p('whenTip')} htmlFor={id}>
<Select id={id} value={s.get('orders.price_change', 'anytime')} disabled={s.saving} data-testid="setting-orders.price_change"
onChange={e => s.save('orders.price_change', e.target.value)}
options={['off', 'before_sending', 'anytime'].map(v => ({ value: v, label: p(`modes.${v}`) }))} />
</SettingRow>
{s.get('orders.price_change', 'anytime') !== 'off' && (<>
<Toggle s={s} k="orders.price_change_reason" label={p('reason')} hint={p('reasonHint')} tip={p('reasonTip')} />
{reasonOn && <TextList s={s} k="orders.price_change_reasons" title={p('reasons')} hint={p('reasonsHint')}
itemLabel={p('reasonItem')} placeholder={p('newReason')} testId="settings-price-reasons" newTestId="price-reason" />}
</>)}
</SettingsCard>
)
}
/** orders.courses: [{ id, name, color }] in the order they are served. */
function Courses({ s }) {
const { t } = useTranslation('manager')
@@ -94,29 +119,30 @@ function Courses({ s }) {
)
}
/** orders.quick_notes: the notes a waiter can add to a line with one tap. */
function QuickNotes({ s }) {
/** A JSON list of short texts in a setting (orders.quick_notes: notes a waiter adds to a line with
* one tap; orders.price_change_reasons: quick reasons for a price changed by hand, 6F.3). */
function TextList({ s, k, title, hint, tip, itemLabel, placeholder, testId, newTestId }) {
const { t } = useTranslation('manager')
const notes = readJson(s.get('orders.quick_notes', '[]'), [])
const notes = readJson(s.get(k, '[]'), [])
const [typed, setTyped] = useState('')
const [edits, setEdits] = useState({})
const save = next => s.save('orders.quick_notes', JSON.stringify(cleanNotes(next)))
const save = next => s.save(k, JSON.stringify(cleanNotes(next)))
const add = () => { if (typed.trim()) { save([...notes, typed]); setTyped('') } }
return (
<div className="px-5 py-3 grid gap-2" data-testid="settings-quick-notes">
<span className="flex items-center gap-1 text-body font-medium text-ink">{t('settings.ops.quickNotes')}<InfoTip>{t('settings.ops.quickNotesTip')}</InfoTip></span>
<span className="text-label text-ink-2 -mt-1">{t('settings.ops.quickNotesHint')}</span>
<div className="px-5 py-3 grid gap-2" data-testid={testId}>
<span className="flex items-center gap-1 text-body font-medium text-ink">{title}{tip && <InfoTip>{tip}</InfoTip>}</span>
<span className="text-label text-ink-2 -mt-1">{hint}</span>
{notes.map((n, i) => (
<div key={`${i}-${n}`} className="flex items-center gap-2">
<Input value={edits[i] ?? n} aria-label={t('settings.ops.quickNote')} onChange={e => setEdits(x => ({ ...x, [i]: e.target.value }))}
<Input value={edits[i] ?? n} aria-label={itemLabel} onChange={e => setEdits(x => ({ ...x, [i]: e.target.value }))}
onBlur={() => { if (edits[i] != null && edits[i] !== n) save(notes.map((x, j) => (j === i ? edits[i] : x))); setEdits({}) }} />
<IconButton size="sm" variant="ghost" label={t('settings.ops.remove', { name: n })} onClick={() => save(notes.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
</div>
))}
<div className="flex items-center gap-2">
<Input value={typed} placeholder={t('settings.ops.newQuickNote')} aria-label={t('settings.ops.newQuickNote')} onChange={e => setTyped(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid="quick-note-new" />
<Button size="sm" variant="secondary" icon={<Plus size={14} />} disabled={!typed.trim()} onClick={add} data-testid="quick-note-add">{t('settings.ops.add')}</Button>
<Input value={typed} placeholder={placeholder} aria-label={placeholder} onChange={e => setTyped(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid={`${newTestId}-new`} />
<Button size="sm" variant="secondary" icon={<Plus size={14} />} disabled={!typed.trim()} onClick={add} data-testid={`${newTestId}-add`}>{t('settings.ops.add')}</Button>
</div>
</div>
)
@@ -59,6 +59,8 @@ export function PriceEventList({ events }) {
<span className="flex flex-wrap gap-x-3">
{(ev.modifier_name || ev.deal_name) && <span className="font-semibold">{ev.modifier_name || ev.deal_name}</span>}
{ev.applied_by_username && <span className="text-ink-3">{t('orders.history.by', { name: ev.applied_by_username })}</span>}
{ev.approved_by_username && <span className="text-ink-3">{t('orders.history.approvedBy', { name: ev.approved_by_username })}</span>}
{ev.stage && <span className="text-ink-3">{t(`orders.history.stage.${ev.stage}`)}</span>}
{ev.delta_amount != null && (
<span className={cx('font-semibold tabular-nums', ev.delta_amount < 0 ? 'text-success-ink' : 'text-danger-ink')}>
{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}
@@ -15,7 +15,7 @@ import { Pill } from '../overview/parts'
import { lineAmount, lineDetails, nameOf, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic'
const STATUS_TONE = { paid: 'success', cancelled: 'danger', tabbed: 'info', closed: 'warning' }
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink' }
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink', manual_price: 'text-warning-ink' }
export default function OrderLines({ order, open, priceEvents, onPay, onChanged }) {
const { t } = useTranslation('manager')
@@ -79,6 +79,12 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
<span aria-hidden="true">↳</span>
<span>{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}</span>
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
{ev.event_type === 'manual_price' && (
<span className="text-ink-3" data-testid="line-price-change">
{formatMoney(ev.price_before)} → {formatMoney(ev.price_after)}
{ev.applied_by_username && ` · ${ev.applied_by_username}`}{ev.waiter_note && ` · ${ev.waiter_note}`}
</span>
)}
</div>
))}
</div>
@@ -142,7 +142,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
{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}`)}</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>
@@ -2,6 +2,7 @@
// cancelled line (what, how much, who sent it, who cancelled it, why) and every discount given
// (on what, how much, by whom, why), with totals per person; exports for Excel.
import { useState } from 'react'
import { useCan } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
@@ -12,9 +13,11 @@ import { defaultPeriod, periodParams, periodSlug } from '../kit/reportLogic'
export default function MiscReport() {
const { t } = useTranslation('manager')
const seesChanges = useCan('ordering.prices.view_changes')
const tabs = [
{ id: 'cancellations', label: t('reports.misc.cancellations'), Component: CancellationsTab },
{ id: 'discounts', label: t('reports.misc.discounts'), Component: DiscountsTab },
...(seesChanges ? [{ id: 'price-changes', label: t('reports.misc.priceChanges'), Component: PriceChangesTab }] : []),
]
return <ReportPage title={t('reports.misc.title')} tabs={tabs} testId="report-misc" />
}
@@ -102,3 +105,46 @@ function DiscountsTab() {
</div>
)
}
/** Prices changed by hand (6F.3): each change, before → after, its value for the line's quantity,
* where (cart / sent / served), who, the approving manager, why; totals per person. */
function PriceChangesTab() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const params = periodParams(period)
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-price-changes', params], queryFn: () => client.get('/api/reports/price-changes', { params }).then(r => r.data) })
const rows = data?.changes ?? []
const columns = [
{ key: 'at', label: t('reports.misc.when'), render: c => fmt.formatDateTime(c.at, 'datetimeShort') },
{ key: 'product_name', label: t('reports.prod.product'), render: c => <span className="font-semibold text-ink">{c.product_name}</span> },
{ key: 'table_name', label: t('reports.place'), render: c => c.table_name || t('reports.noTable') },
{ key: 'before', label: t('reports.misc.priceWas'), align: 'right', render: c => fmt.formatMoney(c.before) },
{ key: 'after', label: t('reports.misc.priceNow'), align: 'right', render: c => fmt.formatMoney(c.after) },
{ key: 'value', label: t('reports.misc.value'), align: 'right', render: c => <span className={c.value < 0 ? 'font-semibold text-danger-ink' : 'font-semibold text-success-ink'}>{fmt.formatMoney(c.value, { signDisplay: 'exceptZero' })}</span> },
{ key: 'stage', label: t('reports.misc.stage'), render: c => (c.stage ? t(`orders.history.stage.${c.stage}`) : '') },
{ key: 'by', label: t('reports.misc.changedBy'), render: c => c.by || '' },
{ key: 'approved_by', label: t('reports.misc.approvedBy'), render: c => c.approved_by || '' },
{ key: 'reason', label: t('reports.misc.reason'), render: c => c.reason || '' },
]
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} right={<ExportButton endpoint="/api/reports/price-changes/export" params={params} filename={`price-changes-${periodSlug(period)}.csv`} />} />
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('reports.misc.changes')} value={data.count} testId="price-changes-count" />
<Stat label={t('reports.misc.changesValue')} tone={data.total_value < 0 ? 'danger' : 'success'} value={fmt.formatMoney(data.total_value, { signDisplay: 'exceptZero' })} tip={t('reports.misc.changesValueTip')} />
</div>
{data.by_person.length > 1 && (
<Panel title={t('reports.misc.byWhom')}>
<BarList format={v => fmt.formatMoney(v, { signDisplay: 'exceptZero' })} rows={data.by_person.map(p => ({ key: p.user_id ?? '—', label: p.name ?? '—', value: p.total_value, sub: t('reports.misc.changesCount', { count: p.count }) }))} />
</Panel>
)}
<Panel padded={false} title={t('reports.misc.priceChanges')}>
<Table columns={columns} rows={rows} rowTestId="report-price-change" initialSort={{ key: 'at', dir: 'desc' }} limit={500} />
</Panel>
</>)}
</div>
)
}