Files
xenia-pos-local/manager_dashboard/src/pages/online/FeesPage.jsx
T
bonaminandClaude Opus 5.5 301502965c feat(manager): UI review pass 3 (fees tabs, products panes, floor editor, permissions search, pricing heads)
- Online orders → Settings: the fee tabs breathe (inset strip); a rule's buttons
  and switch centred together.
- Products: categories and list as panes that scroll on their own, headers and
  footers stay; the list sunken with white rows; the category search is the
  shared SearchInput. Product editor: "Make main" text instead of a star, the
  left tabs share the width.
- Floor editor: no "+" next to a corner; − / fit width / whole plan / +;
  "Edit the floor's shape" → "Save shape" (saves the shape and size at once);
  sizes in grid cells by half cells (steppers; typing snapped every keystroke
  before), resize handles on every unrotated table and thing, half-cell snapping.
- MediaField: the picture's name under the buttons, Remove red on hover.
- Staff permissions: a search box at the top.
- Prep zone name hint fixed. Offers & pricing: title first, then tabs; every tab
  has its head with the New button at the top right.
- Tests: floor cells, e2e (cell steppers, no + near a corner, Save shape,
  permission search, products panes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:51:17 +02:00

407 lines
23 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 settings: Online orders → Settings (2026-11-20; was its own page /online/fees).
// Online ordering (plan phase 3S, steps S.3–S.5): the ordering settings (OrderingSettings),
// delivery areas and fees, and the fee's line on the receipt (FeeProductCard). 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 { useSearchParams } from 'react-router-dom'
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, Tabs } from '@xenia/ui'
import client from '../../api/client'
import FeeProductCard from './FeeProductCard'
import OrderingLink from './OrderingLink'
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 [params, setParams] = useSearchParams()
const section = ['rules', 'areas', 'settings'].includes(params.get('fees')) ? params.get('fees') : 'rules'
const setSection = v => setParams(p => { const n = new URLSearchParams(p); n.set('fees', v); return n }, { replace: true })
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 <EmptyState title={error} />
if (!data) return <div className="py-10 flex justify-center"><Spinner /></div>
return (
<div className="grid gap-6" data-testid="fees-page">
{data.links?.order && <OrderingLink url={data.links.order} />}
<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>
{/* left: the fee rules, the areas and the fee's settings as tabs; right: test an order (2026-11-20) */}
<div className="grid gap-6 xl:grid-cols-[minmax(0,3fr)_minmax(19rem,1fr)] items-start">
<section className="rounded-card border border-line bg-surface shadow-raised min-w-0" data-testid="fees-sections">
<Tabs inset value={section} onChange={setSection}
tabs={[
{ id: 'rules', label: t('fees.rules'), badge: data.rules.length || null, testId: 'fees-tab-rules' },
{ id: 'areas', label: t('fees.areas'), badge: data.areas.length || null, testId: 'fees-tab-areas' },
{ id: 'settings', label: t('fees.settings'), testId: 'fees-tab-settings' },
]}
end={section === 'rules' ? <Button size="sm" icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'rule' })} data-testid="rule-add">{t('fees.addRule')}</Button>
: section === 'areas' ? <Button size="sm" icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'area' })} data-testid="area-add">{t('fees.addArea')}</Button>
: null} />
<div className="p-card">
{section === 'rules' && (data.rules.length === 0 ? (
<EmptyState icon={<Truck size={28} />} title={t('fees.noRules')} description={t('fees.noRulesBody')} />
) : (
<ol className="grid gap-3" 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 === 'areas' && (data.areas.length === 0 ? (
<EmptyState icon={<MapPin size={28} />} title={t('fees.noAreas')} />
) : (
<ul className="grid gap-3" data-testid="areas">
{data.areas.map(a => (
<li key={a.id} className="px-card py-card-y rounded-card border border-line bg-surface flex items-center gap-3" data-testid="area">
<MapPin size={16} className="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>
<span className="flex gap-1.5">
<IconButton size="sm" variant="ghost" tone="accent" label={t('fees.edit')} onClick={() => setDialog({ kind: 'area', item: a })}><Pencil size={16} /></IconButton>
<IconButton size="sm" variant="ghost" tone="danger" label={t('fees.delete')} onClick={() => setDialog({ kind: 'delete', what: 'area', item: a })}><Trash2 size={16} /></IconButton>
</span>
</li>
))}
</ul>
))}
{section === 'settings' && (data.fee_product
? <FeeProductCard key={JSON.stringify(data.fee_product)} product={data.fee_product} onSaved={load} />
: <EmptyState title={t('fees.noSettings')} />)}
</div>
</section>
<TestOrder areas={data.areas} />
</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={`px-card py-card-y rounded-card border border-line bg-surface grid gap-2 ${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>
<span className="flex items-center gap-1 shrink-0">
<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>
<IconButton size="sm" variant="ghost" tone="accent" label={t('fees.edit')} onClick={onEdit}><Pencil size={16} /></IconButton>
<IconButton size="sm" variant="ghost" tone="danger" label={t('fees.delete')} onClick={onDelete}><Trash2 size={16} /></IconButton>
<Switch className="ml-2" checked={rule.is_active} onChange={onToggle} aria-label={t('fees.active')} />
</span>
</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-card rounded-card border border-line bg-surface shadow-raised 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>
)
}