Files
xenia-pos-local/manager_dashboard/src/pages/online/FeesPage.jsx
T
bonaminandClaude Opus 5.5 8ea44d71aa feat: online ordering settings (services, hours, preparation, slots) and the order app e2e (platform-v2 3S, S.4)
- connect_orders.ordering setting; GET/PUT /api/connect/fees/ordering (validated:
  services, hours per day incl. past midnight, preparation, slot minutes, days ahead,
  ASAP); pushed to the cloud with the menu (snapshot `ordering`).
- Manager: the Online ordering page gains "Services and hours" (OrderingSettings.jsx; logic
  in feesLogic.js, unit-tested); nav label "Online ordering".
- tests/e2e/order_app.mjs: a real cloud + the built order app in a phone-sized browser:
  takeaway and delivery placed, priced by the cloud (fee by area, minimum refused), the
  site moves the delivery to delivered and the page follows; a rejection with its reason;
  Greek. In run-all, with the order app's unit tests.
- Tests: backend +1 (406), manager unit +1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:39:13 +02:00

395 lines
22 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Online ordering (plan phase 3S, steps S.3–S.4): the ordering settings (OrderingSettings),
// delivery areas and fees. Backend: /api/connect/fees
// (connect_orders.fees). The venue lists the areas it delivers to and the fee rules, looked
// at from the top: a rule whose conditions hold changes the fee (set, add, % of the
// products, free) or refuses the order below a minimum; "stop here" makes the first match
// win. The cloud applies the same rules at checkout (the same engine), so "Test an order"
// shows exactly what a customer will be charged. No rules = no fee.
import { useCallback, useEffect, useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp, MapPin, Pencil, Plus, Trash2, Truck } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { SALES_POINTS } from '@xenia/access'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui'
import client from '../../api/client'
import OrderingSettings from './OrderingSettings'
import { ACTIONS, DAYS, describeRule, emptyRule, moveRule, parsePostcodes, previewBody, ruleBody, ruleProblems, ruleToForm } from './feesLogic'
const chip = on => `px-3 min-h-[var(--x-control-sm)] rounded-full text-label font-medium transition-colors duration-fast
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
export default function FeesPage() {
const { t } = useTranslation('manager')
const [data, setData] = useState(null)
const [error, setError] = useState(null)
const [dialog, setDialog] = useState(null) // { kind: 'area' | 'rule', item? } | { kind: 'delete', what, item }
const load = useCallback(async () => {
try {
setData((await client.get('/api/connect/fees')).data)
setError(null)
} catch (err) { setError(errorMessage(err, t)) }
}, [t])
useEffect(() => { load() }, [load])
const areaNames = useMemo(() => Object.fromEntries((data?.areas ?? []).map(a => [a.id, a.name])), [data])
const act = async (fn, done) => {
try {
await fn()
if (done) toast.success(done)
await load()
return true
} catch (err) {
toast.error(errorMessage(err, t))
return false
}
}
if (error) return <div className="p-6"><EmptyState title={error} /></div>
if (!data) return <div className="p-6 flex justify-center"><Spinner /></div>
return (
<div className="p-4 md:p-6 grid gap-6 max-w-6xl" data-testid="fees-page">
<header className="grid gap-1">
<h1 className="text-heading font-semibold text-ink">{t('ordering.pageTitle')}</h1>
</header>
<OrderingSettings key={JSON.stringify(data.ordering)} ordering={data.ordering} />
<div className="grid gap-1">
<h2 className="text-title font-semibold text-ink">{t('fees.title')}</h2>
<p className="text-body text-ink-2 max-w-3xl">{t('fees.intro')}</p>
</div>
<div className="grid gap-6 lg:grid-cols-[1fr_22rem] items-start">
<section className="grid gap-3" aria-labelledby="fee-rules">
<div className="flex items-center gap-2">
<h2 id="fee-rules" className="flex-1 text-title font-semibold text-ink">{t('fees.rules')}</h2>
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'rule' })} data-testid="rule-add">{t('fees.addRule')}</Button>
</div>
{data.rules.length === 0 ? (
<EmptyState icon={<Truck size={28} />} title={t('fees.noRules')} description={t('fees.noRulesBody')} />
) : (
<ol className="grid gap-2" data-testid="rules">
{data.rules.map((r, i) => (
<RuleRow key={r.id} rule={r} n={i + 1} areaNames={areaNames} first={i === 0} last={i === data.rules.length - 1}
onMove={step => act(() => client.put('/api/connect/fees/rules/order', moveRule(data.rules, r.id, step)))}
onToggle={on => act(() => client.put(`/api/connect/fees/rules/${r.id}`, { ...ruleBody(ruleToForm(r)), is_active: on }))}
onEdit={() => setDialog({ kind: 'rule', item: r })}
onDelete={() => setDialog({ kind: 'delete', what: 'rule', item: r })} />
))}
</ol>
)}
</section>
<div className="grid gap-6">
<section className="grid gap-3" aria-labelledby="fee-areas">
<div className="flex items-center gap-2">
<h2 id="fee-areas" className="flex-1 text-title font-semibold text-ink">{t('fees.areas')}</h2>
<Button variant="secondary" icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'area' })} data-testid="area-add">{t('fees.addArea')}</Button>
</div>
{data.areas.length === 0 ? (
<p className="text-label text-ink-2">{t('fees.noAreas')}</p>
) : (
<ul className="grid gap-2" data-testid="areas">
{data.areas.map(a => (
<li key={a.id} className="p-3 rounded-card border border-line bg-surface flex items-start gap-2" data-testid="area">
<MapPin size={16} className="mt-0.5 text-ink-3 shrink-0" aria-hidden="true" />
<span className="flex-1 min-w-0">
<span className={`block text-body font-medium ${a.is_active ? 'text-ink' : 'text-ink-3 line-through'}`}>{a.name}</span>
<span className="block text-caption text-ink-2 truncate">{a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}</span>
</span>
<IconButton size="sm" variant="ghost" label={t('fees.edit')} onClick={() => setDialog({ kind: 'area', item: a })}><Pencil size={16} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('fees.delete')} onClick={() => setDialog({ kind: 'delete', what: 'area', item: a })}><Trash2 size={16} /></IconButton>
</li>
))}
</ul>
)}
</section>
<TestOrder areas={data.areas} />
</div>
</div>
{dialog?.kind === 'area' && (
<AreaDialog area={dialog.item} onClose={() => setDialog(null)}
onSave={body => act(() => (dialog.item ? client.put(`/api/connect/fees/areas/${dialog.item.id}`, body) : client.post('/api/connect/fees/areas', body)),
t('fees.saved')).then(ok => ok && setDialog(null))} />
)}
{dialog?.kind === 'rule' && (
<RuleDialog rule={dialog.item} areas={data.areas} onClose={() => setDialog(null)}
onSave={body => act(() => (dialog.item ? client.put(`/api/connect/fees/rules/${dialog.item.id}`, body) : client.post('/api/connect/fees/rules', body)),
t('fees.saved')).then(ok => ok && setDialog(null))} />
)}
{dialog?.kind === 'delete' && (
<Dialog open size="sm" title={t(`fees.delete${dialog.what === 'area' ? 'Area' : 'Rule'}`, { name: dialog.item.name })} onClose={() => setDialog(null)}
footer={<>
<Button variant="secondary" onClick={() => setDialog(null)}>{t('fees.cancel')}</Button>
<Button variant="danger" icon={<Trash2 size={16} />} data-testid="confirm-delete"
onClick={() => act(() => client.delete(`/api/connect/fees/${dialog.what}s/${dialog.item.id}`), t('fees.deleted')).then(() => setDialog(null))}>
{t('fees.delete')}
</Button>
</>}>
<p className="text-body text-ink-2">{t('fees.deleteBody')}</p>
</Dialog>
)}
</div>
)
}
function RuleRow({ rule, n, areaNames, first, last, onMove, onToggle, onEdit, onDelete }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const { formatMoney } = useFormat()
const d = describeRule(rule, areaNames)
const params = p => ({ ...p, min: p.min, max: p.max, minMoney: p.min != null ? formatMoney(p.min) : '', maxMoney: p.max != null ? formatMoney(p.max) : '',
days: (p.days ?? []).map(x => t(`fees.dayShort.${x}`)).join(', ') })
return (
<li className={`p-3 rounded-card border border-line bg-surface grid gap-1.5 ${rule.is_active ? '' : 'opacity-60'}`} data-testid="rule" data-rule={rule.id}>
<div className="flex items-center gap-2">
<span className="text-caption font-semibold text-ink-3 w-5">{n}</span>
<span className="flex-1 min-w-0 text-body font-semibold text-ink truncate">{rule.name}</span>
<IconButton size="sm" variant="ghost" label={t('fees.up')} disabled={first} onClick={() => onMove(-1)}><ArrowUp size={16} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('fees.down')} disabled={last} onClick={() => onMove(1)}><ArrowDown size={16} /></IconButton>
<Switch checked={rule.is_active} onChange={onToggle} aria-label={t('fees.active')} />
<IconButton size="sm" variant="ghost" label={t('fees.edit')} onClick={onEdit}><Pencil size={16} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('fees.delete')} onClick={onDelete}><Trash2 size={16} /></IconButton>
</div>
<div className="pl-7 text-label text-ink-2 grid gap-0.5">
<span>
<span className="font-medium text-ink">{t('fees.when')}</span>{' '}
{rule.sales_points.map(sp => tc(`salesPoints.${sp}.name`)).join(', ')}
{d.when.map(([k, p]) => ` · ${t(`fees.cond.${k}`, params(p))}`).join('')}
</span>
<span>
<span className="font-medium text-ink">{t('fees.then')}</span>{' '}
{t(`fees.do.${d.action[0]}`, { value: d.action[0] === 'percent' ? d.action[1].value : formatMoney(d.action[1].value) })}
{rule.stop ? ` · ${t('fees.stopShort')}` : ''}
</span>
</div>
</li>
)
}
function AreaDialog({ area, onClose, onSave }) {
const { t } = useTranslation('manager')
const [name, setName] = useState(area?.name ?? '')
const [codes, setCodes] = useState((area?.postcodes ?? []).join(', '))
const [active, setActive] = useState(area?.is_active ?? true)
const [busy, setBusy] = useState(false)
const save = async () => { setBusy(true); await onSave({ name: name.trim(), postcodes: parsePostcodes(codes), is_active: active }); setBusy(false) }
return (
<Dialog open size="sm" title={area ? t('fees.editArea') : t('fees.addArea')} onClose={busy ? undefined : onClose}
footer={<>
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('fees.cancel')}</Button>
<Button onClick={save} loading={busy} disabled={!name.trim()} data-testid="area-save">{t('fees.save')}</Button>
</>}>
<div className="grid gap-3">
<Field label={t('fees.areaName')} hint={t('fees.areaNameHint')} required>
<Input value={name} onChange={e => setName(e.target.value)} maxLength={80} autoFocus data-testid="area-name" />
</Field>
<Field label={t('fees.postcodes')} hint={t('fees.postcodesHint')}>
<Input value={codes} onChange={e => setCodes(e.target.value)} data-testid="area-postcodes" />
</Field>
<Switch checked={active} onChange={setActive} label={t('fees.areaActive')} />
</div>
</Dialog>
)
}
function RuleDialog({ rule, areas, onClose, onSave }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const [form, setForm] = useState(() => (rule ? ruleToForm(rule) : emptyRule()))
const [busy, setBusy] = useState(false)
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const toggle = (k, v) => setForm(f => ({ ...f, [k]: f[k].includes(v) ? f[k].filter(x => x !== v) : [...f[k], v] }))
const problems = ruleProblems(form)
const save = async () => {
setTried(true)
if (problems.length) return
setBusy(true)
await onSave(ruleBody(form))
setBusy(false)
}
const showProblem = k => (tried && problems.includes(k) ? t(`fees.problem.${k}`) : undefined)
return (
<Dialog open size="lg" title={rule ? t('fees.editRule') : t('fees.addRule')} onClose={busy ? undefined : onClose}
footer={<>
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('fees.cancel')}</Button>
<Button onClick={save} loading={busy} data-testid="rule-save">{t('fees.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="rule-dialog">
<Field label={t('fees.ruleName')} hint={t('fees.ruleNameHint')} error={showProblem('name')} required>
<Input value={form.name} onChange={e => set('name', e.target.value)} maxLength={80} autoFocus data-testid="rule-name" />
</Field>
<fieldset className="grid gap-2">
<legend className="text-label font-semibold text-ink mb-1">{t('fees.what')}</legend>
<div className="grid gap-2 sm:grid-cols-[1fr_10rem]">
<Select value={form.action} onChange={e => set('action', e.target.value)} aria-label={t('fees.what')} data-testid="rule-action">
{ACTIONS.map(a => <option key={a} value={a}>{t(`fees.action.${a}`)}</option>)}
</Select>
{form.action !== 'free' && (
<Input inputMode="decimal" value={form.value} onChange={e => set('value', e.target.value)} aria-label={t(`fees.valueLabel.${form.action}`)}
placeholder={form.action === 'percent' ? '%' : '€'} data-testid="rule-value" />
)}
</div>
<p className="text-caption text-ink-2">{t(`fees.actionHint.${form.action}`)}</p>
{['value', 'negative', 'percent'].map(k => showProblem(k) && <p key={k} role="alert" className="text-label text-danger-ink">{showProblem(k)}</p>)}
</fieldset>
<fieldset className="grid gap-2">
<legend className="text-label font-semibold text-ink mb-1">{t('fees.salesPoints')}</legend>
<div className="flex flex-wrap gap-1.5">
{SALES_POINTS.filter(sp => sp !== 'in_store').map(sp => (
<button key={sp} type="button" className={chip(form.sales_points.includes(sp))} aria-pressed={form.sales_points.includes(sp)}
onClick={() => toggle('sales_points', sp)} data-testid={`rule-sp-${sp}`}>{tc(`salesPoints.${sp}.name`)}</button>
))}
</div>
{showProblem('salesPoints') && <p role="alert" className="text-label text-danger-ink">{showProblem('salesPoints')}</p>}
</fieldset>
<fieldset className="grid gap-3">
<legend className="text-label font-semibold text-ink mb-1">{t('fees.conditions')}</legend>
<p className="text-caption text-ink-2 -mt-1">{t('fees.conditionsHint')}</p>
{areas.length > 0 && (
<div className="grid gap-1.5">
<span className="text-label text-ink-2">{t('fees.onlyAreas')}</span>
<div className="flex flex-wrap gap-1.5">
{areas.map(a => (
<button key={a.id} type="button" className={chip(form.area_ids.includes(a.id))} aria-pressed={form.area_ids.includes(a.id)}
onClick={() => toggle('area_ids', a.id)} data-testid={`rule-area-${a.id}`}>{a.name}</button>
))}
</div>
</div>
)}
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('fees.subtotalMin')} error={showProblem('subtotalRange')}>
<Input inputMode="decimal" value={form.subtotal_min} onChange={e => set('subtotal_min', e.target.value)} placeholder="€" data-testid="rule-subtotal-min" />
</Field>
<Field label={t('fees.subtotalMax')}>
<Input inputMode="decimal" value={form.subtotal_max} onChange={e => set('subtotal_max', e.target.value)} placeholder="€" />
</Field>
<Field label={t('fees.itemsMin')} error={showProblem('itemsRange')}>
<Input inputMode="numeric" value={form.items_min} onChange={e => set('items_min', e.target.value)} data-testid="rule-items-min" />
</Field>
<Field label={t('fees.itemsMax')}>
<Input inputMode="numeric" value={form.items_max} onChange={e => set('items_max', e.target.value)} />
</Field>
</div>
<div className="grid gap-1.5">
<span className="text-label text-ink-2">{t('fees.onlyDays')}</span>
<div className="flex flex-wrap gap-1.5">
{DAYS.map(d => (
<button key={d} type="button" className={chip(form.days.includes(d))} aria-pressed={form.days.includes(d)}
onClick={() => toggle('days', d)}>{t(`fees.dayShort.${d}`)}</button>
))}
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('fees.timeFrom')} error={showProblem('times')}>
<Input type="time" value={form.time_from} onChange={e => set('time_from', e.target.value)} />
</Field>
<Field label={t('fees.timeTo')} hint={t('fees.timeHint')}>
<Input type="time" value={form.time_to} onChange={e => set('time_to', e.target.value)} />
</Field>
</div>
</fieldset>
<Switch checked={form.stop} onChange={v => set('stop', v)} label={t('fees.stop')} description={t('fees.stopHint')} />
<Switch checked={form.is_active} onChange={v => set('is_active', v)} label={t('fees.active')} />
</div>
</Dialog>
)
}
function TestOrder({ areas }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const { formatMoney } = useFormat()
// where / area_id stay null until picked: they follow the areas as they're added or removed
const [picked, setForm] = useState({ sales_point: 'online_delivery', where: null, area_id: null,
postcode: '', subtotal: '15', items: '2', day: 'now', time: '' })
const form = {
...picked,
where: picked.where ?? (areas.length ? 'area' : 'postcode'),
area_id: picked.area_id ?? (areas.some(a => a.id === Number(picked.area_id)) ? picked.area_id : (areas[0]?.id ?? '')),
}
const [result, setResult] = useState(null)
const [busy, setBusy] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const run = async () => {
setBusy(true)
try { setResult((await client.post('/api/connect/fees/preview', previewBody(form))).data) } catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
return (
<section className="p-4 rounded-card border border-line bg-surface-2 grid gap-3" aria-labelledby="fee-test" data-testid="fee-test">
<h2 id="fee-test" className="text-title font-semibold text-ink">{t('fees.test')}</h2>
<Field label={t('fees.testSalesPoint')}>
<Select value={form.sales_point} onChange={e => set('sales_point', e.target.value)}>
{SALES_POINTS.filter(sp => sp !== 'in_store').map(sp => <option key={sp} value={sp}>{tc(`salesPoints.${sp}.name`)}</option>)}
</Select>
</Field>
{form.sales_point === 'online_delivery' && (
<div className="grid gap-2">
<Select value={form.where} onChange={e => set('where', e.target.value)} aria-label={t('fees.testWhere')}>
<option value="area">{t('fees.testByArea')}</option>
<option value="postcode">{t('fees.testByPostcode')}</option>
</Select>
{form.where === 'area' ? (
<Select value={form.area_id} onChange={e => set('area_id', e.target.value)} aria-label={t('fees.areas')} data-testid="test-area">
<option value="">{t('fees.testNoArea')}</option>
{areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
</Select>
) : (
<Input value={form.postcode} onChange={e => set('postcode', e.target.value)} placeholder={t('fees.postcode')} aria-label={t('fees.postcode')} data-testid="test-postcode" />
)}
</div>
)}
<div className="grid grid-cols-2 gap-2">
<Field label={t('fees.testSubtotal')}>
<Input inputMode="decimal" value={form.subtotal} onChange={e => set('subtotal', e.target.value)} data-testid="test-subtotal" />
</Field>
<Field label={t('fees.testItems')}>
<Input inputMode="numeric" value={form.items} onChange={e => set('items', e.target.value)} data-testid="test-items" />
</Field>
<Field label={t('fees.testDay')}>
<Select value={form.day} onChange={e => set('day', e.target.value)}>
<option value="now">{t('fees.now')}</option>
{DAYS.map(d => <option key={d} value={String(d)}>{t(`fees.dayLong.${d}`)}</option>)}
</Select>
</Field>
{form.day !== 'now' && (
<Field label={t('fees.testTime')}>
<Input type="time" value={form.time} onChange={e => set('time', e.target.value)} />
</Field>
)}
</div>
<Button onClick={run} loading={busy} data-testid="test-run">{t('fees.testRun')}</Button>
{result && (
<div className="p-3 rounded-control bg-surface border border-line grid gap-1" role="status" data-testid="test-result"
data-fee={result.fee} data-refused={result.refused ?? ''}>
{result.refused ? (
<p className="text-body font-semibold text-danger-ink">
{t(`fees.refused.${result.refused}`, { minimum: result.minimum != null ? formatMoney(result.minimum) : '' })}
</p>
) : (
<>
<p className="text-body text-ink">{t('fees.testFee')} <span className="font-semibold">{formatMoney(result.fee)}</span></p>
<p className="text-label text-ink-2">{t('fees.testTotal', { total: formatMoney(result.total) })}</p>
</>
)}
{result.area_name && <p className="text-caption text-ink-2">{t('fees.testArea', { name: result.area_name })}</p>}
<p className="text-caption text-ink-2">
{result.applied.length ? t('fees.testApplied', { names: result.applied.map(a => a.name).join(' → ') }) : t('fees.testNone')}
</p>
</div>
)}
</section>
)
}