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
|
// 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
|
// (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.
|
// 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 { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import toast from 'react-hot-toast'
|
import toast from 'react-hot-toast'
|
||||||
|
import { FileText, Image as ImageIcon, Paperclip, Plus, Trash2 } from 'lucide-react'
|
||||||
import { errorMessage } from '@xenia/api'
|
import { errorMessage } from '@xenia/api'
|
||||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
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 client from '../../api/client'
|
||||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||||
import ContactDialog from './ContactDialog'
|
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 { t } = useTranslation('manager')
|
||||||
const fmt = useFormat()
|
const fmt = useFormat()
|
||||||
const qc = useQueryClient()
|
const qc = useQueryClient()
|
||||||
|
const [expense, setExpense] = useState(initial) // documents change it in place
|
||||||
const isNew = !expense
|
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 [tried, setTried] = useState(false)
|
||||||
const [addContact, setAddContact] = 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 { 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 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 paid = expense?.paid_amount ?? 0
|
||||||
const wrong = expenseProblems(form, paid)
|
const wrong = expenseProblems(form, paid)
|
||||||
const err = k => (tried && wrong.includes(k) ? t(`finance.exp.wrong.${k}`, { paid: fmt.formatMoney(paid) }) : undefined)
|
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({
|
const save = useMutation({
|
||||||
mutationFn: body => (isNew ? client.post('/api/expenses/', body) : client.put(`/api/expenses/${expense.id}`, body)),
|
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)),
|
onError: e => toast.error(errorMessage(e, t)),
|
||||||
})
|
})
|
||||||
const submit = () => { setTried(true); if (!wrong.length) save.mutate(expenseBody(form)) }
|
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
|
// A supplier no longer in the book still shows on its expense
|
||||||
const options = [{ value: '', label: t('finance.exp.noSupplier') },
|
const options = [{ value: '', label: t('finance.exp.noSupplier') },
|
||||||
...contacts.map(c => ({ value: String(c.id), label: c.name })),
|
...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 ?? '' }] : [])]
|
...(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 (
|
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={<>
|
footer={<>
|
||||||
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
|
<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>
|
<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')}>
|
<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" />
|
<Input value={form.description} autoFocus onChange={e => set('description', e.target.value)} placeholder={t('finance.exp.whatHint')} data-testid="expense-description" />
|
||||||
</Field>
|
</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')}>
|
<Field label={t('finance.exp.category')}>
|
||||||
<Select value={form.category} onChange={e => set('category', e.target.value)} data-testid="expense-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}`) }))} />
|
options={CATEGORIES.map(c => ({ value: c, label: t(`finance.categories.${c}`) }))} />
|
||||||
</Field>
|
</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>}>
|
<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} />
|
<Select value={form.contact_id} onChange={e => set('contact_id', e.target.value)} data-testid="expense-supplier" options={options} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label={t('finance.exp.dueBy')} hint={t('finance.exp.dueByHint')}>
|
<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" />
|
<Input type="date" value={form.due_date} onChange={e => set('due_date', e.target.value)} data-testid="expense-due-date" />
|
||||||
</Field>
|
</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>
|
</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')}>
|
<Field label={t('finance.notes')}>
|
||||||
<Textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} />
|
<Textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} />
|
||||||
</Field>
|
</Field>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useMutation } from '@tanstack/react-query'
|
import { useMutation } from '@tanstack/react-query'
|
||||||
import toast from 'react-hot-toast'
|
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 { errorMessage } from '@xenia/api'
|
||||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||||
import { Button, Dialog, Dropdown, EmptyState, IconButton, Page, PageHeader, SearchInput, Spinner, Toolbar } from '@xenia/ui'
|
import { Button, Dialog, Dropdown, EmptyState, IconButton, Page, PageHeader, SearchInput, Spinner, Toolbar } from '@xenia/ui'
|
||||||
@@ -44,7 +44,8 @@ export default function ExpensesPage() {
|
|||||||
const columns = [
|
const columns = [
|
||||||
{ key: 'description', label: t('finance.exp.what'), render: e => (
|
{ key: 'description', label: t('finance.exp.what'), render: e => (
|
||||||
<span className="grid">
|
<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>}
|
{e.contact_name && <span className="text-caption text-ink-2">{e.contact_name}</span>}
|
||||||
</span>) },
|
</span>) },
|
||||||
{ key: 'category', label: t('finance.exp.category'), sort: e => cat(e.category), render: e => cat(e.category) },
|
{ 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',
|
description: e?.description ?? '', category: e?.category ?? 'supplier',
|
||||||
contact_id: e?.contact_id ? String(e.contact_id) : '', total_amount: e ? String(e.total_amount) : '',
|
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 ?? '',
|
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) {
|
export function expenseProblems(form, paid = 0) {
|
||||||
const out = []
|
const out = []
|
||||||
if (!form.description.trim()) out.push('description')
|
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')
|
if (!(total > 0)) out.push('total_amount')
|
||||||
else if (cents(total) < cents(paid)) out.push('below_paid')
|
else if (cents(total) < cents(paid)) out.push('below_paid')
|
||||||
return out
|
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) {
|
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 {
|
return {
|
||||||
description: form.description.trim(), category: form.category,
|
description: form.description.trim(), category: form.category,
|
||||||
contact_id: form.contact_id ? Number(form.contact_id) : null,
|
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,
|
due_date: form.due_date || null, notes: form.notes.trim() || null,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export default function FeeProductCard({ product, onSaved }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
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">
|
<div className="grid gap-1">
|
||||||
<h2 id="fee-product-h" className="text-title font-semibold text-ink">{t('feeProduct.title')}</h2>
|
<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>
|
<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"
|
// 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.
|
// shows exactly what a customer will be charged. No rules = no fee.
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { useSearchParams } from 'react-router-dom'
|
||||||
import toast from 'react-hot-toast'
|
import toast from 'react-hot-toast'
|
||||||
import { ArrowDown, ArrowUp, MapPin, Pencil, Plus, Trash2, Truck } from 'lucide-react'
|
import { ArrowDown, ArrowUp, MapPin, Pencil, Plus, Trash2, Truck } from 'lucide-react'
|
||||||
import { errorMessage } from '@xenia/api'
|
import { errorMessage } from '@xenia/api'
|
||||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||||
import { SALES_POINTS } from '@xenia/access'
|
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 client from '../../api/client'
|
||||||
import FeeProductCard from './FeeProductCard'
|
import FeeProductCard from './FeeProductCard'
|
||||||
import OrderingLink from './OrderingLink'
|
import OrderingLink from './OrderingLink'
|
||||||
@@ -27,6 +28,9 @@ export default function FeesPage() {
|
|||||||
const [data, setData] = useState(null)
|
const [data, setData] = useState(null)
|
||||||
const [error, setError] = useState(null)
|
const [error, setError] = useState(null)
|
||||||
const [dialog, setDialog] = useState(null) // { kind: 'area' | 'rule', item? } | { kind: 'delete', what, item }
|
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 () => {
|
const load = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
@@ -65,16 +69,23 @@ export default function FeesPage() {
|
|||||||
<p className="text-body text-ink-2 max-w-3xl">{t('fees.intro')}</p>
|
<p className="text-body text-ink-2 max-w-3xl">{t('fees.intro')}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-6 lg:grid-cols-[1fr_22rem] items-start">
|
{/* left: the fee rules, the areas and the fee's settings as tabs; right: test an order (2026-11-20) */}
|
||||||
<section className="grid gap-3" aria-labelledby="fee-rules">
|
<div className="grid gap-6 xl:grid-cols-[minmax(0,3fr)_minmax(19rem,1fr)] items-start">
|
||||||
<div className="flex items-center gap-2">
|
<section className="rounded-card border border-line bg-surface shadow-raised min-w-0" data-testid="fees-sections">
|
||||||
<h2 id="fee-rules" className="flex-1 text-title font-semibold text-ink">{t('fees.rules')}</h2>
|
<Tabs className="px-card" value={section} onChange={setSection}
|
||||||
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'rule' })} data-testid="rule-add">{t('fees.addRule')}</Button>
|
tabs={[
|
||||||
</div>
|
{ id: 'rules', label: t('fees.rules'), badge: data.rules.length || null, testId: 'fees-tab-rules' },
|
||||||
{data.rules.length === 0 ? (
|
{ 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')} />
|
<EmptyState icon={<Truck size={28} />} title={t('fees.noRules')} description={t('fees.noRulesBody')} />
|
||||||
) : (
|
) : (
|
||||||
<ol className="grid gap-2" data-testid="rules">
|
<ol className="grid gap-3" data-testid="rules">
|
||||||
{data.rules.map((r, i) => (
|
{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}
|
<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)))}
|
onMove={step => act(() => client.put('/api/connect/fees/rules/order', moveRule(data.rules, r.id, step)))}
|
||||||
@@ -83,36 +94,32 @@ export default function FeesPage() {
|
|||||||
onDelete={() => setDialog({ kind: 'delete', what: 'rule', item: r })} />
|
onDelete={() => setDialog({ kind: 'delete', what: 'rule', item: r })} />
|
||||||
))}
|
))}
|
||||||
</ol>
|
</ol>
|
||||||
)}
|
))}
|
||||||
</section>
|
{section === 'areas' && (data.areas.length === 0 ? (
|
||||||
|
<EmptyState icon={<MapPin size={28} />} title={t('fees.noAreas')} />
|
||||||
<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">
|
<ul className="grid gap-3" data-testid="areas">
|
||||||
{data.areas.map(a => (
|
{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">
|
<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="mt-0.5 text-ink-3 shrink-0" aria-hidden="true" />
|
<MapPin size={16} className="text-ink-3 shrink-0" aria-hidden="true" />
|
||||||
<span className="flex-1 min-w-0">
|
<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-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 className="block text-caption text-ink-2 truncate">{a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}</span>
|
||||||
</span>
|
</span>
|
||||||
<IconButton size="sm" variant="ghost" label={t('fees.edit')} onClick={() => setDialog({ kind: 'area', item: a })}><Pencil size={16} /></IconButton>
|
<span className="flex gap-1.5">
|
||||||
<IconButton size="sm" variant="ghost" label={t('fees.delete')} onClick={() => setDialog({ kind: 'delete', what: 'area', item: a })}><Trash2 size={16} /></IconButton>
|
<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>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</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>
|
</section>
|
||||||
<TestOrder areas={data.areas} />
|
<TestOrder areas={data.areas} />
|
||||||
{data.fee_product && <FeeProductCard key={JSON.stringify(data.fee_product)} product={data.fee_product} onSaved={load} />}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{dialog?.kind === 'area' && (
|
{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) : '',
|
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(', ') })
|
days: (p.days ?? []).map(x => t(`fees.dayShort.${x}`)).join(', ') })
|
||||||
return (
|
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">
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-caption font-semibold text-ink-3 w-5">{n}</span>
|
<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-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.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" 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" tone="accent" label={t('fees.edit')} onClick={onEdit}><Pencil size={16} /></IconButton>
|
||||||
<IconButton size="sm" variant="ghost" 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>
|
||||||
<IconButton size="sm" variant="ghost" 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>
|
||||||
<div className="pl-7 text-label text-ink-2 grid gap-0.5">
|
<div className="pl-7 text-label text-ink-2 grid gap-0.5">
|
||||||
<span>
|
<span>
|
||||||
@@ -330,7 +337,7 @@ function TestOrder({ areas }) {
|
|||||||
setBusy(false)
|
setBusy(false)
|
||||||
}
|
}
|
||||||
return (
|
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>
|
<h2 id="fee-test" className="text-title font-semibold text-ink">{t('fees.test')}</h2>
|
||||||
<Field label={t('fees.testSalesPoint')}>
|
<Field label={t('fees.testSalesPoint')}>
|
||||||
<Select value={form.sales_point} onChange={e => set('sales_point', e.target.value)}>
|
<Select value={form.sales_point} onChange={e => set('sales_point', e.target.value)}>
|
||||||
|
|||||||
@@ -33,20 +33,22 @@ export default function OrderingSettings({ ordering, onSaved }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
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">
|
<div className="grid gap-1">
|
||||||
<h2 id="ordering-h" className="text-title font-semibold text-ink">{t('ordering.title')}</h2>
|
<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>
|
<p className="text-label text-ink-2">{t('ordering.intro')}</p>
|
||||||
</div>
|
</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 => (
|
{['takeaway', 'delivery'].map(s => (
|
||||||
<Switch key={s} checked={form.services.includes(s)} onChange={() => toggleService(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}`} />
|
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>
|
</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">
|
<div className="grid gap-3 sm:grid-cols-3">
|
||||||
<Field label={t('ordering.prep')} hint={t('ordering.prepHint')}>
|
<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. */
|
/** 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 { t } = useTranslation('manager')
|
||||||
const setDay = (d, ranges) => onDays(days.map((r, i) => (i === d ? ranges : r)))
|
const setDay = (d, ranges) => onDays(days.map((r, i) => (i === d ? ranges : r)))
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-2">
|
<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 && (
|
{!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 => (
|
{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>
|
<span className="text-body text-ink pt-2">{t(`fees.dayLong.${d}`)}</span>
|
||||||
<div className="grid gap-1.5">
|
<div className="grid gap-1.5">
|
||||||
{days[d].length === 0 && <span className="text-label text-ink-3 pt-2">{t('ordering.closedDay')}</span>}
|
{days[d].length === 0 && <span className="text-label text-ink-3 pt-2">{t('ordering.closedDay')}</span>}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { test } from 'node:test'
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import {
|
import {
|
||||||
contactBody, contactForm, contactProblems, daysBetween, expenseBody, expenseForm, expenseProblems, expenseTotals,
|
contactBody, contactForm, contactProblems, daysBetween, expenseBody, expenseForm, expenseProblems, expenseTotals,
|
||||||
filterContacts, filterExpenses, filterTabs, isLate, owedByContact, paymentAmount, tabActions, tabTotals,
|
filterContacts, filterExpenses, filterTabs, isLate, lineMoney, linesTotal, owedByContact, paymentAmount, tabActions, tabTotals,
|
||||||
} from '../src/pages/finance/financeLogic.js'
|
} from '../src/pages/finance/financeLogic.js'
|
||||||
|
|
||||||
const key = iso => iso.slice(0, 10)
|
const key = iso => iso.slice(0, 10)
|
||||||
@@ -21,7 +21,7 @@ test('an expense form: typed amounts with a comma, the due date as a venue date,
|
|||||||
assert.deepEqual(expenseProblems({ ...f, description: ' ', total_amount: '0' }), ['description', 'total_amount'])
|
assert.deepEqual(expenseProblems({ ...f, description: ' ', total_amount: '0' }), ['description', 'total_amount'])
|
||||||
assert.deepEqual(expenseProblems({ ...f, total_amount: '60' }, 70), ['below_paid'])
|
assert.deepEqual(expenseProblems({ ...f, total_amount: '60' }, 70), ['below_paid'])
|
||||||
assert.deepEqual(expenseBody({ ...f, total_amount: '120,50', contact_id: '', due_date: '', notes: ' ' }),
|
assert.deepEqual(expenseBody({ ...f, total_amount: '120,50', contact_id: '', due_date: '', notes: ' ' }),
|
||||||
{ description: 'Γάλα Νοεμβρίου', category: 'supplier', contact_id: null, total_amount: 120.5, due_date: null, notes: null })
|
{ description: 'Γάλα Νοεμβρίου', category: 'supplier', contact_id: null, total_amount: 120.5, lines: [], due_date: null, notes: null })
|
||||||
assert.equal(expenseForm(null).category, 'supplier')
|
assert.equal(expenseForm(null).category, 'supplier')
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -68,3 +68,18 @@ test('tabs: what can be done, days open, search and what is owed', () => {
|
|||||||
assert.equal(filterTabs(tabs, 'big').length, 1)
|
assert.equal(filterTabs(tabs, 'big').length, 1)
|
||||||
assert.deepEqual(tabTotals(tabs), { owed: 15.5, count: 2 })
|
assert.deepEqual(tabTotals(tabs), { owed: 15.5, count: 2 })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test('the lines of an expense make its total, VAT rounded half up as on an invoice', () => {
|
||||||
|
const lines = [{ description: 'Tomatoes', quantity: '3', unit_price: '2,50', vat_rate: '13' }, { description: 'Bags', quantity: '1', unit_price: '10', vat_rate: '24' }]
|
||||||
|
assert.deepEqual(lineMoney(lines[0]), { net: 7.5, vat: 0.98, total: 8.48 })
|
||||||
|
assert.deepEqual(linesTotal(lines), { net: 17.5, vat: 3.38, total: 20.88 })
|
||||||
|
const f = { ...expenseForm(null), description: 'Market', lines }
|
||||||
|
assert.deepEqual(expenseProblems(f), [])
|
||||||
|
const body = expenseBody(f)
|
||||||
|
assert.equal(body.total_amount, null)
|
||||||
|
assert.deepEqual(body.lines[0], { description: 'Tomatoes', quantity: 3, unit_price: 2.5, vat_rate: 13 })
|
||||||
|
// a line without a description, and lines below what was paid
|
||||||
|
assert.deepEqual(expenseProblems({ ...f, lines: [{ ...lines[0], description: ' ' }] }), ['line.0'])
|
||||||
|
assert.deepEqual(expenseProblems(f, 30), ['below_paid'])
|
||||||
|
})
|
||||||
|
|||||||
@@ -777,6 +777,8 @@
|
|||||||
"fees": {
|
"fees": {
|
||||||
"title": "Περιοχές και χρεώσεις διανομής",
|
"title": "Περιοχές και χρεώσεις διανομής",
|
||||||
"intro": "Χρεώσεις για online παραγγελίες, από πάνω προς τα κάτω: κάθε κανόνας του οποίου οι συνθήκες ισχύουν αλλάζει τη χρέωση ή απορρίπτει την παραγγελία κάτω από ένα ελάχιστο. Ο πελάτης βλέπει τη χρέωση πριν παραγγείλει, και το online ταμείο χρεώνει ακριβώς ό,τι δείχνει η «Δοκιμή παραγγελίας». Χωρίς κανόνες δεν υπάρχει χρέωση.",
|
"intro": "Χρεώσεις για online παραγγελίες, από πάνω προς τα κάτω: κάθε κανόνας του οποίου οι συνθήκες ισχύουν αλλάζει τη χρέωση ή απορρίπτει την παραγγελία κάτω από ένα ελάχιστο. Ο πελάτης βλέπει τη χρέωση πριν παραγγείλει, και το online ταμείο χρεώνει ακριβώς ό,τι δείχνει η «Δοκιμή παραγγελίας». Χωρίς κανόνες δεν υπάρχει χρέωση.",
|
||||||
|
"settings": "Ρυθμίσεις χρέωσης",
|
||||||
|
"noSettings": "Η γραμμή της χρέωσης αποστολής δεν έχει ρυθμιστεί.",
|
||||||
"rules": "Κανόνες χρέωσης",
|
"rules": "Κανόνες χρέωσης",
|
||||||
"addRule": "Νέος κανόνας",
|
"addRule": "Νέος κανόνας",
|
||||||
"editRule": "Επεξεργασία κανόνα",
|
"editRule": "Επεξεργασία κανόνα",
|
||||||
@@ -810,9 +812,9 @@
|
|||||||
"stopShort": "σταματά εδώ",
|
"stopShort": "σταματά εδώ",
|
||||||
"cond": {
|
"cond": {
|
||||||
"areas": "περιοχή {{names}}",
|
"areas": "περιοχή {{names}}",
|
||||||
"subtotalBetween": "προϊόντα {{minMoney}} έως κάτω από {{maxMoney}}",
|
"subtotalBetween": "αξία παραγγελίας {{minMoney}} έως κάτω από {{maxMoney}}",
|
||||||
"subtotalFrom": "προϊόντα {{minMoney}} και πάνω",
|
"subtotalFrom": "αξία παραγγελίας {{minMoney}} και πάνω",
|
||||||
"subtotalBelow": "προϊόντα κάτω από {{maxMoney}}",
|
"subtotalBelow": "αξία παραγγελίας κάτω από {{maxMoney}}",
|
||||||
"itemsBetween": "{{min}} έως {{max}} τεμάχια",
|
"itemsBetween": "{{min}} έως {{max}} τεμάχια",
|
||||||
"itemsFrom": "{{min}} τεμάχια και πάνω",
|
"itemsFrom": "{{min}} τεμάχια και πάνω",
|
||||||
"itemsUpTo": "έως {{max}} τεμάχια",
|
"itemsUpTo": "έως {{max}} τεμάχια",
|
||||||
@@ -853,10 +855,10 @@
|
|||||||
"conditions": "Μόνο όταν (όσα συμπληρώσετε)",
|
"conditions": "Μόνο όταν (όσα συμπληρώσετε)",
|
||||||
"conditionsHint": "Αφήστε κενό για πάντα.",
|
"conditionsHint": "Αφήστε κενό για πάντα.",
|
||||||
"onlyAreas": "Περιοχές διανομής",
|
"onlyAreas": "Περιοχές διανομής",
|
||||||
"subtotalMin": "Προϊόντα από (€)",
|
"subtotalMin": "Αξία παραγγελίας από (€)",
|
||||||
"subtotalMax": "Προϊόντα κάτω από (€)",
|
"subtotalMax": "Αξία παραγγελίας κάτω από (€)",
|
||||||
"itemsMin": "Τεμάχια από",
|
"itemsMin": "Σύνολο τεμαχίων από",
|
||||||
"itemsMax": "Τεμάχια έως",
|
"itemsMax": "Σύνολο τεμαχίων έως",
|
||||||
"onlyDays": "Ημέρες",
|
"onlyDays": "Ημέρες",
|
||||||
"timeFrom": "Από",
|
"timeFrom": "Από",
|
||||||
"timeTo": "Έως",
|
"timeTo": "Έως",
|
||||||
@@ -3533,6 +3535,23 @@
|
|||||||
"payYes": "Καταγραφή πληρωμής",
|
"payYes": "Καταγραφή πληρωμής",
|
||||||
"paidAll": "Πληρώθηκαν {{amount}}: δεν οφείλεται τίποτα άλλο",
|
"paidAll": "Πληρώθηκαν {{amount}}: δεν οφείλεται τίποτα άλλο",
|
||||||
"paidPart": "Πληρώθηκαν {{amount}}: οφείλονται ακόμα {{due}}",
|
"paidPart": "Πληρώθηκαν {{amount}}: οφείλονται ακόμα {{due}}",
|
||||||
|
"amountFromLines": "Το άθροισμα των γραμμών.",
|
||||||
|
"lines": "Τι αγοράστηκε",
|
||||||
|
"addLine": "Προσθήκη γραμμής",
|
||||||
|
"noLines": "Χωρίς γραμμές: το σύνολο γράφεται πάνω. Προσθέστε γραμμές για ό,τι αγοράστηκε (με ΦΠΑ)· αυτές κάνουν το σύνολο.",
|
||||||
|
"lineWhat": "Είδος",
|
||||||
|
"lineQty": "Ποσότητα",
|
||||||
|
"linePrice": "Τιμή (χωρίς ΦΠΑ)",
|
||||||
|
"lineVat": "ΦΠΑ",
|
||||||
|
"lineTotal": "Σύνολο",
|
||||||
|
"removeLine": "Αφαίρεση γραμμής",
|
||||||
|
"net": "Χωρίς ΦΠΑ",
|
||||||
|
"vat": "ΦΠΑ",
|
||||||
|
"documents": "Έγγραφα",
|
||||||
|
"addDocument": "Επισύναψη PDF ή φωτογραφίας",
|
||||||
|
"noDocuments": "Κανένα έγγραφο. Επισυνάψτε το τιμολόγιο (PDF) ή φωτογραφία της απόδειξης.",
|
||||||
|
"uploadOnSave": "ανεβαίνει με την αποθήκευση",
|
||||||
|
"removeDocument": "Αφαίρεση {{name}}",
|
||||||
"wrong": {
|
"wrong": {
|
||||||
"description": "Γράψτε τι είναι.",
|
"description": "Γράψτε τι είναι.",
|
||||||
"total_amount": "Βάλτε ποσό πάνω από μηδέν.",
|
"total_amount": "Βάλτε ποσό πάνω από μηδέν.",
|
||||||
|
|||||||
@@ -777,6 +777,8 @@
|
|||||||
"fees": {
|
"fees": {
|
||||||
"title": "Delivery areas and fees",
|
"title": "Delivery areas and fees",
|
||||||
"intro": "Fees for online orders, looked at from the top: every rule whose conditions hold changes the fee, or refuses the order below a minimum. The customer sees the fee before ordering, and the online checkout charges exactly what \"Test an order\" shows. Without rules there is no fee.",
|
"intro": "Fees for online orders, looked at from the top: every rule whose conditions hold changes the fee, or refuses the order below a minimum. The customer sees the fee before ordering, and the online checkout charges exactly what \"Test an order\" shows. Without rules there is no fee.",
|
||||||
|
"settings": "Fee settings",
|
||||||
|
"noSettings": "The delivery fee line is not set up.",
|
||||||
"rules": "Fee rules",
|
"rules": "Fee rules",
|
||||||
"addRule": "Add a rule",
|
"addRule": "Add a rule",
|
||||||
"editRule": "Edit rule",
|
"editRule": "Edit rule",
|
||||||
@@ -810,9 +812,9 @@
|
|||||||
"stopShort": "stop here",
|
"stopShort": "stop here",
|
||||||
"cond": {
|
"cond": {
|
||||||
"areas": "area {{names}}",
|
"areas": "area {{names}}",
|
||||||
"subtotalBetween": "products {{minMoney}} to under {{maxMoney}}",
|
"subtotalBetween": "order price {{minMoney}} to under {{maxMoney}}",
|
||||||
"subtotalFrom": "products {{minMoney}} or more",
|
"subtotalFrom": "order price {{minMoney}} or more",
|
||||||
"subtotalBelow": "products under {{maxMoney}}",
|
"subtotalBelow": "order price under {{maxMoney}}",
|
||||||
"itemsBetween": "{{min}} to {{max}} items",
|
"itemsBetween": "{{min}} to {{max}} items",
|
||||||
"itemsFrom": "{{min}} items or more",
|
"itemsFrom": "{{min}} items or more",
|
||||||
"itemsUpTo": "up to {{max}} items",
|
"itemsUpTo": "up to {{max}} items",
|
||||||
@@ -853,10 +855,10 @@
|
|||||||
"conditions": "Only when (all that you fill in)",
|
"conditions": "Only when (all that you fill in)",
|
||||||
"conditionsHint": "Leave empty for always.",
|
"conditionsHint": "Leave empty for always.",
|
||||||
"onlyAreas": "Delivery areas",
|
"onlyAreas": "Delivery areas",
|
||||||
"subtotalMin": "Products from (€)",
|
"subtotalMin": "Order price from (€)",
|
||||||
"subtotalMax": "Products under (€)",
|
"subtotalMax": "Order price under (€)",
|
||||||
"itemsMin": "Items from",
|
"itemsMin": "Total items count from",
|
||||||
"itemsMax": "Items up to",
|
"itemsMax": "Total items count up to",
|
||||||
"onlyDays": "Days",
|
"onlyDays": "Days",
|
||||||
"timeFrom": "From",
|
"timeFrom": "From",
|
||||||
"timeTo": "Until",
|
"timeTo": "Until",
|
||||||
@@ -3533,6 +3535,23 @@
|
|||||||
"payYes": "Record the payment",
|
"payYes": "Record the payment",
|
||||||
"paidAll": "{{amount}} paid: nothing more is due",
|
"paidAll": "{{amount}} paid: nothing more is due",
|
||||||
"paidPart": "{{amount}} paid: {{due}} still due",
|
"paidPart": "{{amount}} paid: {{due}} still due",
|
||||||
|
"amountFromLines": "The lines add up to it.",
|
||||||
|
"lines": "What was bought",
|
||||||
|
"addLine": "Add a line",
|
||||||
|
"noLines": "No lines: the total is typed above. Add lines to list what was bought (with VAT); they make the total.",
|
||||||
|
"lineWhat": "Item",
|
||||||
|
"lineQty": "Quantity",
|
||||||
|
"linePrice": "Price (before VAT)",
|
||||||
|
"lineVat": "VAT",
|
||||||
|
"lineTotal": "Total",
|
||||||
|
"removeLine": "Remove the line",
|
||||||
|
"net": "Before VAT",
|
||||||
|
"vat": "VAT",
|
||||||
|
"documents": "Documents",
|
||||||
|
"addDocument": "Attach a PDF or photo",
|
||||||
|
"noDocuments": "No documents. Attach the invoice (PDF) or a photo of the receipt.",
|
||||||
|
"uploadOnSave": "uploaded when you save",
|
||||||
|
"removeDocument": "Remove {{name}}",
|
||||||
"wrong": {
|
"wrong": {
|
||||||
"description": "Say what it is.",
|
"description": "Say what it is.",
|
||||||
"total_amount": "Enter an amount above zero.",
|
"total_amount": "Enter an amount above zero.",
|
||||||
|
|||||||
@@ -523,12 +523,14 @@ try {
|
|||||||
&& await page.getByTestId('online-tab-settings').getAttribute('aria-selected') === 'true' && await page.getByTestId('rule').count() === 0)
|
&& await page.getByTestId('online-tab-settings').getAttribute('aria-selected') === 'true' && await page.getByTestId('rule').count() === 0)
|
||||||
r.check('ordering link: the venue\'s ordering app address is shown, with its QR code', await page.getByTestId('ordering-link').count() === 1
|
r.check('ordering link: the venue\'s ordering app address is shown, with its QR code', await page.getByTestId('ordering-link').count() === 1
|
||||||
&& (await page.getByTestId('ordering-link-url').textContent()).endsWith('/order/test-site-1') && await page.getByTestId('ordering-link').locator('svg').count() >= 1)
|
&& (await page.getByTestId('ordering-link-url').textContent()).endsWith('/order/test-site-1') && await page.getByTestId('ordering-link').locator('svg').count() >= 1)
|
||||||
|
await page.getByTestId('fees-tab-areas').click() // rules · areas · fee settings are tabs (2026-11-20)
|
||||||
await page.getByTestId('area-add').click()
|
await page.getByTestId('area-add').click()
|
||||||
await page.getByTestId('area-name').fill('Centre')
|
await page.getByTestId('area-name').fill('Centre')
|
||||||
await page.getByTestId('area-postcodes').fill('24100, 241 31')
|
await page.getByTestId('area-postcodes').fill('24100, 241 31')
|
||||||
await page.getByTestId('area-save').click()
|
await page.getByTestId('area-save').click()
|
||||||
r.check('fees: an area with postcodes', await page.getByTestId('area').filter({ hasText: 'Centre' }).waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
|
r.check('fees: an area with postcodes', await page.getByTestId('area').filter({ hasText: 'Centre' }).waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
|
||||||
&& (await page.getByTestId('area').first().textContent()).includes('241 31'))
|
&& (await page.getByTestId('area').first().textContent()).includes('241 31'))
|
||||||
|
await page.getByTestId('fees-tab-rules').click()
|
||||||
const addRule = async (name, fill) => {
|
const addRule = async (name, fill) => {
|
||||||
await page.getByTestId('rule-add').click()
|
await page.getByTestId('rule-add').click()
|
||||||
await page.getByTestId('rule-name').fill(name)
|
await page.getByTestId('rule-name').fill(name)
|
||||||
@@ -569,6 +571,7 @@ try {
|
|||||||
await page.waitForFunction(() => document.querySelector('[data-testid="test-result"]')?.dataset.refused, null, { timeout: 5000 }).catch(() => {})
|
await page.waitForFunction(() => document.querySelector('[data-testid="test-result"]')?.dataset.refused, null, { timeout: 5000 }).catch(() => {})
|
||||||
r.check('fees: …a postcode outside the areas is refused', await page.getByTestId('test-result').getAttribute('data-refused') === 'area_not_served')
|
r.check('fees: …a postcode outside the areas is refused', await page.getByTestId('test-result').getAttribute('data-refused') === 'area_not_served')
|
||||||
// S.5: the fee's line on the bill and the receipt (a system product, never in the catalogue)
|
// S.5: the fee's line on the bill and the receipt (a system product, never in the catalogue)
|
||||||
|
await page.getByTestId('fees-tab-settings').click()
|
||||||
await page.getByTestId('fee-product-name').fill('Delivery')
|
await page.getByTestId('fee-product-name').fill('Delivery')
|
||||||
await page.getByTestId('fee-product-vat').fill('2')
|
await page.getByTestId('fee-product-vat').fill('2')
|
||||||
await page.getByTestId('fee-product-save').click()
|
await page.getByTestId('fee-product-save').click()
|
||||||
|
|||||||
Reference in New Issue
Block a user