// 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
if (!data) return
return (

{t('ordering.pageTitle')}

{t('fees.title')}

{t('fees.intro')}

{t('fees.rules')}

{data.rules.length === 0 ? ( } title={t('fees.noRules')} description={t('fees.noRulesBody')} /> ) : (
    {data.rules.map((r, i) => ( 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 })} /> ))}
)}

{t('fees.areas')}

{data.areas.length === 0 ? (

{t('fees.noAreas')}

) : (
    {data.areas.map(a => (
  • ))}
)}
{dialog?.kind === 'area' && ( 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' && ( 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' && ( setDialog(null)} footer={<> }>

{t('fees.deleteBody')}

)}
) } 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 (
  • {n} {rule.name} onMove(-1)}> onMove(1)}>
    {t('fees.when')}{' '} {rule.sales_points.map(sp => tc(`salesPoints.${sp}.name`)).join(', ')} {d.when.map(([k, p]) => ` · ${t(`fees.cond.${k}`, params(p))}`).join('')} {t('fees.then')}{' '} {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')}` : ''}
  • ) } 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 ( }>
    setName(e.target.value)} maxLength={80} autoFocus data-testid="area-name" /> setCodes(e.target.value)} data-testid="area-postcodes" />
    ) } 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 ( }>
    set('name', e.target.value)} maxLength={80} autoFocus data-testid="rule-name" />
    {t('fees.what')}
    {form.action !== 'free' && ( set('value', e.target.value)} aria-label={t(`fees.valueLabel.${form.action}`)} placeholder={form.action === 'percent' ? '%' : '€'} data-testid="rule-value" /> )}

    {t(`fees.actionHint.${form.action}`)}

    {['value', 'negative', 'percent'].map(k => showProblem(k) &&

    {showProblem(k)}

    )}
    {t('fees.salesPoints')}
    {SALES_POINTS.filter(sp => sp !== 'in_store').map(sp => ( ))}
    {showProblem('salesPoints') &&

    {showProblem('salesPoints')}

    }
    {t('fees.conditions')}

    {t('fees.conditionsHint')}

    {areas.length > 0 && (
    {t('fees.onlyAreas')}
    {areas.map(a => ( ))}
    )}
    set('subtotal_min', e.target.value)} placeholder="€" data-testid="rule-subtotal-min" /> set('subtotal_max', e.target.value)} placeholder="€" /> set('items_min', e.target.value)} data-testid="rule-items-min" /> set('items_max', e.target.value)} />
    {t('fees.onlyDays')}
    {DAYS.map(d => ( ))}
    set('time_from', e.target.value)} /> set('time_to', e.target.value)} />
    set('stop', v)} label={t('fees.stop')} description={t('fees.stopHint')} /> set('is_active', v)} label={t('fees.active')} />
    ) } 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 (

    {t('fees.test')}

    {form.sales_point === 'online_delivery' && (
    {form.where === 'area' ? ( ) : ( set('postcode', e.target.value)} placeholder={t('fees.postcode')} aria-label={t('fees.postcode')} data-testid="test-postcode" /> )}
    )}
    set('subtotal', e.target.value)} data-testid="test-subtotal" /> set('items', e.target.value)} data-testid="test-items" /> {form.day !== 'now' && ( set('time', e.target.value)} /> )}
    {result && (
    {result.refused ? (

    {t(`fees.refused.${result.refused}`, { minimum: result.minimum != null ? formatMoney(result.minimum) : '' })}

    ) : ( <>

    {t('fees.testFee')} {formatMoney(result.fee)}

    {t('fees.testTotal', { total: formatMoney(result.total) })}

    )} {result.area_name &&

    {t('fees.testArea', { name: result.area_name })}

    }

    {result.applied.length ? t('fees.testApplied', { names: result.applied.map(a => a.name).join(' → ') }) : t('fees.testNone')}

    )}
    ) }