feat(manager): online ordering settings in tabs beside Test an order; expense lines and documents
- Online orders -> Settings: takeaway / delivery / any time side by side (wrapping, with room), the days of the week apart; fee rules, delivery areas and fee settings (the fee line) as tabs on the left, Test an order on the right; a rule's switch at the far right, equal padding, 'Order price from' / 'Total items count from' in the rule editor. - Expenses: the dialog lists what was bought (quantity, price before VAT, VAT; they make the total, with net / VAT / total) and keeps documents (attach a PDF or photo, open, remove; picked for a new expense, uploaded when it's saved); a paperclip in the list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,67 +1,197 @@
|
||||
// A new expense or an existing one (plan step 6.13a): what it is, its category, the supplier
|
||||
// (from the supplier book; a new one can be added from here), the amount (comma or dot), the date
|
||||
// it is due by and notes. The total can't be less than what was paid already.
|
||||
import { useState } from 'react'
|
||||
// 2026-11-20: what it bought, line by line (quantity, price before VAT, VAT %; the lines make the
|
||||
// total), and the documents kept with it (the invoice as a PDF, a photo of the receipt). Files
|
||||
// picked for a new expense are uploaded once it is saved.
|
||||
import { useRef, useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { FileText, Image as ImageIcon, Paperclip, Plus, Trash2 } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Field, Input, Select, Textarea } from '@xenia/ui'
|
||||
import { Button, Dialog, Dropdown, Field, IconButton, Input, Select, Textarea, cx } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import ContactDialog from './ContactDialog'
|
||||
import { CATEGORIES, expenseBody, expenseForm, expenseProblems } from './financeLogic'
|
||||
import { CATEGORIES, VAT_RATES, emptyLine, expenseBody, expenseForm, expenseProblems, lineMoney, linesTotal } from './financeLogic'
|
||||
|
||||
export default function ExpenseDialog({ expense, onClose, onSaved }) {
|
||||
const ACCEPT = 'application/pdf,image/jpeg,image/png,image/webp,image/heic,.heic'
|
||||
|
||||
export default function ExpenseDialog({ expense: initial, onClose, onSaved }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const fmt = useFormat()
|
||||
const qc = useQueryClient()
|
||||
const [expense, setExpense] = useState(initial) // documents change it in place
|
||||
const isNew = !expense
|
||||
const [form, setForm] = useState(() => expenseForm(expense, fmt.venueDateKey))
|
||||
const [form, setForm] = useState(() => expenseForm(initial, fmt.venueDateKey))
|
||||
const [tried, setTried] = useState(false)
|
||||
const [addContact, setAddContact] = useState(false)
|
||||
const [pending, setPending] = useState([]) // files picked for a new expense
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const fileInput = useRef(null)
|
||||
const { data: contacts = [] } = useLiveQuery({ queryKey: ['contacts'], queryFn: () => client.get('/api/contacts/').then(r => r.data), events: ['expenses.changed'] })
|
||||
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
|
||||
const setLine = (i, k, v) => setForm(f => ({ ...f, lines: f.lines.map((l, j) => (j === i ? { ...l, [k]: v } : l)) }))
|
||||
const paid = expense?.paid_amount ?? 0
|
||||
const wrong = expenseProblems(form, paid)
|
||||
const err = k => (tried && wrong.includes(k) ? t(`finance.exp.wrong.${k}`, { paid: fmt.formatMoney(paid) }) : undefined)
|
||||
const hasLines = form.lines.length > 0
|
||||
const sum = linesTotal(form.lines)
|
||||
|
||||
const upload = async (id, files) => {
|
||||
let last = null
|
||||
for (const f of files) {
|
||||
const body = new FormData()
|
||||
body.append('file', f)
|
||||
try { last = (await client.post(`/api/expenses/${id}/documents`, body)).data } catch (e) { toast.error(`${f.name}: ${errorMessage(e, t)}`) }
|
||||
}
|
||||
return last
|
||||
}
|
||||
const save = useMutation({
|
||||
mutationFn: body => (isNew ? client.post('/api/expenses/', body) : client.put(`/api/expenses/${expense.id}`, body)),
|
||||
onSuccess: () => { toast.success(t(isNew ? 'finance.exp.added' : 'finance.exp.saved', { what: form.description.trim() })); onSaved() },
|
||||
onSuccess: async r => {
|
||||
if (isNew && pending.length) await upload(r.data.id, pending)
|
||||
toast.success(t(isNew ? 'finance.exp.added' : 'finance.exp.saved', { what: form.description.trim() }))
|
||||
onSaved()
|
||||
},
|
||||
onError: e => toast.error(errorMessage(e, t)),
|
||||
})
|
||||
const submit = () => { setTried(true); if (!wrong.length) save.mutate(expenseBody(form)) }
|
||||
const pick = async files => {
|
||||
const list = [...files]
|
||||
if (!list.length) return
|
||||
if (isNew) { setPending(p => [...p, ...list]); return }
|
||||
setUploading(true)
|
||||
const next = await upload(expense.id, list)
|
||||
if (next) { setExpense(next); qc.invalidateQueries({ queryKey: ['expenses'] }) }
|
||||
setUploading(false)
|
||||
}
|
||||
const removeDoc = async doc => {
|
||||
try { setExpense((await client.delete(`/api/expenses/${expense.id}/documents/${doc.id}`)).data); qc.invalidateQueries({ queryKey: ['expenses'] }) } catch (e) { toast.error(errorMessage(e, t)) }
|
||||
}
|
||||
const openDoc = async doc => {
|
||||
// fetched with the session (the address alone isn't enough), shown in a new tab
|
||||
const tab = window.open('', '_blank')
|
||||
try {
|
||||
const blob = (await client.get(`/api/expenses/${expense.id}/documents/${doc.id}`, { responseType: 'blob' })).data
|
||||
const url = URL.createObjectURL(blob)
|
||||
if (tab) tab.location.href = url
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000)
|
||||
} catch (e) { tab?.close(); toast.error(errorMessage(e, t)) }
|
||||
}
|
||||
// A supplier no longer in the book still shows on its expense
|
||||
const options = [{ value: '', label: t('finance.exp.noSupplier') },
|
||||
...contacts.map(c => ({ value: String(c.id), label: c.name })),
|
||||
...(expense?.contact_id && !contacts.some(c => c.id === expense.contact_id) ? [{ value: String(expense.contact_id), label: expense.contact_name ?? '' }] : [])]
|
||||
const docs = [...(expense?.documents ?? []).map(d => ({ ...d, saved: true })), ...pending.map((f, i) => ({ id: `p${i}`, filename: f.name, content_type: f.type, size: f.size, file: f }))]
|
||||
|
||||
return (
|
||||
<Dialog open size="lg" onClose={onClose} title={isNew ? t('finance.exp.newTitle') : expense.description}
|
||||
<Dialog open size="xl" onClose={onClose} title={isNew ? t('finance.exp.newTitle') : expense.description}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
|
||||
<Button loading={save.isPending} onClick={submit} data-testid="expense-save">{isNew ? t('finance.exp.add') : t('finance.save')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-3" data-testid="expense-dialog">
|
||||
<div className="grid gap-5" data-testid="expense-dialog">
|
||||
<Field label={t('finance.exp.what')} required error={err('description')}>
|
||||
<Input value={form.description} autoFocus onChange={e => set('description', e.target.value)} placeholder={t('finance.exp.whatHint')} data-testid="expense-description" />
|
||||
</Field>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Field label={t('finance.exp.category')}>
|
||||
<Select value={form.category} onChange={e => set('category', e.target.value)} data-testid="expense-category"
|
||||
options={CATEGORIES.map(c => ({ value: c, label: t(`finance.categories.${c}`) }))} />
|
||||
</Field>
|
||||
<Field label={t('finance.exp.amount')} required error={err('total_amount') ?? err('below_paid')}>
|
||||
<Input inputMode="decimal" value={form.total_amount} onChange={e => set('total_amount', e.target.value)} placeholder="0,00" data-testid="expense-amount" />
|
||||
</Field>
|
||||
<Field label={t('finance.exp.supplier')} hint={<button type="button" className="text-accent-ink hover:underline" onClick={() => setAddContact(true)}>{t('finance.exp.newSupplier')}</button>}>
|
||||
<Select value={form.contact_id} onChange={e => set('contact_id', e.target.value)} data-testid="expense-supplier" options={options} />
|
||||
</Field>
|
||||
<Field label={t('finance.exp.dueBy')} hint={t('finance.exp.dueByHint')}>
|
||||
<Input type="date" value={form.due_date} onChange={e => set('due_date', e.target.value)} data-testid="expense-due-date" />
|
||||
</Field>
|
||||
<Field label={t('finance.exp.amount')} required hint={hasLines ? t('finance.exp.amountFromLines') : undefined} error={err('total_amount') ?? err('below_paid')}>
|
||||
{hasLines
|
||||
? <Input value={fmt.formatMoney(sum.total)} readOnly tabIndex={-1} data-testid="expense-amount" />
|
||||
: <Input inputMode="decimal" value={form.total_amount} onChange={e => set('total_amount', e.target.value)} placeholder="0,00" data-testid="expense-amount" />}
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
{/* what it bought */}
|
||||
<section className="grid gap-2" data-testid="expense-lines">
|
||||
<div className="flex items-center gap-3">
|
||||
<h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.lines')}</h3>
|
||||
<span className="flex-1 border-t border-line" aria-hidden="true" />
|
||||
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => set('lines', [...form.lines, emptyLine()])} data-testid="expense-line-add">{t('finance.exp.addLine')}</Button>
|
||||
</div>
|
||||
{!hasLines ? <p className="text-label text-ink-3">{t('finance.exp.noLines')}</p> : (
|
||||
<div className="rounded-card border border-line overflow-x-auto">
|
||||
<table className="w-full text-label">
|
||||
<thead className="bg-surface-2 text-ink-3">
|
||||
<tr className="text-overline font-semibold uppercase tracking-wide">
|
||||
<th className="px-3 py-2 text-left">{t('finance.exp.lineWhat')}</th>
|
||||
<th className="px-2 py-2 text-right w-24">{t('finance.exp.lineQty')}</th>
|
||||
<th className="px-2 py-2 text-right w-32">{t('finance.exp.linePrice')}</th>
|
||||
<th className="px-2 py-2 text-right w-28">{t('finance.exp.lineVat')}</th>
|
||||
<th className="px-3 py-2 text-right w-28">{t('finance.exp.lineTotal')}</th>
|
||||
<th className="w-12" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{form.lines.map((l, i) => {
|
||||
const m = lineMoney(l)
|
||||
const bad = tried && wrong.includes(`line.${i}`)
|
||||
return (
|
||||
<tr key={i} className={cx('align-middle', bad && 'bg-danger-soft')} data-testid="expense-line">
|
||||
<td className="px-2 py-1.5"><Input size="sm" value={l.description} onChange={e => setLine(i, 'description', e.target.value)} aria-label={t('finance.exp.lineWhat')} data-testid="expense-line-what" /></td>
|
||||
<td className="px-1 py-1.5"><Input size="sm" inputMode="decimal" className="text-right" value={l.quantity} onChange={e => setLine(i, 'quantity', e.target.value)} aria-label={t('finance.exp.lineQty')} data-testid="expense-line-qty" /></td>
|
||||
<td className="px-1 py-1.5"><Input size="sm" inputMode="decimal" className="text-right" value={l.unit_price} placeholder="0,00" onChange={e => setLine(i, 'unit_price', e.target.value)} aria-label={t('finance.exp.linePrice')} data-testid="expense-line-price" /></td>
|
||||
<td className="px-1 py-1.5">
|
||||
<Dropdown size="sm" value={l.vat_rate} onChange={v => setLine(i, 'vat_rate', v)} aria-label={t('finance.exp.lineVat')} data-testid="expense-line-vat"
|
||||
options={[...new Set([...VAT_RATES.map(String), l.vat_rate])].map(v => ({ value: v, label: `${v} %` }))} />
|
||||
</td>
|
||||
<td className="px-3 py-1.5 text-right tabular-nums font-medium text-ink">{fmt.formatMoney(m.total)}</td>
|
||||
<td className="px-1 py-1.5 text-right">
|
||||
<IconButton size="sm" variant="ghost" tone="danger" label={t('finance.exp.removeLine')} onClick={() => set('lines', form.lines.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot className="bg-surface-2 text-ink-2">
|
||||
<tr><td colSpan={4} className="px-3 py-1.5 text-right">{t('finance.exp.net')}</td><td className="px-3 py-1.5 text-right tabular-nums">{fmt.formatMoney(sum.net)}</td><td /></tr>
|
||||
<tr><td colSpan={4} className="px-3 py-1.5 text-right">{t('finance.exp.vat')}</td><td className="px-3 py-1.5 text-right tabular-nums">{fmt.formatMoney(sum.vat)}</td><td /></tr>
|
||||
<tr className="text-ink font-semibold"><td colSpan={4} className="px-3 py-2 text-right">{t('finance.exp.total')}</td><td className="px-3 py-2 text-right tabular-nums" data-testid="expense-lines-total">{fmt.formatMoney(sum.total)}</td><td /></tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* the invoice / receipt */}
|
||||
<section className="grid gap-2" data-testid="expense-documents">
|
||||
<div className="flex items-center gap-3">
|
||||
<h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.documents')}</h3>
|
||||
<span className="flex-1 border-t border-line" aria-hidden="true" />
|
||||
<Button size="sm" variant="secondary" icon={<Paperclip size={14} />} loading={uploading} onClick={() => fileInput.current?.click()} data-testid="expense-doc-add">{t('finance.exp.addDocument')}</Button>
|
||||
<input ref={fileInput} type="file" accept={ACCEPT} multiple hidden onChange={e => { pick(e.target.files); e.target.value = '' }} data-testid="expense-doc-input" />
|
||||
</div>
|
||||
{docs.length === 0 ? <p className="text-label text-ink-3">{t('finance.exp.noDocuments')}</p> : (
|
||||
<ul className="grid gap-2 sm:grid-cols-2">
|
||||
{docs.map(d => (
|
||||
<li key={d.id} className="flex items-center gap-3 px-3 py-2 rounded-card border border-line bg-surface" data-testid="expense-doc">
|
||||
{d.content_type === 'application/pdf' ? <FileText size={18} className="text-danger-ink shrink-0" aria-hidden="true" /> : <ImageIcon size={18} className="text-info-ink shrink-0" aria-hidden="true" />}
|
||||
<span className="flex-1 min-w-0 grid">
|
||||
{d.saved
|
||||
? <button type="button" className="text-left text-label font-medium text-accent-ink hover:underline truncate" onClick={() => openDoc(d)}>{d.filename}</button>
|
||||
: <span className="text-label font-medium text-ink truncate">{d.filename}</span>}
|
||||
<span className="text-caption text-ink-3">{d.saved ? `${fmt.formatDateTime(d.uploaded_at, 'datetimeShort')} · ` : `${t('finance.exp.uploadOnSave')} · `}{Math.max(1, Math.round(d.size / 1024))} KB</span>
|
||||
</span>
|
||||
<IconButton size="sm" variant="ghost" tone="danger" label={t('finance.exp.removeDocument', { name: d.filename })}
|
||||
onClick={() => (d.saved ? removeDoc(d) : setPending(p => p.filter(f => f !== d.file)))}><Trash2 size={14} /></IconButton>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<Field label={t('finance.notes')}>
|
||||
<Textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} />
|
||||
</Field>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { Banknote, Pencil, Plus, Receipt, Trash2 } from 'lucide-react'
|
||||
import { Banknote, Pencil, Plus, Receipt, Trash2, Paperclip } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Dropdown, EmptyState, IconButton, Page, PageHeader, SearchInput, Spinner, Toolbar } from '@xenia/ui'
|
||||
@@ -44,7 +44,8 @@ export default function ExpensesPage() {
|
||||
const columns = [
|
||||
{ key: 'description', label: t('finance.exp.what'), render: e => (
|
||||
<span className="grid">
|
||||
<span className="font-semibold text-ink">{e.description}</span>
|
||||
<span className="font-semibold text-ink flex items-center gap-1.5">{e.description}
|
||||
{e.documents?.length > 0 && <Paperclip size={13} className="text-ink-3" aria-label={t('finance.exp.documents')} />}</span>
|
||||
{e.contact_name && <span className="text-caption text-ink-2">{e.contact_name}</span>}
|
||||
</span>) },
|
||||
{ key: 'category', label: t('finance.exp.category'), sort: e => cat(e.category), render: e => cat(e.category) },
|
||||
|
||||
@@ -22,25 +22,60 @@ export function expenseForm(e, dateKey = d => d) {
|
||||
description: e?.description ?? '', category: e?.category ?? 'supplier',
|
||||
contact_id: e?.contact_id ? String(e.contact_id) : '', total_amount: e ? String(e.total_amount) : '',
|
||||
due_date: e?.due_date ? dateKey(e.due_date) : '', notes: e?.notes ?? '',
|
||||
lines: (e?.lines ?? []).map(l => ({ description: l.description, quantity: String(l.quantity), unit_price: String(l.unit_price), vat_rate: String(l.vat_rate) })),
|
||||
}
|
||||
}
|
||||
|
||||
/** Which fields are wrong: description, total_amount (none, zero, or less than what was paid). */
|
||||
// ── An expense's lines (2026-11-20): what it bought; the lines make its total ──
|
||||
|
||||
/** Greek VAT rates offered for a line (another one can be typed). */
|
||||
export const VAT_RATES = [24, 13, 6, 0]
|
||||
|
||||
/** An empty line (VAT 24 %, the usual rate). */
|
||||
export const emptyLine = () => ({ description: '', quantity: '1', unit_price: '', vat_rate: '24' })
|
||||
|
||||
const qty = text => parseNumber(String(text ?? ''), { decimals: 3, allowNegative: false })
|
||||
const halfUp = v => Math.round((v + Number.EPSILON) * 100) / 100
|
||||
|
||||
/** A line's money as the backend counts it (routers/expenses.py): net = quantity × price before
|
||||
* VAT, VAT = net × rate (each rounded half up to the cent), total = net + VAT. */
|
||||
export function lineMoney(line) {
|
||||
const net = halfUp((qty(line.quantity) || 0) * (money(line.unit_price) || 0))
|
||||
const vat = halfUp(net * (qty(line.vat_rate) || 0) / 100)
|
||||
return { net, vat, total: halfUp(net + vat) }
|
||||
}
|
||||
|
||||
/** The lines added up: { net, vat, total }. */
|
||||
export function linesTotal(lines = []) {
|
||||
return lines.map(lineMoney).reduce((a, m) => ({ net: halfUp(a.net + m.net), vat: halfUp(a.vat + m.vat), total: halfUp(a.total + m.total) }),
|
||||
{ net: 0, vat: 0, total: 0 })
|
||||
}
|
||||
|
||||
/** Which fields are wrong: description, total_amount (none, zero, or less than what was paid);
|
||||
* with lines: line.<i> (no description, no quantity, no price) and the total is the lines'. */
|
||||
export function expenseProblems(form, paid = 0) {
|
||||
const out = []
|
||||
if (!form.description.trim()) out.push('description')
|
||||
const total = money(form.total_amount)
|
||||
const lines = form.lines ?? []
|
||||
lines.forEach((l, i) => {
|
||||
if (!l.description.trim() || !(qty(l.quantity) > 0) || money(l.unit_price) == null) out.push(`line.${i}`)
|
||||
})
|
||||
const total = lines.length ? linesTotal(lines).total : money(form.total_amount)
|
||||
if (!(total > 0)) out.push('total_amount')
|
||||
else if (cents(total) < cents(paid)) out.push('below_paid')
|
||||
return out
|
||||
}
|
||||
|
||||
/** What the API takes. `due_date` is the venue date picked ('' clears it). */
|
||||
/** What the API takes. `due_date` is the venue date picked ('' clears it). With lines, the
|
||||
* backend makes the total from them; `lines: []` removes them (the typed total counts). */
|
||||
export function expenseBody(form) {
|
||||
const lines = (form.lines ?? []).map(l => ({ description: l.description.trim(), quantity: qty(l.quantity),
|
||||
unit_price: money(l.unit_price), vat_rate: qty(l.vat_rate) || 0 }))
|
||||
return {
|
||||
description: form.description.trim(), category: form.category,
|
||||
contact_id: form.contact_id ? Number(form.contact_id) : null,
|
||||
total_amount: money(form.total_amount),
|
||||
total_amount: lines.length ? null : money(form.total_amount),
|
||||
lines,
|
||||
due_date: form.due_date || null, notes: form.notes.trim() || null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ export default function FeeProductCard({ product, onSaved }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="p-4 rounded-card border border-line bg-surface grid gap-3" aria-labelledby="fee-product-h" data-testid="fee-product">
|
||||
<section className="grid gap-3 max-w-2xl" aria-labelledby="fee-product-h" data-testid="fee-product">
|
||||
<div className="grid gap-1">
|
||||
<h2 id="fee-product-h" className="text-title font-semibold text-ink">{t('feeProduct.title')}</h2>
|
||||
<p className="text-label text-ink-2">{t('feeProduct.intro')}</p>
|
||||
|
||||
@@ -7,12 +7,13 @@
|
||||
// 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 } from '@xenia/ui'
|
||||
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'
|
||||
@@ -27,6 +28,9 @@ export default function FeesPage() {
|
||||
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 {
|
||||
@@ -65,54 +69,57 @@ export default function FeesPage() {
|
||||
<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>
|
||||
{/* 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 className="px-card" 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')} />
|
||||
) : (
|
||||
<ul className="grid gap-2" data-testid="areas">
|
||||
<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="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" />
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<TestOrder areas={data.areas} />
|
||||
{data.fee_product && <FeeProductCard key={JSON.stringify(data.fee_product)} product={data.fee_product} onSaved={load} />}
|
||||
</div>
|
||||
))}
|
||||
{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' && (
|
||||
@@ -149,15 +156,15 @@ function RuleRow({ rule, n, areaNames, first, last, onMove, onToggle, onEdit, on
|
||||
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}>
|
||||
<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>
|
||||
<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>
|
||||
<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')} />
|
||||
</div>
|
||||
<div className="pl-7 text-label text-ink-2 grid gap-0.5">
|
||||
<span>
|
||||
@@ -330,7 +337,7 @@ function TestOrder({ areas }) {
|
||||
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">
|
||||
<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)}>
|
||||
|
||||
@@ -33,20 +33,22 @@ export default function OrderingSettings({ ordering, onSaved }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="p-4 rounded-card border border-line bg-surface grid gap-4" aria-labelledby="ordering-h" data-testid="ordering-settings">
|
||||
<section className="p-card rounded-card border border-line bg-surface grid gap-4" aria-labelledby="ordering-h" data-testid="ordering-settings">
|
||||
<div className="grid gap-1">
|
||||
<h2 id="ordering-h" className="text-title font-semibold text-ink">{t('ordering.title')}</h2>
|
||||
<p className="text-label text-ink-2">{t('ordering.intro')}</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{/* takeaway, delivery and "any time" side by side, each at least 16rem, wrapping when they don't fit */}
|
||||
<div className="grid gap-x-10 gap-y-4 grid-cols-[repeat(auto-fit,minmax(16rem,1fr))]">
|
||||
{['takeaway', 'delivery'].map(s => (
|
||||
<Switch key={s} checked={form.services.includes(s)} onChange={() => toggleService(s)}
|
||||
label={t(`ordering.service.${s}`)} description={t(`ordering.serviceHint.${s}`)} data-testid={`ordering-${s}`} />
|
||||
))}
|
||||
<Switch checked={form.anyTime} onChange={v => set('anyTime', v)} label={t('ordering.anyTime')} description={t('ordering.anyTimeHint')} />
|
||||
</div>
|
||||
|
||||
<Hours anyTime={form.anyTime} days={form.days} onAnyTime={v => set('anyTime', v)} onDays={d => set('days', d)} testId="ordering-hours" />
|
||||
<Hours anyTime={form.anyTime} days={form.days} onAnyTime={v => set('anyTime', v)} onDays={d => set('days', d)} testId="ordering-hours" noSwitch />
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<Field label={t('ordering.prep')} hint={t('ordering.prepHint')}>
|
||||
@@ -106,16 +108,16 @@ export default function OrderingSettings({ ordering, onSaved }) {
|
||||
}
|
||||
|
||||
/** Hours per day (several ranges, past midnight), or any time. */
|
||||
function Hours({ anyTime, days, onAnyTime, onDays, anyLabel, anyHint, testId }) {
|
||||
function Hours({ anyTime, days, onAnyTime, onDays, anyLabel, anyHint, testId, noSwitch = false }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const setDay = (d, ranges) => onDays(days.map((r, i) => (i === d ? ranges : r)))
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<Switch checked={anyTime} onChange={onAnyTime} label={anyLabel ?? t('ordering.anyTime')} description={anyHint ?? t('ordering.anyTimeHint')} />
|
||||
{!noSwitch && <Switch checked={anyTime} onChange={onAnyTime} label={anyLabel ?? t('ordering.anyTime')} description={anyHint ?? t('ordering.anyTimeHint')} />}
|
||||
{!anyTime && (
|
||||
<ul className="grid gap-1.5" data-testid={testId}>
|
||||
<ul className="grid divide-y divide-line rounded-card border border-line" data-testid={testId}>
|
||||
{DAYS.map(d => (
|
||||
<li key={d} className="grid grid-cols-[6rem_1fr] gap-2 items-start">
|
||||
<li key={d} className="grid grid-cols-[7rem_1fr] gap-3 items-start px-card py-3">
|
||||
<span className="text-body text-ink pt-2">{t(`fees.dayLong.${d}`)}</span>
|
||||
<div className="grid gap-1.5">
|
||||
{days[d].length === 0 && <span className="text-label text-ink-3 pt-2">{t('ordering.closedDay')}</span>}
|
||||
|
||||
Reference in New Issue
Block a user