feat: pricing on v2 (platform-v2 step 6.7)

- manager src/pages/pricing: price rules, price groups, deals, discounts on the tokens,
  English and Greek; the rules as data in pricingLogic.js (tests/pricing.test.mjs)
- routers/pricing: set-up needs pricing.manage, broadcasts pricing.changed; incomplete
  conditions refused (pricing.bad_condition); venue discount settings saved again (the
  date-as-text bug) with empty = no limit (pricing.bad_limit), old "None" tolerated
- nav: Offers & pricing needs pricing.manage
- tests: test_pricing_setup.py (a happy-hour rule prices a counter quote), manager.mjs e2e

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 15:40:51 +02:00
co-authored by Claude Opus 5.5
parent c1af7770cf
commit fd3254aa31
28 changed files with 2040 additions and 2118 deletions
@@ -0,0 +1,159 @@
// Deals (plan step 6.7): offers a waiter is prompted with when an order has the right products,
// e.g. "3 beers → a fourth free". A deal has
// - when: the products the order must have (any of the rows) and optional conditions (all hold);
// - what it gives: a free product, a free one the guest picks from a list, a manual price rule, a
// new price, ± an amount or ± a percentage.
// Nothing is applied by itself: the waiter's phone shows the offer and the waiter accepts or skips it.
import { useState } from 'react'
import toast from 'react-hot-toast'
import { Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { ColourPicker, ConditionList, Missing, PickSeveral, RuleCard, Segmented, TabHead, TagPicker, TargetList } from './PricingParts'
import { COLOURS, useCatalog } from './useCatalog'
import { DEAL_ACTIONS, DEAL_CONDITIONS, DEAL_TARGETS, FREE_CHOICE_FROM, actionText, dealBody, dealForm, dealProblems } from './pricingLogic'
const PAGES = ['when', 'gives']
export default function DealsTab() {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const catalog = useCatalog()
const { data: deals, refetch } = useLiveQuery({ queryKey: ['pricing', 'deals'], queryFn: api.listDeals, events: api.PRICING_EVENTS })
const { data: rules = [] } = useLiveQuery({ queryKey: ['pricing', 'modifiers'], queryFn: api.listModifiers, events: api.PRICING_EVENTS })
const [editing, setEditing] = useState(null)
const [deleting, setDeleting] = useState(null)
const [busy, setBusy] = useState(false)
const run = async (fn, done) => {
setBusy(true)
try { await fn(); if (done) toast.success(done); await refetch(); return true } catch (err) { toast.error(errorMessage(err, t)); return false } finally { setBusy(false) }
}
const givesText = d => {
if (d.action_type === 'free_item') return t('pricing.deals.givesFree', { count: d.action_free_quantity, name: catalog.products.find(p => p.id === d.action_free_item_id)?.name ?? '—' })
if (d.action_type === 'free_choice') return t('pricing.deals.givesChoice', { count: d.action_free_quantity })
if (d.action_type === 'apply_modifier') return t('pricing.deals.givesRule', { name: rules.find(r => r.id === d.action_modifier_id)?.name ?? '—' })
return actionText(d.action_type, d.action_value, formatMoney)
}
return (
<section className="grid gap-4" data-testid="pricing-deals">
<TabHead title={t('pricing.deals.title')} intro={t('pricing.deals.intro')}
action={<Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="pricing-deal-new">{t('pricing.deals.new')}</Button>} />
{!deals ? <div className="flex justify-center p-6"><Spinner /></div>
: deals.length === 0 ? <EmptyState title={t('pricing.deals.none')} description={t('pricing.deals.noneHint')} />
: (
<ul className="grid gap-2">
{deals.map(d => (
<RuleCard key={d.id} testid="pricing-deal" colour={d.color ?? COLOURS[2]} name={d.name} active={d.is_active} busy={busy}
description={d.description}
badges={<span className="px-2 py-0.5 rounded-full bg-accent-soft text-accent-ink text-caption font-semibold">{givesText(d)}</span>}
summary={d.conditions?.length ? t('pricing.rules.conditions', { count: d.conditions.length }) : null}
onToggle={() => run(() => api.toggleDeal(d.id))}
onEdit={() => setEditing(d)} onDelete={() => setDeleting(d)} />
))}
</ul>
)}
{editing && <DealDialog deal={editing} catalog={catalog} rules={rules} busy={busy} onClose={() => setEditing(null)}
onSave={async body => { if (await run(() => api.saveDeal(editing.id, body), t('pricing.saved'))) setEditing(null) }} />}
{deleting && (
<Dialog open size="sm" title={t('pricing.deals.deleteTitle')} onClose={() => setDeleting(null)}
footer={<>
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('pricing.cancel')}</Button>
<Button variant="danger" loading={busy} data-testid="pricing-confirm-delete"
onClick={async () => { if (await run(() => api.deleteDeal(deleting.id), t('pricing.deleted'))) setDeleting(null) }}>{t('pricing.delete')}</Button>
</>}>
<p>{t('pricing.deals.deleteBody', { name: deleting.name })}</p>
</Dialog>
)}
</section>
)
}
function DealDialog({ deal, catalog, rules, busy, onClose, onSave }) {
const { t } = useTranslation('manager')
const [f, setF] = useState(() => dealForm(deal.id ? deal : null, COLOURS[2]))
const [page, setPage] = useState('when')
const [tried, setTried] = useState(false)
const set = (k, v) => setF(p => ({ ...p, [k]: v }))
const problems = dealProblems(f)
const manualRules = rules.filter(r => !r.conditions?.length)
const a = f.action_type
return (
<Dialog open size="lg" onClose={onClose} title={t(deal.id ? 'pricing.deals.edit' : 'pricing.deals.new')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('pricing.cancel')}</Button>
<Button loading={busy} data-testid="pricing-save" onClick={() => { setTried(true); if (!problems.length) onSave(dealBody(f)) }}>{t('pricing.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="pricing-deal-dialog">
<div className="grid sm:grid-cols-2 gap-3">
<Field label={t('pricing.name')}><Input value={f.name} autoFocus onChange={e => set('name', e.target.value)} placeholder={t('pricing.deals.namePlaceholder')} data-testid="pricing-name" /></Field>
<Field label={t('pricing.description')} hint={t('pricing.deals.descriptionHint')}><Input value={f.description} onChange={e => set('description', e.target.value)} /></Field>
</div>
<div className="flex flex-wrap gap-1 border-b border-line" role="tablist">
{PAGES.map(k => (
<button key={k} type="button" role="tab" aria-selected={page === k} onClick={() => setPage(k)} data-testid={`pricing-deal-page-${k}`}
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast ${page === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
{t(`pricing.deals.pages.${k}`)}
</button>
))}
</div>
{page === 'when' && (
<div className="grid gap-3">
<p className="text-caption text-ink-2">{t('pricing.deals.targetsHint')}</p>
<TargetList value={f.targets} onChange={v => set('targets', v)} types={DEAL_TARGETS} catalog={catalog} testid="pricing-deal-targets" />
<p className="text-caption text-ink-2">{t('pricing.deals.conditionsHint')}</p>
<ConditionList value={f.conditions} onChange={v => set('conditions', v)} types={DEAL_CONDITIONS} catalog={catalog} testid="pricing-deal-conditions" />
<Switch checked={f.is_active} onChange={v => set('is_active', v)} label={t('pricing.deals.on')} />
</div>
)}
{page === 'gives' && (
<div className="grid gap-3">
<Segmented value={a} onChange={v => set('action_type', v)} testid="pricing-deal-action"
options={DEAL_ACTIONS.map(v => ({ value: v, label: t(`pricing.deals.actions.${v}`) }))} />
{a === 'free_item' && (
<Field label={t('pricing.deals.freeProduct')}>
<Select value={f.action_free_item_id ?? ''} onChange={e => set('action_free_item_id', e.target.value === '' ? null : Number(e.target.value))}
placeholder={t('pricing.choose')} options={catalog.products.map(p => ({ value: p.id, label: p.name }))} data-testid="pricing-deal-free-product" />
</Field>
)}
{a === 'free_choice' && (
<>
<Segmented value={f.action_free_target_type} onChange={v => setF(p => ({ ...p, action_free_target_type: v, action_free_target_ids: [] }))}
options={FREE_CHOICE_FROM.map(v => ({ value: v, label: t(`pricing.deals.freeFrom.${v}`) }))} />
{f.action_free_target_type === 'item' && <PickSeveral items={catalog.products} value={f.action_free_target_ids} onChange={v => set('action_free_target_ids', v)} />}
{f.action_free_target_type === 'category' && <PickSeveral items={catalog.categories} value={f.action_free_target_ids} onChange={v => set('action_free_target_ids', v)} />}
{f.action_free_target_type === 'tag' && <TagPicker value={f.action_free_target_ids} onChange={v => set('action_free_target_ids', v)} known={catalog.tags} />}
</>
)}
{(a === 'free_item' || a === 'free_choice') && (
<Field label={t('pricing.deals.quantity')}>
<Input type="number" min={1} step={1} className="w-28" value={f.action_free_quantity}
onChange={e => set('action_free_quantity', Number(e.target.value))} />
</Field>
)}
{a === 'apply_modifier' && (
<Field label={t('pricing.deals.rule')} hint={t('pricing.deals.ruleHint')}>
<Select value={f.action_modifier_id ?? ''} onChange={e => set('action_modifier_id', e.target.value === '' ? null : Number(e.target.value))}
placeholder={manualRules.length ? t('pricing.choose') : t('pricing.deals.noManualRules')} options={manualRules.map(r => ({ value: r.id, label: r.name }))} />
</Field>
)}
{['set_price', 'add_amount', 'add_percent'].includes(a) && (
<Field label={t(`pricing.actions.valueLabel.${a === 'set_price' ? 'set' : a}`)} hint={a !== 'set_price' ? t('pricing.actions.minusHint') : undefined}>
<Input type="number" step={a === 'add_percent' ? 1 : 0.1} className="w-36" value={Number.isFinite(f.action_value) ? f.action_value : ''}
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} />
</Field>
)}
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
</div>
)}
{tried && <Missing problems={problems} prefix="pricing.deals.problems" />}
</div>
</Dialog>
)
}
@@ -0,0 +1,136 @@
// Waiter discounts (plan step 6.7): the venue's switch and limits, then each person's.
// - Venue: discounts on or off for everyone (off: nobody can give one, not even with a manager's
// approval), the most the whole venue gives in a business day, the most given during a waiter's
// shift (everyone's discounts since that shift began) and how many items.
// - Per person: may give discounts at all, the most per discount (% and amount), and their own
// totals per shift / per business day / per order. Both sets apply: the first limit reached stops it.
// Past a limit a person with "Give discounts beyond the limits" goes on, others need a manager's
// approval on the spot (D-10). An empty box = no limit.
import { useState } from 'react'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { TabHead } from './PricingParts'
import { COUNT_LIMITS, VENUE_LIMITS, WAITER_LIMITS, limitText, parseLimit } from './pricingLogic'
const UNIT = { max_discount_percent: '%', max_discount_amount: '€', max_total_value_shift: '€', max_total_value_workday: '€' }
export default function DiscountsTab() {
const { t } = useTranslation('manager')
return (
<section className="grid gap-5" data-testid="pricing-discounts">
<TabHead title={t('pricing.discounts.title')} intro={t('pricing.discounts.intro')} />
<VenueLimits />
<PersonLimits />
</section>
)
}
function LimitBoxes({ keys, texts, setText, prefix }) {
const { t } = useTranslation('manager')
return (
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
{keys.map(k => {
const bad = !parseLimit(texts[k], COUNT_LIMITS.has(k)).ok
return (
<Field key={k} label={t(`${prefix}.${k}`)} hint={t(`${prefix}.${k}Hint`)} error={bad ? t('pricing.discounts.badNumber') : undefined}>
<div className="flex items-center gap-2">
<Input inputMode="decimal" className="w-28" value={texts[k]} placeholder={t('pricing.discounts.noLimit')}
onChange={e => setText(k, e.target.value)} data-testid={`limit-${k}`} />
<span className="text-label text-ink-2">{UNIT[k] ?? t('pricing.discounts.items')}</span>
</div>
</Field>
)
})}
</div>
)
}
const textsOf = (data, keys) => Object.fromEntries(keys.map(k => [k, limitText(data?.[k])]))
function VenueLimits() {
const { t } = useTranslation('manager')
const { data, refetch } = useLiveQuery({ queryKey: ['pricing', 'venue-limits'], queryFn: api.venueLimits, events: api.PRICING_EVENTS })
if (!data) return <div className="flex justify-center p-6"><Spinner /></div>
return <VenueForm key={JSON.stringify(data)} data={data} onSaved={refetch} t={t} />
}
function VenueForm({ data, onSaved, t }) {
const [on, setOn] = useState(data.enabled !== false)
const [texts, setTexts] = useState(() => textsOf(data, VENUE_LIMITS))
const [busy, setBusy] = useState(false)
const parsed = VENUE_LIMITS.map(k => [k, parseLimit(texts[k], COUNT_LIMITS.has(k))])
const ok = parsed.every(([, p]) => p.ok)
const save = async () => {
setBusy(true)
try {
await api.saveVenueLimits({ enabled: on, ...Object.fromEntries(parsed.map(([k, p]) => [k, p.value])) })
toast.success(t('pricing.saved'))
await onSaved()
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}
return (
<div className="grid gap-4 p-5 rounded-card border border-line bg-surface shadow-raised" data-testid="pricing-venue-limits">
<header className="grid gap-0.5">
<h3 className="text-body font-semibold text-ink">{t('pricing.discounts.venue')}</h3>
<p className="text-label text-ink-2">{t('pricing.discounts.venueHint')}</p>
</header>
<Switch checked={on} onChange={setOn} label={t('pricing.discounts.enabled')} description={t('pricing.discounts.enabledHint')} data-testid="discounts-enabled" />
<LimitBoxes keys={VENUE_LIMITS} texts={texts} setText={(k, v) => setTexts(s => ({ ...s, [k]: v }))} prefix="pricing.discounts.venueLimits" />
<div className="flex justify-end"><Button loading={busy} disabled={!ok} onClick={save} data-testid="pricing-venue-save">{t('pricing.save')}</Button></div>
</div>
)
}
const personName = p => p.nickname || p.full_name || p.username
function PersonLimits() {
const { t } = useTranslation('manager')
const { data: staff } = useLiveQuery({ queryKey: ['staff'], queryFn: api.listStaff })
const people = (staff ?? []).filter(p => p.is_active !== false)
const [chosen, setChosen] = useState(null)
const id = chosen ?? people[0]?.id ?? null
const { data } = useLiveQuery({ queryKey: ['pricing', 'person-limits', id], queryFn: () => api.waiterLimits(id), enabled: !!id, events: api.PRICING_EVENTS })
return (
<div className="grid gap-4 p-5 rounded-card border border-line bg-surface shadow-raised" data-testid="pricing-person-limits">
<header className="grid gap-0.5">
<h3 className="text-body font-semibold text-ink">{t('pricing.discounts.person')}</h3>
<p className="text-label text-ink-2">{t('pricing.discounts.personHint')}</p>
</header>
{!staff ? <Spinner /> : people.length === 0 ? <EmptyState compact title={t('pricing.discounts.nobody')} /> : (
<>
<Field label={t('pricing.discounts.who')}>
<Select value={id ?? ''} onChange={e => setChosen(Number(e.target.value))} data-testid="pricing-person"
options={people.map(p => ({ value: p.id, label: personName(p) }))} />
</Field>
{!data ? <Spinner /> : <PersonForm key={`${id}:${JSON.stringify(data)}`} id={id} data={data} t={t} />}
</>
)}
</div>
)
}
function PersonForm({ id, data, t }) {
const [can, setCan] = useState(!!data.can_apply_discounts)
const [texts, setTexts] = useState(() => textsOf(data, WAITER_LIMITS))
const [busy, setBusy] = useState(false)
const parsed = WAITER_LIMITS.map(k => [k, parseLimit(texts[k], COUNT_LIMITS.has(k))])
const ok = parsed.every(([, p]) => p.ok)
const save = async () => {
setBusy(true)
try {
await api.saveWaiterLimits(id, { can_apply_discounts: can, ...Object.fromEntries(parsed.map(([k, p]) => [k, p.value])) })
toast.success(t('pricing.saved'))
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}
return (
<div className="grid gap-4">
<Switch checked={can} onChange={setCan} label={t('pricing.discounts.can')} description={t('pricing.discounts.canHint')} data-testid="discounts-can" />
<LimitBoxes keys={WAITER_LIMITS} texts={texts} setText={(k, v) => setTexts(s => ({ ...s, [k]: v }))} prefix="pricing.discounts.personLimits" />
<div className="flex justify-end"><Button loading={busy} disabled={!ok} onClick={save} data-testid="pricing-person-save">{t('pricing.save')}</Button></div>
</div>
)
}
@@ -0,0 +1,176 @@
// Price rules (modifiers, plan step 6.7): change the price of some products while conditions hold,
// e.g. "drinks −20% from 17:00 to 19:00". A rule has
// - what it changes: one product, or (all products | some products | categories | prep zones |
// tags; any of the rows);
// - when: conditions, all of which must hold (no condition = always while it's on);
// - by how much: ± a percentage (with an optional rounding), ± an amount, or a new price.
// The order is the priority: of the rules that don't stack only the first that applies counts;
// the stacking ones all apply after it, in order. The server rounds the final price to 0.10.
// New prices apply to what is added to orders from then on (the counter, the phones, the tablets).
import { useState } from 'react'
import toast from 'react-hot-toast'
import { Layers, Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { ColourPicker, ConditionList, Missing, RuleCard, Segmented, TabHead, TargetList } from './PricingParts'
import { COLOURS, useCatalog } from './useCatalog'
import {
MODIFIER_ACTIONS, MODIFIER_CONDITIONS, MODIFIER_TARGETS, ROUNDINGS, actionText, examplePrice, modifierBody, modifierForm, modifierProblems, moveItem,
} from './pricingLogic'
const PAGES = ['what', 'when', 'price']
export default function ModifiersTab() {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const catalog = useCatalog()
const { data: rules, refetch } = useLiveQuery({ queryKey: ['pricing', 'modifiers'], queryFn: api.listModifiers, events: api.PRICING_EVENTS })
const [editing, setEditing] = useState(null)
const [deleting, setDeleting] = useState(null)
const [busy, setBusy] = useState(false)
const run = async (fn, done) => {
setBusy(true)
try { await fn(); if (done) toast.success(done); await refetch(); return true } catch (err) { toast.error(errorMessage(err, t)); return false } finally { setBusy(false) }
}
const productName = id => catalog.products.find(p => p.id === id)?.name ?? '—'
const whatText = m => (m.scope === 'item' ? productName(m.item_id)
: m.targets?.some(x => x.target_type === 'all') ? t('pricing.rules.allProducts') : t('pricing.rules.someProducts', { count: m.targets?.length ?? 0 }))
const whenText = m => (m.conditions?.length ? t('pricing.rules.conditions', { count: m.conditions.length }) : t('pricing.rules.always'))
return (
<section className="grid gap-4" data-testid="pricing-rules">
<TabHead title={t('pricing.rules.title')} intro={t('pricing.rules.intro')}
action={<Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="pricing-rule-new">{t('pricing.rules.new')}</Button>} />
{!rules ? <div className="flex justify-center p-6"><Spinner /></div>
: rules.length === 0 ? <EmptyState title={t('pricing.rules.none')} description={t('pricing.rules.noneHint')} />
: (
<>
<p className="text-caption text-ink-3">{t('pricing.rules.orderHint')}</p>
<ul className="grid gap-2">
{rules.map((m, i) => (
<RuleCard key={m.id} testid="pricing-rule" colour={m.color ?? COLOURS[0]} name={m.name} active={m.is_active} busy={busy}
description={m.description}
badges={<>
<span className="px-2 py-0.5 rounded-full bg-accent-soft text-accent-ink text-caption font-semibold tabular-nums" data-testid="pricing-rule-action">{actionText(m.action_type, m.action_value, formatMoney)}</span>
{m.allow_stack && <span className="inline-flex items-center gap-1 text-caption text-ink-2"><Layers size={12} aria-hidden="true" />{t('pricing.rules.stacks')}</span>}
</>}
summary={`${whatText(m)} · ${whenText(m)}`}
onUp={i > 0 ? () => run(() => api.reorderModifiers(moveItem(rules, i, i - 1))) : undefined}
onDown={i < rules.length - 1 ? () => run(() => api.reorderModifiers(moveItem(rules, i, i + 1))) : undefined}
onToggle={() => run(() => api.toggleModifier(m.id))}
onEdit={() => setEditing(m)} onDelete={() => setDeleting(m)} />
))}
</ul>
</>
)}
{editing && <RuleDialog rule={editing} catalog={catalog} busy={busy} onClose={() => setEditing(null)}
onSave={async body => {
if (!editing.id) body.sort_order = rules?.length ?? 0 // a new rule goes last
if (await run(() => api.saveModifier(editing.id, body), t('pricing.saved'))) setEditing(null)
}} />}
{deleting && (
<Dialog open size="sm" title={t('pricing.rules.deleteTitle')} onClose={() => setDeleting(null)}
footer={<>
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('pricing.cancel')}</Button>
<Button variant="danger" loading={busy} data-testid="pricing-confirm-delete"
onClick={async () => { if (await run(() => api.deleteModifier(deleting.id), t('pricing.deleted'))) setDeleting(null) }}>{t('pricing.delete')}</Button>
</>}>
<p>{t('pricing.rules.deleteBody', { name: deleting.name })}</p>
</Dialog>
)}
</section>
)
}
function RuleDialog({ rule, catalog, busy, onClose, onSave }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [f, setF] = useState(() => modifierForm(rule.id ? rule : null, COLOURS[0]))
const [page, setPage] = useState('what')
const [tried, setTried] = useState(false)
const set = (k, v) => setF(p => ({ ...p, [k]: v }))
const problems = modifierProblems(f)
const sample = 5
return (
<Dialog open size="lg" onClose={onClose} title={t(rule.id ? 'pricing.rules.edit' : 'pricing.rules.new')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('pricing.cancel')}</Button>
<Button loading={busy} data-testid="pricing-save" onClick={() => { setTried(true); if (!problems.length) onSave(modifierBody(f)) }}>{t('pricing.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="pricing-rule-dialog">
<div className="grid sm:grid-cols-2 gap-3">
<Field label={t('pricing.name')}><Input value={f.name} autoFocus onChange={e => set('name', e.target.value)} placeholder={t('pricing.rules.namePlaceholder')} data-testid="pricing-name" /></Field>
<Field label={t('pricing.description')}><Input value={f.description} onChange={e => set('description', e.target.value)} /></Field>
</div>
<div className="flex flex-wrap gap-1 border-b border-line" role="tablist">
{PAGES.map(k => (
<button key={k} type="button" role="tab" aria-selected={page === k} onClick={() => setPage(k)} data-testid={`pricing-rule-page-${k}`}
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast ${page === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
{t(`pricing.rules.pages.${k}`)}
</button>
))}
</div>
{page === 'what' && (
<div className="grid gap-3">
<Segmented value={f.scope} onChange={v => set('scope', v)} testid="pricing-rule-scope"
options={['global', 'item'].map(v => ({ value: v, label: t(`pricing.rules.scopes.${v}`) }))} />
{f.scope === 'item' ? (
<Field label={t('pricing.rules.product')}>
<Select value={f.item_id ?? ''} onChange={e => set('item_id', e.target.value === '' ? null : Number(e.target.value))}
placeholder={t('pricing.choose')} options={catalog.products.map(p => ({ value: p.id, label: p.name }))} />
</Field>
) : (
<>
<p className="text-caption text-ink-2">{t('pricing.rules.targetsHint')}</p>
<TargetList value={f.targets} onChange={v => set('targets', v)} types={MODIFIER_TARGETS} catalog={catalog} testid="pricing-rule-targets" />
</>
)}
</div>
)}
{page === 'when' && (
<div className="grid gap-3">
<p className="text-caption text-ink-2">{t('pricing.rules.conditionsHint')}</p>
<ConditionList value={f.conditions} onChange={v => set('conditions', v)} types={MODIFIER_CONDITIONS} catalog={catalog} testid="pricing-rule-conditions" />
<Switch checked={f.is_active} onChange={v => set('is_active', v)} label={t('pricing.rules.on')} description={t('pricing.rules.onHint')} />
</div>
)}
{page === 'price' && (
<div className="grid gap-3">
<Segmented value={f.action_type} onChange={v => set('action_type', v)} testid="pricing-rule-action-type"
options={MODIFIER_ACTIONS.map(v => ({ value: v, label: t(`pricing.actions.${v}`) }))} />
<div className="grid sm:grid-cols-2 gap-3">
<Field label={t(`pricing.actions.valueLabel.${f.action_type}`)} hint={f.action_type !== 'set' ? t('pricing.actions.minusHint') : undefined}>
<Input type="number" step={f.action_type === 'add_percent' ? 1 : 0.1} value={Number.isFinite(f.action_value) ? f.action_value : ''}
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} data-testid="pricing-rule-value" />
</Field>
{f.action_type === 'add_percent' && (
<Field label={t('pricing.rules.rounding')}>
<Select value={f.round_to} onChange={e => set('round_to', e.target.value)}
options={ROUNDINGS.map(v => ({ value: v, label: t(`pricing.roundings.${v ? v.replace('.', '_') : 'none'}`) }))} />
</Field>
)}
</div>
{Number.isFinite(f.action_value) && (
<p className="text-label text-ink-2" data-testid="pricing-rule-example">
{t('pricing.rules.example', { before: formatMoney(sample), after: formatMoney(examplePrice(sample, f.action_type, f.action_value, f.round_to)) })}
</p>
)}
<div className="flex items-center gap-1">
<Switch checked={f.allow_stack} onChange={v => set('allow_stack', v)} label={t('pricing.rules.stack')} />
<InfoTip>{t('pricing.rules.stackTip')}</InfoTip>
</div>
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
</div>
)}
{tried && <Missing problems={problems} prefix="pricing.rules.problems" />}
</div>
</Dialog>
)
}
@@ -0,0 +1,95 @@
// Price groups (plan step 6.7): named switches like "Happy hour" or "Summer", on by hand or by a
// weekly schedule (from–to on some days, in the venue's time). A price rule or a deal can have the
// condition "a price group is on", so several rules follow one switch.
import { useState } from 'react'
import toast from 'react-hot-toast'
import { Clock, Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, Spinner, Switch } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { ColourPicker, DayPicker, Missing, RuleCard, TabHead } from './PricingParts'
import { COLOURS } from './useCatalog'
import { groupBody, groupForm, groupProblems, groupSchedule } from './pricingLogic'
export default function PriceGroupsTab() {
const { t } = useTranslation('manager')
const { data: groups, refetch } = useLiveQuery({ queryKey: ['pricing', 'groups'], queryFn: api.listGroups, events: api.PRICING_EVENTS })
const [editing, setEditing] = useState(null) // a group, or {} for a new one
const [deleting, setDeleting] = useState(null)
const [busy, setBusy] = useState(false)
const run = async (fn, done) => {
setBusy(true)
try { await fn(); if (done) toast.success(done); await refetch(); return true } catch (err) { toast.error(errorMessage(err, t)); return false } finally { setBusy(false) }
}
const days = g => groupSchedule(g)?.days.map(d => t(`signage.weekdays.${d}`)).join(' ')
return (
<section className="grid gap-4" data-testid="pricing-groups">
<TabHead title={t('pricing.groups.title')} intro={t('pricing.groups.intro')}
action={<Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="pricing-group-new">{t('pricing.groups.new')}</Button>} />
{!groups ? <div className="flex justify-center p-6"><Spinner /></div>
: groups.length === 0 ? <EmptyState title={t('pricing.groups.none')} description={t('pricing.groups.noneHint')} />
: (
<ul className="grid gap-2">
{groups.map(g => {
const s = groupSchedule(g)
return (
<RuleCard key={g.id} testid="pricing-group" colour={g.color ?? COLOURS[0]} name={g.name} active={g.is_active} busy={busy}
description={g.description}
summary={s ? <span className="inline-flex items-center gap-1"><Clock size={12} aria-hidden="true" />{t('pricing.groups.scheduled', { from: s.from, to: s.to, days: days(g) })}</span> : t('pricing.groups.byHand')}
onToggle={() => run(() => api.toggleGroup(g.id))}
onEdit={() => setEditing(g)} onDelete={() => setDeleting(g)} />
)
})}
</ul>
)}
{editing && <GroupDialog group={editing} busy={busy} onClose={() => setEditing(null)}
onSave={async body => { if (await run(() => api.saveGroup(editing.id, body), t('pricing.saved'))) setEditing(null) }} />}
{deleting && (
<Dialog open size="sm" title={t('pricing.groups.deleteTitle')} onClose={() => setDeleting(null)}
footer={<>
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('pricing.cancel')}</Button>
<Button variant="danger" loading={busy} data-testid="pricing-confirm-delete"
onClick={async () => { if (await run(() => api.deleteGroup(deleting.id), t('pricing.deleted'))) setDeleting(null) }}>{t('pricing.delete')}</Button>
</>}>
<p>{t('pricing.groups.deleteBody', { name: deleting.name })}</p>
</Dialog>
)}
</section>
)
}
function GroupDialog({ group, busy, onClose, onSave }) {
const { t } = useTranslation('manager')
const [f, setF] = useState(() => groupForm(group.id ? group : null, COLOURS[0]))
const set = (k, v) => setF(p => ({ ...p, [k]: v }))
const problems = groupProblems(f)
const [tried, setTried] = useState(false)
return (
<Dialog open size="md" onClose={onClose} title={t(group.id ? 'pricing.groups.edit' : 'pricing.groups.new')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('pricing.cancel')}</Button>
<Button loading={busy} data-testid="pricing-save" onClick={() => { setTried(true); if (!problems.length) onSave(groupBody(f)) }}>{t('pricing.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="pricing-group-dialog">
<Field label={t('pricing.name')}><Input value={f.name} autoFocus onChange={e => set('name', e.target.value)} placeholder={t('pricing.groups.namePlaceholder')} data-testid="pricing-name" /></Field>
<Field label={t('pricing.description')}><Input value={f.description} onChange={e => set('description', e.target.value)} /></Field>
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
<Switch checked={f.is_active} onChange={v => set('is_active', v)} label={t('pricing.groups.onNow')} description={t('pricing.groups.onNowHint')} />
<fieldset className="grid gap-3 p-3 rounded-control border border-line">
<legend className="px-1 text-label font-semibold text-ink">{t('pricing.groups.schedule')}</legend>
<p className="text-caption text-ink-2">{t('pricing.groups.scheduleHint')}</p>
<div className="grid grid-cols-2 gap-3">
<Field label={t('pricing.condition.from')}><Input type="time" value={f.auto_enable_time} onChange={e => set('auto_enable_time', e.target.value)} /></Field>
<Field label={t('pricing.condition.to')}><Input type="time" value={f.auto_disable_time} onChange={e => set('auto_disable_time', e.target.value)} /></Field>
</div>
<DayPicker value={f.auto_days} onChange={v => set('auto_days', v)} />
</fieldset>
{tried && <Missing problems={problems} prefix="pricing.groups.problems" />}
</div>
</Dialog>
)
}
@@ -0,0 +1,37 @@
// Management → Pricing (plan step 6.7): price rules, price groups, deals and the waiters' discount
// limits, one tab each. Changes reach the counter, the phones and the tablets at once: new prices
// apply to what is added to orders from then on (lines already on an order keep their price).
import { useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import DealsTab from './DealsTab'
import DiscountsTab from './DiscountsTab'
import ModifiersTab from './ModifiersTab'
import PriceGroupsTab from './PriceGroupsTab'
const TABS = ['rules', 'groups', 'deals', 'discounts']
export default function PricingPage() {
const { t } = useTranslation('manager')
const [tab, setTab] = useState('rules')
return (
<div className="p-4 md:p-6 grid gap-5 max-w-5xl content-start" data-testid="pricing-page">
<header className="grid gap-1">
<h1 className="text-heading font-semibold text-ink">{t('pricing.pageTitle')}</h1>
<p className="text-body text-ink-2 max-w-3xl">{t('pricing.intro')}</p>
</header>
<div className="flex flex-wrap gap-1 border-b border-line" role="tablist" aria-label={t('pricing.pageTitle')}>
{TABS.map(k => (
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`pricing-tab-${k}`}
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast
${tab === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
{t(`pricing.tabs.${k}`)}
</button>
))}
</div>
{tab === 'rules' && <ModifiersTab />}
{tab === 'groups' && <PriceGroupsTab />}
{tab === 'deals' && <DealsTab />}
{tab === 'discounts' && <DiscountsTab />}
</div>
)
}
@@ -0,0 +1,291 @@
// Pieces the pricing tabs share (plan step 6.7): the colour and day pickers, the condition list (AND) and the target list (OR), a searchable
// pick-several list, a tag picker, and the card a rule, a deal or a group shows as.
import { useState } from 'react'
import { ArrowDown, ArrowUp, Check, Pencil, Plus, Power, Trash2, X } from 'lucide-react'
import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access'
import { latin, useFormat, useTranslation } from '@xenia/i18n'
import { Button, IconButton, Input, Select, cx } from '@xenia/ui'
import { COLOURS } from './useCatalog'
import { OLD_PLACEHOLDERS, WEEKDAYS, blankCondition, conditionComplete, toggleIn } from './pricingLogic'
export function ColourPicker({ value, onChange, label }) {
return (
<div className="grid gap-2">
<span className="text-label font-semibold text-ink">{label}</span>
<div className="flex flex-wrap gap-2" role="radiogroup" aria-label={label}>
{COLOURS.map(c => (
<button key={c} type="button" role="radio" aria-checked={value === c} aria-label={c} onClick={() => onChange(c)}
className={cx('w-8 h-8 rounded-full grid place-items-center text-accent-fg ring-offset-2 ring-offset-surface', value === c && 'ring-2 ring-[var(--x-ink)]')}
style={{ background: c }}>
{value === c && <Check size={14} />}
</button>
))}
</div>
</div>
)
}
export function DayPicker({ value = [], onChange, testid }) {
const { t } = useTranslation('manager')
return (
<div className="flex flex-wrap gap-1.5" data-testid={testid}>
{WEEKDAYS.map(d => (
<button key={d} type="button" aria-pressed={value.includes(d)} onClick={() => onChange(toggleIn(value, d).sort())}
className={cx('px-3 py-1.5 rounded-control border text-label font-medium transition-colors duration-fast',
value.includes(d) ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{t(`signage.weekdays.${d}`)}
</button>
))}
</div>
)
}
/** Chips to pick several values (sales points, days…). */
export function Chips({ options, value, onChange, testid }) {
return (
<div className="flex flex-wrap gap-1.5" data-testid={testid}>
{options.map(o => (
<button key={o.value} type="button" aria-pressed={value.includes(o.value)} onClick={() => onChange(toggleIn(value, o.value))}
className={cx('px-3 py-1.5 rounded-control border text-label font-medium transition-colors duration-fast',
value.includes(o.value) ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{o.label}
</button>
))}
</div>
)
}
/** One of a few choices as buttons (scope, action…). */
export function Segmented({ options, value, onChange, testid }) {
return (
<div className="flex flex-wrap gap-2" role="radiogroup" data-testid={testid}>
{options.map(o => (
<button key={o.value} type="button" role="radio" aria-checked={value === o.value} onClick={() => onChange(o.value)} data-value={o.value}
className={cx('flex-1 min-w-[8rem] px-3 py-2 rounded-control border text-label font-medium text-center transition-colors duration-fast',
value === o.value ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{o.label}
</button>
))}
</div>
)
}
/** A searchable list to pick several (products, categories, zones). */
export function PickSeveral({ items, value, onChange, testid }) {
const { t } = useTranslation('manager')
const [q, setQ] = useState('')
const fold = v => latin(String(v)).toLowerCase()
const shown = q.trim() ? items.filter(i => fold(i.plain ?? i.name).includes(fold(q.trim()))) : items
const chosen = items.filter(i => value.includes(i.id))
return (
<div className="grid gap-2" data-testid={testid}>
{chosen.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{chosen.map(i => (
<span key={i.id} className="inline-flex items-center gap-1 pl-2.5 pr-1 py-0.5 rounded-full bg-accent-soft text-accent-ink text-label">
{i.plain ?? i.name}
<button type="button" aria-label={t('pricing.remove')} onClick={() => onChange(value.filter(v => v !== i.id))} className="p-0.5 rounded-full hover:bg-surface"><X size={12} /></button>
</span>
))}
</div>
)}
{items.length > 8 && <Input size="sm" value={q} onChange={e => setQ(e.target.value)} placeholder={t('pricing.search')} aria-label={t('pricing.search')} />}
<ul className="max-h-48 overflow-y-auto rounded-control border border-line divide-y divide-line bg-surface">
{shown.length === 0 && <li className="px-3 py-2 text-label text-ink-3">{t('pricing.nothingFound')}</li>}
{shown.map(i => {
const on = value.includes(i.id)
return (
<li key={i.id}>
<button type="button" role="checkbox" aria-checked={on} onClick={() => onChange(toggleIn(value, i.id))} data-name={i.plain ?? i.name}
className={cx('w-full flex items-center gap-2.5 px-3 py-1.5 text-left text-label', on ? 'bg-accent-soft text-accent-ink' : 'text-ink hover:bg-surface-2')}>
<span className={cx('w-4 h-4 rounded border grid place-items-center shrink-0', on ? 'bg-accent border-accent text-accent-fg' : 'border-line-strong bg-surface')}>
{on && <Check size={12} />}
</span>
<span className="truncate">{i.name}</span>
</button>
</li>
)
})}
</ul>
</div>
)
}
export function TagPicker({ value, onChange, known }) {
const { t } = useTranslation('manager')
const [draft, setDraft] = useState('')
const add = () => { const v = draft.trim(); if (v && !value.includes(v)) onChange([...value, v]); setDraft('') }
return (
<div className="grid gap-2">
{known.length > 0 && <Chips options={known.map(k => ({ value: k, label: k }))} value={value} onChange={onChange} />}
<div className="flex gap-2">
<Input size="sm" value={draft} onChange={e => setDraft(e.target.value)} placeholder={t('pricing.newTag')} aria-label={t('pricing.newTag')}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); add() } }} />
<Button size="sm" variant="secondary" onClick={add} disabled={!draft.trim()}>{t('pricing.add')}</Button>
</div>
{value.filter(v => !known.includes(v)).length > 0 && (
<Chips options={value.filter(v => !known.includes(v)).map(k => ({ value: k, label: k }))} value={value} onChange={onChange} />
)}
</div>
)
}
/** The products a rule or a deal looks at: any one of the rows (OR). */
export function TargetList({ value, onChange, types, catalog, testid }) {
const { t } = useTranslation('manager')
const set = (i, v) => onChange(value.map((x, j) => (j === i ? v : x)))
return (
<div className="grid gap-2" data-testid={testid}>
{value.map((tg, i) => (
<div key={i} className="grid gap-2 p-3 rounded-control border border-line bg-surface-2" data-testid="pricing-target">
<div className="flex items-center gap-2">
<Select size="sm" className="flex-1" value={tg.target_type} aria-label={t('pricing.target.type')}
onChange={e => set(i, { target_type: e.target.value, target_ids: [], target_tags: [] })}
options={types.map(v => ({ value: v, label: t(`pricing.target.types.${v}`) }))} />
{value.length > 1 && <IconButton size="sm" variant="ghost" label={t('pricing.remove')} onClick={() => onChange(value.filter((_, j) => j !== i))}><X size={14} /></IconButton>}
</div>
{tg.target_type === 'item' && <PickSeveral items={catalog.products} value={tg.target_ids} onChange={v => set(i, { ...tg, target_ids: v })} testid="pricing-target-products" />}
{tg.target_type === 'category' && <PickSeveral items={catalog.categories} value={tg.target_ids} onChange={v => set(i, { ...tg, target_ids: v })} testid="pricing-target-categories" />}
{tg.target_type === 'prep_zone' && <PickSeveral items={catalog.zones} value={tg.target_ids} onChange={v => set(i, { ...tg, target_ids: v })} />}
{tg.target_type === 'tag' && <TagPicker value={tg.target_tags} onChange={v => set(i, { ...tg, target_tags: v })} known={catalog.tags} />}
</div>
))}
<div><Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => onChange([...value, { target_type: types[0], target_ids: [], target_tags: [] }])}>{t('pricing.target.add')}</Button></div>
</div>
)
}
/** The conditions: all of them must hold (AND). */
export function ConditionList({ value, onChange, types, catalog, testid }) {
const { t } = useTranslation('manager')
const set = (i, v) => onChange(value.map((x, j) => (j === i ? v : x)))
return (
<div className="grid gap-2" data-testid={testid}>
{value.map((c, i) => (
<div key={i} className={cx('grid gap-2 p-3 rounded-control border bg-surface-2', conditionComplete(c) ? 'border-line' : 'border-warning')} data-testid="pricing-condition">
<div className="flex items-center gap-2">
{OLD_PLACEHOLDERS.includes(c.condition_type)
? <span className="flex-1 text-label text-ink-2">{t('pricing.condition.placeholder')}</span>
: <Select size="sm" className="flex-1" value={c.condition_type} aria-label={t('pricing.condition.type')}
onChange={e => set(i, blankCondition(e.target.value))}
options={types.map(v => ({ value: v, label: t(`pricing.condition.types.${v}`) }))} />}
<IconButton size="sm" variant="ghost" label={t('pricing.remove')} onClick={() => onChange(value.filter((_, j) => j !== i))}><X size={14} /></IconButton>
</div>
<ConditionFields cond={c} onChange={v => set(i, v)} catalog={catalog} />
</div>
))}
<div><Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => onChange([...value, blankCondition(types[0])])} data-testid="pricing-condition-add">{t('pricing.condition.add')}</Button></div>
</div>
)
}
function ConditionFields({ cond, onChange, catalog }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const p = cond.params ?? {}
const set = (k, v) => onChange({ ...cond, params: { ...p, [k]: v } })
const num = (k, low, step) => (
<Input size="sm" type="number" min={low} step={step} className="w-32" value={p[k] ?? ''} aria-label={t(`pricing.condition.fields.${k === 'min' ? cond.condition_type : k}`)}
onChange={e => set(k, e.target.value === '' ? null : Number(e.target.value))} />
)
const pair = (type, a, b) => (
<div className="grid grid-cols-2 gap-2">
<label className="grid gap-1 text-caption text-ink-2">{t('pricing.condition.from')}
<Input size="sm" type={type} value={p[a] ?? ''} onChange={e => set(a, e.target.value)} data-testid={`pricing-cond-${a}`} /></label>
<label className="grid gap-1 text-caption text-ink-2">{t('pricing.condition.to')}
<Input size="sm" type={type} value={p[b] ?? ''} onChange={e => set(b, e.target.value)} data-testid={`pricing-cond-${b}`} /></label>
</div>
)
switch (cond.condition_type) {
case 'time_range': return <>{pair('time', 'from', 'to')}<p className="text-caption text-ink-3">{t('pricing.condition.timeHint')}</p></>
case 'date_range': return pair('date', 'from', 'to')
case 'specific_date': return <DateList value={p.dates ?? []} onChange={v => set('dates', v)} />
case 'day_of_week': return <DayPicker value={p.days ?? []} onChange={v => set('days', v)} />
case 'min_item_quantity': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 1, 1)}{t('pricing.condition.ofTheDish')}</label>
case 'min_order_value': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 0, 0.5)}{t('pricing.condition.orderTotal')}</label>
case 'min_category_qty': return (
<div className="flex flex-wrap items-center gap-2">
{num('min', 1, 1)}
<span className="text-label text-ink-2">{t('pricing.condition.fromCategory')}</span>
<Select size="sm" className="flex-1 min-w-[10rem]" value={p.category_id ?? ''} aria-label={t('pricing.condition.fields.category_id')}
onChange={e => set('category_id', e.target.value === '' ? null : Number(e.target.value))}
placeholder={t('pricing.choose')} options={catalog.categories.map(c => ({ value: c.id, label: c.name }))} />
</div>
)
case 'order_channel': return <Chips options={SALES_POINTS.map(s => ({ value: s, label: tc(`salesPoints.${s}.name`) }))}
value={normalizeSalesPoints(p.channels)} onChange={v => set('channels', v)} />
case 'price_group_active': return (
<Select size="sm" value={p.price_group_id ?? ''} aria-label={t('pricing.condition.fields.price_group_id')}
onChange={e => set('price_group_id', e.target.value === '' ? null : Number(e.target.value))}
placeholder={catalog.groups.length ? t('pricing.choose') : t('pricing.condition.noGroups')}
options={catalog.groups.map(g => ({ value: g.id, label: g.name }))} />
)
default: return null
}
}
function DateList({ value, onChange }) {
const { t } = useTranslation('manager')
const { formatDate } = useFormat()
const [draft, setDraft] = useState('')
return (
<div className="grid gap-2">
<div className="flex gap-2">
<Input size="sm" type="date" value={draft} onChange={e => setDraft(e.target.value)} aria-label={t('pricing.condition.date')} />
<Button size="sm" variant="secondary" disabled={!draft || value.includes(draft)} onClick={() => { onChange([...value, draft].sort()); setDraft('') }}>{t('pricing.add')}</Button>
</div>
{value.length > 0 && <Chips options={value.map(d => ({ value: d, label: formatDate(d) }))} value={value} onChange={onChange} />}
</div>
)
}
/** A rule's, a deal's or a group's row: colour, name, badges, a summary, and its buttons. */
export function RuleCard({ colour, name, active, badges, summary, description, onToggle, onEdit, onDelete, onUp, onDown, testid, busy }) {
const { t } = useTranslation('manager')
return (
<li className={cx('flex items-center gap-3 p-3 rounded-card border bg-surface shadow-raised transition-opacity', active ? 'border-line' : 'border-line opacity-60')}
data-testid={testid} data-name={name} data-active={active ? 'true' : 'false'}>
<span className="w-1.5 self-stretch rounded-full shrink-0" style={{ background: colour }} aria-hidden="true" />
<div className="flex-1 min-w-0 grid gap-0.5">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-body font-semibold text-ink truncate">{name}</span>
<span className={cx('px-2 py-0.5 rounded-full text-caption font-medium', active ? 'bg-success-soft text-success-ink' : 'bg-surface-2 text-ink-2')}>
{active ? t('pricing.on') : t('pricing.off')}
</span>
{badges}
</div>
{description && <p className="text-label text-ink-2 truncate">{description}</p>}
{summary && <p className="text-caption text-ink-3">{summary}</p>}
</div>
<div className="flex items-center gap-0.5 shrink-0">
{onUp && <IconButton size="sm" variant="ghost" label={t('pricing.up')} onClick={onUp} disabled={busy}><ArrowUp size={16} /></IconButton>}
{onDown && <IconButton size="sm" variant="ghost" label={t('pricing.down')} onClick={onDown} disabled={busy}><ArrowDown size={16} /></IconButton>}
<IconButton size="sm" variant="ghost" label={active ? t('pricing.turnOff') : t('pricing.turnOn')} onClick={onToggle} disabled={busy} data-testid="pricing-toggle"><Power size={16} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('pricing.edit')} onClick={onEdit} data-testid="pricing-edit"><Pencil size={16} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('pricing.delete')} onClick={onDelete} data-testid="pricing-delete"><Trash2 size={16} /></IconButton>
</div>
</li>
)
}
/** The tab's head: what it is, and its "New" button. */
export function TabHead({ title, intro, action }) {
return (
<header className="flex flex-wrap items-start justify-between gap-3">
<div className="grid gap-1 max-w-3xl">
<h2 className="text-body-lg font-semibold text-ink">{title}</h2>
<p className="text-label text-ink-2">{intro}</p>
</div>
{action}
</header>
)
}
/** "Fill in: …" under a dialog when something is missing. */
export function Missing({ problems, prefix }) {
const { t } = useTranslation('manager')
if (!problems.length) return null
return <p className="p-3 rounded-control bg-warning-soft text-warning-ink text-label" role="note" data-testid="pricing-missing">
{t('pricing.missing', { list: problems.map(p => t(`${prefix}.${p}`)).join(', ') })}
</p>
}
@@ -0,0 +1,35 @@
// The pricing page's server calls (plan step 6.7). Backend: routers/pricing.py (/api/pricing),
// every change needs pricing.manage and sends the live event `pricing.changed`.
import client from '../../api/client'
const data = r => r.data
export const PRICING_EVENTS = ['pricing.changed']
export const listGroups = () => client.get('/api/pricing/groups').then(data)
export const saveGroup = (id, body) => (id ? client.put(`/api/pricing/groups/${id}`, body) : client.post('/api/pricing/groups', body)).then(data)
export const toggleGroup = id => client.patch(`/api/pricing/groups/${id}/toggle`).then(data)
export const deleteGroup = id => client.delete(`/api/pricing/groups/${id}`)
export const listModifiers = () => client.get('/api/pricing/modifiers').then(data)
export const saveModifier = (id, body) => (id ? client.put(`/api/pricing/modifiers/${id}`, body) : client.post('/api/pricing/modifiers', body)).then(data)
export const toggleModifier = id => client.patch(`/api/pricing/modifiers/${id}/toggle`).then(data)
export const deleteModifier = id => client.delete(`/api/pricing/modifiers/${id}`)
export const reorderModifiers = list => client.patch('/api/pricing/modifiers/reorder', { items: list.map((m, i) => ({ id: m.id, sort_order: i })) })
export const listDeals = () => client.get('/api/pricing/deals').then(data)
export const saveDeal = (id, body) => (id ? client.put(`/api/pricing/deals/${id}`, body) : client.post('/api/pricing/deals', body)).then(data)
export const toggleDeal = id => client.patch(`/api/pricing/deals/${id}/toggle`).then(data)
export const deleteDeal = id => client.delete(`/api/pricing/deals/${id}`)
export const venueLimits = () => client.get('/api/pricing/discount-settings/global').then(data)
export const saveVenueLimits = body => client.put('/api/pricing/discount-settings/global', body).then(data)
export const waiterLimits = id => client.get(`/api/pricing/discount-settings/${id}`).then(data)
export const saveWaiterLimits = (id, body) => client.put(`/api/pricing/discount-settings/${id}`, body).then(data)
export const listStaff = () => client.get('/api/waiters/').then(data)
// what the rules can point at
export const listProducts = () => client.get('/api/products/', { params: { all: true } }).then(data)
export const listCategories = () => client.get('/api/products/categories').then(data)
export const listPrepZones = () => client.get('/api/prep-zones').then(data)
export const listTags = () => client.get('/api/products/tags').then(data)
@@ -0,0 +1,234 @@
// The pricing page's rules as plain data (plan step 6.7): the forms of a price group, a price rule
// (modifier) and a deal, what they send to the server, what's missing before they can be saved,
// and their one-line summaries. Tested in tests/pricing-logic.test.mjs.
// The server's engine: local_backend/services/pricing.py (conditions AND-ed, targets OR-ed).
export const WEEKDAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0, as the server counts
// conditions a rule can have; the deals take fewer
export const MODIFIER_CONDITIONS = ['time_range', 'day_of_week', 'date_range', 'specific_date', 'price_group_active',
'order_channel', 'min_item_quantity', 'min_category_qty', 'min_order_value']
export const DEAL_CONDITIONS = ['min_item_quantity', 'min_order_value', 'time_range', 'day_of_week', 'date_range',
'order_channel', 'price_group_active']
export const OLD_PLACEHOLDERS = ['user_tier', 'low_stock'] // never did anything; shown, not offered
export const MODIFIER_TARGETS = ['all', 'item', 'category', 'prep_zone', 'tag']
export const DEAL_TARGETS = ['any', 'item', 'category', 'tag']
export const MODIFIER_ACTIONS = ['add_percent', 'add_amount', 'set']
export const DEAL_ACTIONS = ['free_item', 'free_choice', 'apply_modifier', 'set_price', 'add_amount', 'add_percent']
export const ROUNDINGS = ['', '0.05', '0.10', '0.20', '0.50', 'x.99', 'x.00']
export const FREE_CHOICE_FROM = ['item', 'category', 'tag']
/** A condition of a type with its starting values. */
export function blankCondition(type) {
switch (type) {
case 'time_range': return { condition_type: type, params: { from: '17:00', to: '19:00' } }
case 'date_range': return { condition_type: type, params: { from: '', to: '' } }
case 'specific_date': return { condition_type: type, params: { dates: [] } }
case 'day_of_week': return { condition_type: type, params: { days: [] } }
case 'min_item_quantity': return { condition_type: type, params: { min: 2 } }
case 'min_category_qty': return { condition_type: type, params: { category_id: null, min: 2 } }
case 'min_order_value': return { condition_type: type, params: { min: 20 } }
case 'order_channel': return { condition_type: type, params: { channels: [] } }
case 'price_group_active': return { condition_type: type, params: { price_group_id: null } }
default: return { condition_type: type, params: {} }
}
}
const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/
const DAY = /^\d{4}-\d{2}-\d{2}$/
const positive = (v, low) => typeof v === 'number' && Number.isFinite(v) && v >= low
/** Whether a condition is complete (the server refuses an incomplete one: pricing.bad_condition). */
export function conditionComplete({ condition_type: type, params: p = {} }) {
switch (type) {
case 'time_range': return HHMM.test(p.from ?? '') && HHMM.test(p.to ?? '') && p.from !== p.to
case 'date_range': return DAY.test(p.from ?? '') && DAY.test(p.to ?? '') && p.from <= p.to
case 'specific_date': return (p.dates ?? []).length > 0 && p.dates.every(d => DAY.test(d))
case 'day_of_week': return (p.days ?? []).length > 0
case 'min_item_quantity': return positive(p.min ?? 1, 1)
case 'min_category_qty': return Number.isInteger(p.category_id) && positive(p.min ?? 1, 1)
case 'min_order_value': return positive(p.min ?? 0, 0)
case 'order_channel': return (p.channels ?? []).length > 0
case 'price_group_active': return Number.isInteger(p.price_group_id)
default: return OLD_PLACEHOLDERS.includes(type)
}
}
export const toggleIn = (list, v) => (list.includes(v) ? list.filter(x => x !== v) : [...list, v])
/** Move an item of a list from one place to another (drag, or the arrows). */
export function moveItem(list, from, to) {
if (from === to || from < 0 || to < 0 || from >= list.length || to >= list.length) return list
const out = [...list]
const [x] = out.splice(from, 1)
out.splice(to, 0, x)
return out
}
// ── price groups ──────────────────────────────────────────────────────────────
export const blankGroup = colour => ({ name: '', description: '', color: colour, is_active: false,
auto_enable_time: '', auto_disable_time: '', auto_days: [] })
export const groupForm = (g, colour) => (g ? { ...blankGroup(colour), ...g, description: g.description ?? '',
auto_enable_time: g.auto_enable_time ?? '', auto_disable_time: g.auto_disable_time ?? '', auto_days: g.auto_days ?? [] } : blankGroup(colour))
/** A schedule is all three (from, to, a day) or nothing. */
export function groupProblems(f) {
const out = []
if (!f.name.trim()) out.push('name')
const parts = [f.auto_enable_time, f.auto_disable_time, f.auto_days.length ? 'x' : ''].filter(Boolean).length
if (parts && (parts < 3 || !HHMM.test(f.auto_enable_time) || !HHMM.test(f.auto_disable_time) || f.auto_enable_time === f.auto_disable_time)) out.push('schedule')
return out
}
export function groupBody(f) {
const scheduled = f.auto_enable_time && f.auto_disable_time && f.auto_days.length
return { name: f.name.trim(), description: f.description.trim() || null, color: f.color, is_active: !!f.is_active,
auto_enable_time: scheduled ? f.auto_enable_time : null, auto_disable_time: scheduled ? f.auto_disable_time : null,
auto_days: scheduled ? [...f.auto_days].sort() : null }
}
export const groupSchedule = g => (g.auto_enable_time && g.auto_disable_time && g.auto_days?.length
? { from: g.auto_enable_time, to: g.auto_disable_time, days: [...g.auto_days].sort() } : null)
// ── price rules (modifiers) ───────────────────────────────────────────────────
const ids = t => t.target_ids ?? (t.target_id != null ? [t.target_id] : [])
const tags = t => t.target_tags ?? (t.target_tag ? [t.target_tag] : [])
export const normalizeTarget = t => ({ target_type: t.target_type, target_ids: ids(t), target_tags: tags(t) })
export const blankModifier = colour => ({
name: '', description: '', color: colour, is_active: true, is_favorite: false, allow_stack: false, sort_order: 0,
scope: 'global', item_id: null, action_type: 'add_percent', action_value: -10, round_to: '',
conditions: [], targets: [{ target_type: 'all', target_ids: [], target_tags: [] }],
})
export const modifierForm = (m, colour) => (m ? {
...blankModifier(colour), ...m, description: m.description ?? '', round_to: m.round_to ?? '',
conditions: (m.conditions ?? []).map(c => ({ condition_type: c.condition_type, params: c.params ?? {} })),
targets: (m.targets ?? []).map(normalizeTarget),
} : blankModifier(colour))
const targetComplete = t => ['all', 'any'].includes(t.target_type) || (t.target_type === 'tag' ? t.target_tags.length > 0 : t.target_ids.length > 0)
export function modifierProblems(f) {
const out = []
if (!f.name.trim()) out.push('name')
if (f.scope === 'item' && !f.item_id) out.push('product')
if (f.scope === 'global' && (!f.targets.length || !f.targets.every(targetComplete))) out.push('targets')
if (!f.conditions.every(conditionComplete)) out.push('conditions')
if (!Number.isFinite(f.action_value) || (f.action_type === 'set' && f.action_value < 0)) out.push('value')
return out
}
export function modifierBody(f) {
return {
name: f.name.trim(), description: f.description.trim() || null, color: f.color, is_active: !!f.is_active,
is_favorite: !!f.is_favorite, allow_stack: !!f.allow_stack, sort_order: f.sort_order ?? 0,
scope: f.scope, item_id: f.scope === 'item' ? f.item_id : null,
action_type: f.action_type, action_value: f.action_value,
round_to: f.action_type === 'add_percent' && f.round_to ? f.round_to : null,
conditions: f.conditions.map(c => ({ condition_type: c.condition_type, params: c.params })),
targets: f.scope === 'global' ? f.targets.map(t => ({
target_type: t.target_type,
target_ids: t.target_type === 'tag' || t.target_type === 'all' ? null : t.target_ids,
target_id: t.target_type === 'tag' || t.target_type === 'all' ? null : t.target_ids[0] ?? null,
target_tags: t.target_type === 'tag' ? t.target_tags : null,
target_tag: t.target_type === 'tag' ? t.target_tags[0] ?? null : null,
})) : [],
}
}
/** "−10%", "+€0.50", "= €3.00" (money formatted by the caller's formatter). */
export function actionText(type, value, money) {
const v = Number(value ?? 0)
if (type === 'set' || type === 'set_price') return `= ${money(v)}`
const sign = v < 0 ? '−' : '+'
if (type === 'add_amount') return `${sign}${money(Math.abs(v))}`
return `${sign}${Math.abs(v)}%`
}
/** What a percentage or amount does to a price (the dialog's example), rounded like the server. */
export function examplePrice(base, type, value, roundTo) {
let p = type === 'set' ? value : type === 'add_amount' ? base + value : base * (1 + value / 100)
p = Math.max(p, 0)
if (type === 'add_percent' && roundTo) {
const step = { '0.05': 0.05, '0.10': 0.1, '0.20': 0.2, '0.50': 0.5 }[roundTo]
if (step) p = Math.round(p / step) * step
else if (roundTo === 'x.99') p = p >= 1 ? Math.floor(p) + 0.99 : p
else if (roundTo === 'x.00') p = Math.round(p)
}
return Math.round(Math.round(p / 0.1) * 0.1 * 100) / 100 // the system's final rounding to 0.10
}
// ── deals ─────────────────────────────────────────────────────────────────────
export const blankDeal = colour => ({
name: '', description: '', color: colour, is_active: true, sort_order: 0, action_type: 'free_item',
action_modifier_id: null, action_value: 0, action_free_item_id: null, action_free_target_type: 'item',
action_free_target_ids: [], action_free_quantity: 1,
conditions: [], targets: [{ target_type: 'any', target_ids: [], target_tags: [] }],
})
export const dealForm = (d, colour) => (d ? {
...blankDeal(colour), ...d, description: d.description ?? '', action_value: d.action_value ?? 0,
action_free_target_type: d.action_free_target_type ?? 'item', action_free_target_ids: d.action_free_target_ids ?? [],
conditions: (d.conditions ?? []).map(c => ({ condition_type: c.condition_type, params: c.params ?? {} })),
targets: (d.targets?.length ? d.targets : [{ target_type: 'any' }]).map(normalizeTarget),
} : blankDeal(colour))
export function dealProblems(f) {
const out = []
if (!f.name.trim()) out.push('name')
if (!f.targets.length || !f.targets.every(targetComplete)) out.push('targets')
if (!f.conditions.every(conditionComplete)) out.push('conditions')
const a = f.action_type
if (a === 'apply_modifier' && !f.action_modifier_id) out.push('modifier')
if (a === 'free_item' && !f.action_free_item_id) out.push('freeItem')
if (a === 'free_choice' && !f.action_free_target_ids.length) out.push('freeChoice')
if (['set_price', 'add_amount', 'add_percent'].includes(a) && !Number.isFinite(f.action_value)) out.push('value')
if (['free_item', 'free_choice'].includes(a) && !(f.action_free_quantity >= 1)) out.push('quantity')
return out
}
export function dealBody(f) {
const a = f.action_type
return {
name: f.name.trim(), description: f.description.trim() || null, color: f.color, is_active: !!f.is_active,
sort_order: f.sort_order ?? 0, action_type: a,
action_modifier_id: a === 'apply_modifier' ? f.action_modifier_id : null,
action_value: ['set_price', 'add_amount', 'add_percent'].includes(a) ? f.action_value : null,
action_free_item_id: a === 'free_item' ? f.action_free_item_id : null,
action_free_target_type: a === 'free_choice' ? f.action_free_target_type : null,
action_free_target_ids: a === 'free_choice' ? f.action_free_target_ids : null,
action_free_quantity: ['free_item', 'free_choice'].includes(a) ? f.action_free_quantity : 1,
conditions: f.conditions.map(c => ({ condition_type: c.condition_type, params: c.params })),
targets: f.targets.map(t => ({
target_type: t.target_type,
target_ids: ['item', 'category'].includes(t.target_type) ? t.target_ids : null,
target_id: ['item', 'category'].includes(t.target_type) ? t.target_ids[0] ?? null : null,
target_tags: t.target_type === 'tag' ? t.target_tags : null,
target_tag: t.target_type === 'tag' ? t.target_tags[0] ?? null : null,
})),
}
}
// ── discount limits ───────────────────────────────────────────────────────────
export const VENUE_LIMITS = ['max_total_value_workday', 'max_total_value_shift', 'max_items_per_shift']
export const WAITER_LIMITS = ['max_discount_percent', 'max_discount_amount', 'max_total_value_shift', 'max_total_value_workday',
'max_items_per_shift', 'max_items_per_workday', 'max_items_per_order']
export const COUNT_LIMITS = new Set(['max_items_per_shift', 'max_items_per_workday', 'max_items_per_order'])
/** A limit typed in a box: '' = no limit; a comma works as the decimal point. null when it isn't a number ≥ 0. */
export function parseLimit(text, count = false) {
const s = String(text ?? '').trim().replace(',', '.')
if (s === '') return { ok: true, value: null }
const v = Number(s)
if (!Number.isFinite(v) || v < 0 || (count && !Number.isInteger(v))) return { ok: false, value: null }
return { ok: true, value: v }
}
export const limitText = v => (v == null ? '' : String(v))
@@ -0,0 +1,26 @@
// What the pricing rules can point at (plan step 6.7), loaded once and kept current: products,
// categories (as a tree), prep zones, tags and price groups; and the colours a rule can have.
import { useMemo } from 'react'
import { useLiveQuery } from '../../live/useLiveQuery'
import { CATEGORY_COLOURS } from '../products/categoryColours'
import { categoryTree, treeLabel } from '../products/productsLogic'
import * as api from './pricingApi'
export const COLOURS = CATEGORY_COLOURS // the venue's colours (data, as the categories')
export function useCatalog() {
const products = useLiveQuery({ queryKey: ['products-all'], queryFn: api.listProducts, events: ['products_changed'], staleTime: 60_000 })
const categories = useLiveQuery({ queryKey: ['categories'], queryFn: api.listCategories, events: ['products_changed'], staleTime: 60_000 })
const zones = useLiveQuery({ queryKey: ['prep-zones'], queryFn: api.listPrepZones, staleTime: 60_000 })
const tags = useLiveQuery({ queryKey: ['product-tags'], queryFn: api.listTags, staleTime: 60_000 })
const groups = useLiveQuery({ queryKey: ['pricing', 'groups'], queryFn: api.listGroups, events: api.PRICING_EVENTS })
return useMemo(() => ({
products: (products.data ?? []).filter(p => p.lifecycle_status !== 'archived' && !p.is_service_item)
.sort((a, b) => a.name.localeCompare(b.name)).map(p => ({ id: p.id, name: p.name, price: p.base_price })),
categories: categoryTree(categories.data ?? []).map(({ cat, depth }) => ({ id: cat.id, name: treeLabel(cat, depth), plain: cat.name })),
zones: (zones.data ?? []).map(z => ({ id: z.id, name: z.name })),
tags: tags.data ?? [],
groups: groups.data ?? [],
}), [products.data, categories.data, zones.data, tags.data, groups.data])
}