diff --git a/manager_dashboard/src/pages/finance/ExpenseDialog.jsx b/manager_dashboard/src/pages/finance/ExpenseDialog.jsx index 134c930..fdd8156 100644 --- a/manager_dashboard/src/pages/finance/ExpenseDialog.jsx +++ b/manager_dashboard/src/pages/finance/ExpenseDialog.jsx @@ -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 ( - }> -
+
set('description', e.target.value)} placeholder={t('finance.exp.whatHint')} data-testid="expense-description" /> -
+
set('total_amount', e.target.value)} placeholder="0,00" data-testid="expense-amount" /> - setAddContact(true)}>{t('finance.exp.newSupplier')}}> set('due_date', e.target.value)} data-testid="expense-due-date" /> + + {hasLines + ? + : set('total_amount', e.target.value)} placeholder="0,00" data-testid="expense-amount" />} +
+ + {/* what it bought */} +
+
+

{t('finance.exp.lines')}

+
+ {!hasLines ?

{t('finance.exp.noLines')}

: ( +
+ + + + + + + + + + + + {form.lines.map((l, i) => { + const m = lineMoney(l) + const bad = tried && wrong.includes(`line.${i}`) + return ( + + + + + + + + + ) + })} + + + + + + +
{t('finance.exp.lineWhat')}{t('finance.exp.lineQty')}{t('finance.exp.linePrice')}{t('finance.exp.lineVat')}{t('finance.exp.lineTotal')} +
setLine(i, 'description', e.target.value)} aria-label={t('finance.exp.lineWhat')} data-testid="expense-line-what" /> setLine(i, 'quantity', e.target.value)} aria-label={t('finance.exp.lineQty')} data-testid="expense-line-qty" /> setLine(i, 'unit_price', e.target.value)} aria-label={t('finance.exp.linePrice')} data-testid="expense-line-price" /> + 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} %` }))} /> + {fmt.formatMoney(m.total)} + set('lines', form.lines.filter((_, j) => j !== i))}> +
{t('finance.exp.net')}{fmt.formatMoney(sum.net)}
{t('finance.exp.vat')}{fmt.formatMoney(sum.vat)}
{t('finance.exp.total')}{fmt.formatMoney(sum.total)}
+
+ )} +
+ + {/* the invoice / receipt */} +
+
+

{t('finance.exp.documents')}

+
+ {docs.length === 0 ?

{t('finance.exp.noDocuments')}

: ( +
    + {docs.map(d => ( +
  • + {d.content_type === 'application/pdf' ?
  • + ))} +
+ )} +
+