// 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
if (!data) return
return (
{data.links?.order &&
}
{t('fees.title')}
{t('fees.intro')}
{/* left: the fee rules, the areas and the fee's settings as tabs; right: test an order (2026-11-20) */}
} onClick={() => setDialog({ kind: 'rule' })} data-testid="rule-add">{t('fees.addRule')}
: section === 'areas' ? } onClick={() => setDialog({ kind: 'area' })} data-testid="area-add">{t('fees.addArea')}
: null} />
{section === '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 })} />
))}
))}
{section === 'areas' && (data.areas.length === 0 ? (
} title={t('fees.noAreas')} />
) : (
{data.areas.map(a => (
-
{a.name}
{a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}
setDialog({ kind: 'area', item: a })}>
setDialog({ kind: 'delete', what: 'area', item: a })}>
))}
))}
{section === 'settings' && (data.fee_product
?
:
)}
{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' && (
)}
)
}
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 (
)
}
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 (
)
}
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')}
)}
)
}