feat(manager): expenses, the supplier book and tabs on v2 (platform-v2 step 6.13a)

- Finance -> Expenses: still owed, late, filters, new/edit (supplier picked or added there), pay in parts, details with payments, delete
- CRM -> Contacts: the supplier book with what each one is owed
- Finance -> Tabs: open (who owes most first) / settled, charges and payments, pay (cash/card/other), close, forgive
- backend: expenses.manage / tabs.manage (the list also reports.view, a customer's tabs also crm.manage, put-on-tab needs tabs.manage);
  payment <= due (expense.over_due), total >= paid (expense.below_paid), categories/kinds/methods checked, null clears a field;
  live events expenses.changed / tabs.changed; GET /api/expenses ?from=&to= venue dates (the report uses it); tab_status=settled
- fix: an expense with a due date failed to save (naive date refused by D-11)
- @xenia/i18n/number subpath; tests: test_finance.py (6), finance.test.mjs (5), e2e manager.mjs finance flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 12:54:21 +02:00
co-authored by Claude Opus 5.5
parent 6bdf0bdd79
commit 93c0dd7d9c
32 changed files with 1667 additions and 1153 deletions
+3 -3
View File
@@ -21,12 +21,12 @@ import FeesPage from './pages/online/FeesPage'
import QrCodesPage from './pages/online/QrCodesPage'
// CRM
import ContactsPage from './pages/crm/ContactsPage'
import ContactsPage from './pages/finance/ContactsPage'
import CustomersPage from './pages/crm/CustomersPage'
// Financials
import ExpensesPage from './pages/financials/ExpensesPage'
import TabsPage from './pages/financials/TabsPage'
import ExpensesPage from './pages/finance/ExpensesPage'
import TabsPage from './pages/finance/TabsPage'
// Management
import ProductsPage from './pages/products/ProductsPage'
@@ -1,217 +0,0 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
const TYPE_LABELS = {
supplier: 'Προμηθευτής',
staff: 'Προσωπικό',
utility: 'Κοινή Χρεία',
other: 'Άλλο',
}
const TYPE_COLORS = {
supplier: { bg: '#eff6ff', color: '#1d4ed8' },
staff: { bg: '#f0fdf4', color: '#15803d' },
utility: { bg: '#fefce8', color: '#a16207' },
other: { bg: '#f3f4f6', color: '#374151' },
}
const EMPTY_FORM = { name: '', type: 'supplier', phone: '', email: '', address: '', notes: '' }
function ContactModal({ initial, onClose, onSave, isPending }) {
const [form, setForm] = useState(initial ?? EMPTY_FORM)
const f = (k, v) => setForm(p => ({ ...p, [k]: v }))
const isNew = !initial?.id
const canSave = form.name.trim()
const inputStyle = {
width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit',
background: 'white',
}
return (
<div style={{
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
zIndex: 50, padding: 20,
}}>
<div style={{
background: 'white', borderRadius: 16, width: '100%', maxWidth: 520,
boxShadow: '0 20px 60px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column',
}}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{isNew ? 'Νέα Επαφή' : 'Επεξεργασία Επαφής'}</h2>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af' }}>✕</button>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Όνομα *</label>
<input style={inputStyle} value={form.name} onChange={e => f('name', e.target.value)} autoFocus placeholder="π.χ. Νίκος Γαλακτοπωλείο" />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Τύπος</label>
<select style={inputStyle} value={form.type} onChange={e => f('type', e.target.value)}>
{Object.entries(TYPE_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
</select>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Τηλέφωνο</label>
<input style={inputStyle} value={form.phone} onChange={e => f('phone', e.target.value)} placeholder="π.χ. 6912345678" />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Email</label>
<input style={inputStyle} type="email" value={form.email} onChange={e => f('email', e.target.value)} placeholder="info@example.com" />
</div>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Διεύθυνση</label>
<input style={inputStyle} value={form.address} onChange={e => f('address', e.target.value)} placeholder="Οδός, Πόλη" />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημειώσεις</label>
<textarea style={{ ...inputStyle, resize: 'none' }} rows={3} value={form.notes} onChange={e => f('notes', e.target.value)} placeholder="Εσωτερικές σημειώσεις…" />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button
onClick={() => onSave(form)}
disabled={!canSave || isPending}
style={{
padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600,
cursor: canSave && !isPending ? 'pointer' : 'default',
background: canSave ? '#111827' : '#e5e7eb',
color: canSave ? 'white' : '#9ca3af',
}}
>
{isPending ? 'Αποθήκευση…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
</button>
</div>
</div>
</div>
)
}
export default function ContactsPage() {
const qc = useQueryClient()
const [modal, setModal] = useState(null) // null | { contact } | { contact: null } for new
const { data: contacts = [], isLoading } = useQuery({
queryKey: ['contacts'],
queryFn: () => client.get('/api/contacts/').then(r => r.data),
staleTime: 30_000,
})
const save = useMutation({
mutationFn: ({ form, id }) => id
? client.put(`/api/contacts/${id}`, form)
: client.post('/api/contacts/', form),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['contacts'] })
setModal(null)
toast.success('Αποθηκεύτηκε')
},
onError: () => toast.error('Σφάλμα αποθήκευσης'),
})
const deactivate = useMutation({
mutationFn: (id) => client.delete(`/api/contacts/${id}`),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['contacts'] })
toast.success('Η επαφή αποενεργοποιήθηκε')
},
onError: () => toast.error('Σφάλμα'),
})
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '18px 28px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0, background: 'white' }}>
<div>
<p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>{contacts.length} ενεργές επαφές</p>
</div>
<button
onClick={() => setModal({ contact: null })}
style={{ padding: '9px 18px', borderRadius: 9, border: 'none', background: '#111827', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
>
+ Νέα Επαφή
</button>
</div>
{/* Table */}
<div style={{ flex: 1, overflowY: 'auto', padding: '20px 28px' }}>
{isLoading && <div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0' }}>Φόρτωση…</div>}
{!isLoading && contacts.length === 0 && (
<div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0', fontSize: 14 }}>
Δεν υπάρχουν επαφές ακόμα. Προσθέστε τον πρώτο προμηθευτή.
</div>
)}
{contacts.length > 0 && (
<div style={{ border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
<thead>
<tr style={{ background: '#f9fafb', borderBottom: '1px solid #e5e7eb' }}>
{['Όνομα', 'Τύπος', 'Τηλέφωνο', 'Email', ''].map(h => (
<th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>{h}</th>
))}
</tr>
</thead>
<tbody>
{contacts.map((c, i) => {
const tc = TYPE_COLORS[c.type] || TYPE_COLORS.other
return (
<tr key={c.id} style={{ borderBottom: i < contacts.length - 1 ? '1px solid #f3f4f6' : 'none', background: 'white' }}>
<td style={{ padding: '12px 16px', fontWeight: 600, color: '#111315' }}>
{c.name}
{c.notes && <div style={{ fontSize: 11.5, color: '#9ca3af', fontWeight: 400, marginTop: 1 }}>{c.notes.slice(0, 60)}{c.notes.length > 60 ? '…' : ''}</div>}
</td>
<td style={{ padding: '12px 16px' }}>
<span style={{ fontSize: 11.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: tc.bg, color: tc.color }}>
{TYPE_LABELS[c.type] || c.type}
</span>
</td>
<td style={{ padding: '12px 16px', color: c.phone ? '#374151' : '#d1d5db' }}>{c.phone || '—'}</td>
<td style={{ padding: '12px 16px', color: c.email ? '#374151' : '#d1d5db' }}>{c.email || '—'}</td>
<td style={{ padding: '12px 16px', textAlign: 'right' }}>
<div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
<button
onClick={() => setModal({ contact: c })}
style={{ padding: '4px 12px', borderRadius: 6, border: '1px solid #e5e7eb', background: 'white', fontSize: 12, fontWeight: 500, cursor: 'pointer', color: '#374151' }}
>
Επεξεργασία
</button>
<button
onClick={() => { if (window.confirm(`Αποενεργοποίηση "${c.name}";`)) deactivate.mutate(c.id) }}
style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid #fecaca', background: 'white', fontSize: 12, cursor: 'pointer', color: '#ef4444' }}
>
Απενεργ.
</button>
</div>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
</div>
{modal && (
<ContactModal
initial={modal.contact ? { ...modal.contact, phone: modal.contact.phone || '', email: modal.contact.email || '', address: modal.contact.address || '', notes: modal.contact.notes || '' } : null}
onClose={() => setModal(null)}
isPending={save.isPending}
onSave={(form) => save.mutate({
form: { name: form.name, type: form.type, phone: form.phone || null, email: form.email || null, address: form.address || null, notes: form.notes || null },
id: modal.contact?.id,
})}
/>
)}
</div>
)
}
@@ -1,436 +0,0 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
// ── Constants ─────────────────────────────────────────────────────────────────
const CATEGORIES = [
{ id: 'supplier', label: 'Προμηθευτής' },
{ id: 'utilities', label: 'Κοινή Χρεία' },
{ id: 'rent', label: 'Ενοίκιο' },
{ id: 'maintenance',label: 'Συντήρηση' },
{ id: 'staff', label: 'Προσωπικό' },
{ id: 'equipment', label: 'Εξοπλισμός' },
{ id: 'other', label: 'Άλλο' },
]
const STATUS_CONFIG = {
due: { label: 'Οφείλεται', bg: '#fee2e2', color: '#dc2626' },
partial: { label: 'Μερική Πληρ.', bg: '#fef9c3', color: '#a16207' },
paid: { label: 'Πληρώθηκε', bg: '#dcfce7', color: '#16a34a' },
}
// ── Helpers ───────────────────────────────────────────────────────────────────
function fmt(n) {
if (n == null) return '—'
return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
}
function fmtDate(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit', year: 'numeric' })
}
function fmtDateTime(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
}
const inputStyle = {
width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit', background: 'white',
}
// ── Expense form modal ────────────────────────────────────────────────────────
const EMPTY_FORM = { description: '', category: 'supplier', contact_id: '', total_amount: '', due_date: '', notes: '' }
function ExpenseModal({ initial, contacts, onClose, onSave, isPending }) {
const [form, setForm] = useState(initial ?? EMPTY_FORM)
const f = (k, v) => setForm(p => ({ ...p, [k]: v }))
const isNew = !initial?.id
const canSave = form.description.trim() && parseFloat(form.total_amount) > 0
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 540, boxShadow: '0 20px 60px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{isNew ? 'Νέο Έξοδο' : 'Επεξεργασία Εξόδου'}</h2>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af' }}>✕</button>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Περιγραφή *</label>
<input style={inputStyle} value={form.description} onChange={e => f('description', e.target.value)} autoFocus placeholder="π.χ. Τιμολόγιο Νοεμβρίου — Γαλακτοκομικά" />
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Κατηγορία</label>
<select style={inputStyle} value={form.category} onChange={e => f('category', e.target.value)}>
{CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
</select>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ποσό (€) *</label>
<input style={inputStyle} type="number" step="0.01" min="0" value={form.total_amount} onChange={e => f('total_amount', e.target.value)} placeholder="0.00" />
</div>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Επαφή / Προμηθευτής</label>
<select style={inputStyle} value={form.contact_id} onChange={e => f('contact_id', e.target.value)}>
<option value="">— Χωρίς επαφή —</option>
{contacts.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ημ/νία πληρωμής</label>
<input style={inputStyle} type="date" value={form.due_date ? form.due_date.slice(0, 10) : ''} onChange={e => f('due_date', e.target.value)} />
</div>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημειώσεις</label>
<textarea style={{ ...inputStyle, resize: 'none' }} rows={2} value={form.notes} onChange={e => f('notes', e.target.value)} placeholder="Προαιρετικές σημειώσεις…" />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button
onClick={() => onSave(form)}
disabled={!canSave || isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: canSave && !isPending ? 'pointer' : 'default', background: canSave ? '#111827' : '#e5e7eb', color: canSave ? 'white' : '#9ca3af' }}
>
{isPending ? 'Αποθήκευση…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
</button>
</div>
</div>
</div>
)
}
// ── Pay modal ─────────────────────────────────────────────────────────────────
function PayModal({ expense, onClose, onPay, isPending }) {
const [amount, setAmount] = useState(String(Math.round((expense.due_amount) * 100) / 100))
const [notes, setNotes] = useState('')
const parsed = parseFloat(amount)
const canPay = parsed > 0 && parsed <= expense.due_amount + 0.001
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 400, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef' }}>
<h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>Καταγραφή Πληρωμής</h2>
<p style={{ margin: '4px 0 0', fontSize: 13, color: '#6b7280' }}>{expense.description}</p>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
<div style={{ background: '#f9fafb', borderRadius: 10, padding: '12px 14px', display: 'flex', justifyContent: 'space-between' }}>
<span style={{ fontSize: 13, color: '#6b7280' }}>Εκκρεμεί</span>
<span style={{ fontSize: 15, fontWeight: 700, color: '#dc2626' }}>{fmt(expense.due_amount)}</span>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ποσό πληρωμής (€)</label>
<input style={inputStyle} type="number" step="0.01" min="0.01" max={expense.due_amount} value={amount} onChange={e => setAmount(e.target.value)} autoFocus />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημείωση</label>
<input style={inputStyle} value={notes} onChange={e => setNotes(e.target.value)} placeholder="π.χ. Μετρητά στο χέρι" />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button
onClick={() => onPay(parsed, notes || null)}
disabled={!canPay || isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: canPay && !isPending ? 'pointer' : 'default', background: canPay ? '#16a34a' : '#e5e7eb', color: canPay ? 'white' : '#9ca3af' }}
>
{isPending ? 'Αποθήκευση…' : 'Καταγραφή Πληρωμής'}
</button>
</div>
</div>
</div>
)
}
// ── Expense row (expandable) ──────────────────────────────────────────────────
function ExpenseRow({ expense, isExpanded, onToggle, onPay, onEdit, onDelete }) {
const sc = STATUS_CONFIG[expense.status] || STATUS_CONFIG.due
const catLabel = CATEGORIES.find(c => c.id === expense.category)?.label || expense.category
return (
<>
<tr
onClick={onToggle}
style={{ borderBottom: '1px solid #f3f4f6', cursor: 'pointer', background: isExpanded ? '#f9fafb' : 'white' }}
>
<td style={{ padding: '12px 16px' }}>
<div style={{ fontWeight: 600, color: '#111315', fontSize: 13.5 }}>{expense.description}</div>
{expense.contact_name && <div style={{ fontSize: 11.5, color: '#9ca3af', marginTop: 1 }}>{expense.contact_name}</div>}
</td>
<td style={{ padding: '12px 16px', fontSize: 12, color: '#6b7280' }}>{catLabel}</td>
<td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 600, color: '#111315', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{fmt(expense.total_amount)}</td>
<td style={{ padding: '12px 16px', fontSize: 13, color: '#16a34a', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{expense.paid_amount > 0 ? fmt(expense.paid_amount) : '—'}</td>
<td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 700, color: '#dc2626', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{expense.due_amount > 0 ? fmt(expense.due_amount) : '—'}</td>
<td style={{ padding: '12px 16px' }}>
<span style={{ fontSize: 11.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: sc.bg, color: sc.color }}>{sc.label}</span>
</td>
<td style={{ padding: '12px 16px', fontSize: 12, color: '#9ca3af' }}>{expense.due_date ? fmtDate(expense.due_date) : '—'}</td>
<td style={{ padding: '12px 16px', textAlign: 'right' }}>
<div style={{ display: 'flex', gap: 5, justifyContent: 'flex-end' }}>
{expense.status !== 'paid' && (
<button
onClick={e => { e.stopPropagation(); onPay() }}
style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid #bbf7d0', background: '#f0fdf4', fontSize: 12, fontWeight: 600, cursor: 'pointer', color: '#16a34a' }}
>
Πληρωμή
</button>
)}
<button
onClick={e => { e.stopPropagation(); onEdit() }}
style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid #e5e7eb', background: 'white', fontSize: 12, cursor: 'pointer', color: '#374151' }}
>
Επεξ.
</button>
<button
onClick={e => { e.stopPropagation(); onDelete() }}
style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid #fecaca', background: 'white', fontSize: 12, cursor: 'pointer', color: '#ef4444' }}
>
✕
</button>
</div>
</td>
</tr>
{isExpanded && (
<tr style={{ background: '#f9fafb' }}>
<td colSpan={8} style={{ padding: '12px 16px 16px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{expense.notes && (
<p style={{ margin: 0, fontSize: 12.5, color: '#6b7280', fontStyle: 'italic' }}>📝 {expense.notes}</p>
)}
<div style={{ fontSize: 11.5, color: '#9ca3af' }}>
Καταχωρήθηκε από {expense.created_by_name} · {fmtDate(expense.created_at)}
</div>
{expense.payments.length > 0 && (
<div>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Ιστορικό Πληρωμών</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{expense.payments.map(p => (
<div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 12px', background: 'white', borderRadius: 8, border: '1px solid #e5e7eb' }}>
<span style={{ fontSize: 12.5, color: '#374151' }}>
{p.paid_by_name} · {fmtDateTime(p.paid_at)}
{p.notes && <span style={{ color: '#9ca3af' }}> — {p.notes}</span>}
</span>
<span style={{ fontSize: 13, fontWeight: 700, color: '#16a34a' }}>{fmt(p.amount)}</span>
</div>
))}
</div>
</div>
)}
{expense.payments.length === 0 && expense.status === 'due' && (
<div style={{ fontSize: 12.5, color: '#d1d5db' }}>Δεν έχουν καταγραφεί πληρωμές.</div>
)}
</div>
</td>
</tr>
)}
</>
)
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function ExpensesPage() {
const qc = useQueryClient()
const [statusFilter, setStatusFilter] = useState('all')
const [categoryFilter, setCategoryFilter] = useState('all')
const [expanded, setExpanded] = useState(null)
const [modal, setModal] = useState(null) // null | { type: 'expense', expense? } | { type: 'pay', expense }
const params = {}
if (statusFilter !== 'all') params.status = statusFilter
if (categoryFilter !== 'all') params.category = categoryFilter
const { data: expenses = [], isLoading } = useQuery({
queryKey: ['expenses', statusFilter, categoryFilter],
queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data),
staleTime: 15_000,
})
const { data: contacts = [] } = useQuery({
queryKey: ['contacts'],
queryFn: () => client.get('/api/contacts/').then(r => r.data),
staleTime: 60_000,
})
const { data: summary } = useQuery({
queryKey: ['expenses-summary'],
queryFn: () => client.get('/api/expenses/summary').then(r => r.data),
staleTime: 15_000,
})
const saveExpense = useMutation({
mutationFn: ({ form, id }) => id
? client.put(`/api/expenses/${id}`, form)
: client.post('/api/expenses/', form),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['expenses'] })
qc.invalidateQueries({ queryKey: ['expenses-summary'] })
setModal(null)
toast.success('Αποθηκεύτηκε')
},
onError: () => toast.error('Σφάλμα αποθήκευσης'),
})
const payExpense = useMutation({
mutationFn: ({ id, amount, notes }) => client.post(`/api/expenses/${id}/pay`, { amount, notes }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['expenses'] })
qc.invalidateQueries({ queryKey: ['expenses-summary'] })
setModal(null)
toast.success('Πληρωμή καταγράφηκε')
},
onError: () => toast.error('Σφάλμα καταγραφής πληρωμής'),
})
const deleteExpense = useMutation({
mutationFn: (id) => client.delete(`/api/expenses/${id}`),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['expenses'] })
qc.invalidateQueries({ queryKey: ['expenses-summary'] })
toast.success('Διαγράφηκε')
},
onError: () => toast.error('Σφάλμα διαγραφής'),
})
const totalDue = summary?.total_due ?? 0
const pendingCount = expenses.filter(e => e.status !== 'paid').length
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '18px 28px 14px', borderBottom: '1px solid #f0f0ef', flexShrink: 0, background: 'white' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
<div>
<p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>
{pendingCount} εκκρεμή · Σύνολο οφειλών: <strong style={{ color: totalDue > 0 ? '#dc2626' : '#16a34a' }}>{fmt(totalDue)}</strong>
</p>
</div>
<button
onClick={() => setModal({ type: 'expense', expense: null })}
style={{ padding: '9px 18px', borderRadius: 9, border: 'none', background: '#111827', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
>
+ Νέο Έξοδο
</button>
</div>
{/* Filters */}
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{/* Status filter */}
<div style={{ display: 'flex', gap: 4 }}>
{[['all', 'Όλα'], ['due', 'Οφείλεται'], ['partial', 'Μερική'], ['paid', 'Πληρώθηκε']].map(([v, l]) => (
<button key={v} onClick={() => setStatusFilter(v)}
style={{
padding: '5px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, cursor: 'pointer', border: '1.5px solid',
borderColor: statusFilter === v ? '#111827' : '#e5e7eb',
background: statusFilter === v ? '#111827' : 'white',
color: statusFilter === v ? 'white' : '#6b7280',
}}>
{l}
</button>
))}
</div>
{/* Category filter */}
<select
value={categoryFilter}
onChange={e => setCategoryFilter(e.target.value)}
style={{ padding: '5px 10px', borderRadius: 8, border: '1px solid #e5e7eb', fontSize: 12, outline: 'none', background: 'white', color: '#374151' }}
>
<option value="all">Όλες οι κατηγορίες</option>
{CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
</select>
</div>
</div>
{/* Table */}
<div style={{ flex: 1, overflowY: 'auto', padding: '16px 28px' }}>
{isLoading && <div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0' }}>Φόρτωση…</div>}
{!isLoading && expenses.length === 0 && (
<div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0', fontSize: 14 }}>
Δεν βρέθηκαν έξοδα για τα επιλεγμένα φίλτρα.
</div>
)}
{expenses.length > 0 && (
<div style={{ border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ background: '#f9fafb', borderBottom: '1px solid #e5e7eb' }}>
{['Περιγραφή', 'Κατηγορία', 'Σύνολο', 'Πληρωμένο', 'Εκκρεμεί', 'Κατάσταση', 'Ημ/νία', ''].map(h => (
<th key={h} style={{ padding: '10px 16px', textAlign: h === 'Σύνολο' || h === 'Πληρωμένο' || h === 'Εκκρεμεί' ? 'right' : 'left', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>{h}</th>
))}
</tr>
</thead>
<tbody>
{expenses.map(e => (
<ExpenseRow
key={e.id}
expense={e}
isExpanded={expanded === e.id}
onToggle={() => setExpanded(expanded === e.id ? null : e.id)}
onPay={() => setModal({ type: 'pay', expense: e })}
onEdit={() => setModal({ type: 'expense', expense: e })}
onDelete={() => { if (window.confirm('Διαγραφή εξόδου;')) deleteExpense.mutate(e.id) }}
/>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Expense create/edit modal */}
{modal?.type === 'expense' && (
<ExpenseModal
initial={modal.expense ? {
...modal.expense,
contact_id: modal.expense.contact_id ? String(modal.expense.contact_id) : '',
due_date: modal.expense.due_date || '',
notes: modal.expense.notes || '',
} : null}
contacts={contacts}
onClose={() => setModal(null)}
isPending={saveExpense.isPending}
onSave={(form) => saveExpense.mutate({
form: {
description: form.description,
category: form.category,
contact_id: form.contact_id ? Number(form.contact_id) : null,
total_amount: parseFloat(form.total_amount),
due_date: form.due_date || null,
notes: form.notes || null,
},
id: modal.expense?.id,
})}
/>
)}
{/* Pay modal */}
{modal?.type === 'pay' && (
<PayModal
expense={modal.expense}
onClose={() => setModal(null)}
isPending={payExpense.isPending}
onPay={(amount, notes) => payExpense.mutate({ id: modal.expense.id, amount, notes })}
/>
)}
</div>
)
}
-411
View File
@@ -1,411 +0,0 @@
import { useState, useMemo } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ChevronDown, Search } from 'lucide-react'
import client from '../api/client'
// ── Helpers ───────────────────────────────────────────────────────────────────
function fmt(n) {
if (n == null) return '—'
return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
}
function fmtDateTime(iso) {
if (!iso) return '—'
return new Date(iso).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
}
function daysSince(iso) {
if (!iso) return null
const days = Math.floor((Date.now() - new Date(iso).getTime()) / 86400000)
if (days === 0) return 'Σήμερα'
if (days === 1) return '1 μέρα'
return `${days} μέρες`
}
const STATUS_CONFIG = {
open: { label: 'Ανοιχτή', bg: '#fee2e2', color: '#dc2626' },
closed: { label: 'Κλειστή', bg: '#dcfce7', color: '#16a34a' },
forgiven: { label: 'Χαρίστηκε', bg: '#f3f4f6', color: '#6b7280' },
}
// ── Pay modal ─────────────────────────────────────────────────────────────────
function PayModal({ tab, onClose, onPay, isPending }) {
const [amount, setAmount] = useState(String(Math.round(tab.balance * 100) / 100))
const [method, setMethod] = useState('cash')
const [notes, setNotes] = useState('')
const parsed = parseFloat(amount)
const canPay = parsed > 0 && parsed <= tab.balance + 0.005
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 400, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ fontSize: 16, fontWeight: 700 }}>Πληρωμή Καρτέλας</div>
<div style={{ fontSize: 13, color: '#6b7280', marginTop: 2 }}>{tab.customer_name}</div>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
<div style={{ background: '#f9fafb', borderRadius: 10, padding: '12px 14px', display: 'flex', justifyContent: 'space-between' }}>
<span style={{ fontSize: 13, color: '#6b7280' }}>Υπόλοιπο καρτέλας</span>
<span style={{ fontSize: 15, fontWeight: 700, color: '#dc2626' }}>{fmt(tab.balance)}</span>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ποσό πληρωμής (€)</label>
<input type="number" step="0.01" min="0.01"
value={amount} onChange={e => setAmount(e.target.value)} autoFocus
style={{ width: '100%', padding: '9px 12px', border: '1.5px solid #e5e7eb', borderRadius: 8, fontSize: 16, fontWeight: 600, outline: 'none', boxSizing: 'border-box' }} />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Τρόπος πληρωμής</label>
<div style={{ display: 'flex', gap: 6 }}>
{[['cash', 'Μετρητά'], ['card', 'Κάρτα'], ['other', 'Άλλο']].map(([v, l]) => (
<button key={v} onClick={() => setMethod(v)}
style={{
flex: 1, padding: '7px', borderRadius: 7, fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
border: `1.5px solid ${method === v ? '#111827' : '#e5e7eb'}`,
background: method === v ? '#111827' : 'white',
color: method === v ? 'white' : '#6b7280',
}}>{l}</button>
))}
</div>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημείωση</label>
<input value={notes} onChange={e => setNotes(e.target.value)} placeholder="προαιρετικό"
style={{ width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button onClick={() => onPay(parsed, method, notes || null)} disabled={!canPay || isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: canPay ? 'pointer' : 'default', background: canPay ? '#16a34a' : '#e5e7eb', color: canPay ? 'white' : '#9ca3af' }}>
{isPending ? 'Αποθήκευση…' : 'Καταγραφή Πληρωμής'}
</button>
</div>
</div>
</div>
)
}
// ── Forgive confirm ───────────────────────────────────────────────────────────
function ForgiveModal({ tab, onClose, onForgive, isPending }) {
const [reason, setReason] = useState('')
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 400, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ fontSize: 16, fontWeight: 700, color: '#dc2626' }}>Χάρισμα Καρτέλας</div>
<div style={{ fontSize: 13, color: '#6b7280', marginTop: 2 }}>{tab.customer_name} — υπόλοιπο {fmt(tab.balance)}</div>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div style={{ padding: '12px 14px', background: '#fef2f2', borderRadius: 10, border: '1px solid #fecaca', fontSize: 13, color: '#7f1d1d', lineHeight: 1.5 }}>
Το υπόλοιπο των {fmt(tab.balance)} θα διαγραφεί. Η ενέργεια δεν αναιρείται.
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Αιτιολογία</label>
<input value={reason} onChange={e => setReason(e.target.value)} placeholder="π.χ. Καλή θέληση"
style={{ width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button onClick={() => onForgive(reason || null)} disabled={isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', background: '#dc2626', color: 'white' }}>
{isPending ? 'Αποθήκευση…' : 'Χάρισμα Υπολοίπου'}
</button>
</div>
</div>
</div>
)
}
// ── Tab detail card (collapsible) ─────────────────────────────────────────────
function TabDetail({ tab, onPay, onClose, onForgive, defaultExpanded = false }) {
const [expanded, setExpanded] = useState(defaultExpanded)
const sc = STATUS_CONFIG[tab.status] || STATUS_CONFIG.open
const canClose = tab.status === 'open' && tab.balance <= 0.005 && tab.entries.length > 0
return (
<div style={{ border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden', background: 'white' }}>
{/* Clickable header — always visible */}
<button
onClick={() => setExpanded(e => !e)}
style={{
width: '100%', textAlign: 'left',
padding: '14px 18px', background: '#f9fafb',
borderBottom: expanded ? '1px solid #e5e7eb' : 'none',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
flexWrap: 'wrap', gap: 8, cursor: 'pointer',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
<ChevronDown
size={16}
style={{
flexShrink: 0, color: '#9ca3af',
transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)',
transition: 'transform 0.18s',
}}
/>
<div style={{ minWidth: 0 }}>
<div style={{ fontSize: 15, fontWeight: 700, color: '#111315' }}>{tab.customer_name}</div>
<div style={{ fontSize: 12, color: '#9ca3af', marginTop: 1 }}>
Άνοιγμα: {fmtDateTime(tab.opened_at)} · {daysSince(tab.opened_at)} ανοιχτή
</div>
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
<span style={{ fontSize: 22, fontWeight: 800, color: tab.balance > 0 ? '#dc2626' : '#16a34a' }}>
{fmt(tab.balance)}
</span>
<span style={{ fontSize: 11.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: sc.bg, color: sc.color }}>
{sc.label}
</span>
</div>
</button>
{/* Expanded body */}
{expanded && (
<>
{/* Stats */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 1, background: '#f0f0ef' }}>
{[
{ label: 'Συνολικές χρεώσεις', value: fmt(tab.total_charged) },
{ label: 'Πληρωμένο', value: fmt(tab.total_paid), color: '#16a34a' },
{ label: 'Υπόλοιπο', value: fmt(tab.balance), color: tab.balance > 0 ? '#dc2626' : '#16a34a' },
].map(s => (
<div key={s.label} style={{ background: 'white', padding: '10px 14px', textAlign: 'center' }}>
<div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.label}</div>
<div style={{ fontSize: 15, fontWeight: 800, color: s.color || '#111315', marginTop: 2 }}>{s.value}</div>
</div>
))}
</div>
{/* Entries */}
{tab.entries.length > 0 && (
<div style={{ padding: '12px 18px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Χρεώσεις</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{tab.entries.map(e => (
<div key={e.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13 }}>
<span style={{ color: '#374151' }}>{e.description || `Χρέωση #${e.id}`}</span>
<span style={{ fontWeight: 600, color: '#dc2626', whiteSpace: 'nowrap', marginLeft: 12 }}>{fmt(e.amount)}</span>
</div>
))}
</div>
</div>
)}
{/* Payments */}
{tab.payments.length > 0 && (
<div style={{ padding: '12px 18px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Πληρωμές</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{tab.payments.map(p => (
<div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13 }}>
<span style={{ color: '#374151' }}>
{p.received_by_name} · {fmtDateTime(p.created_at)}
{p.payment_method && <span style={{ color: '#9ca3af', marginLeft: 6 }}>({p.payment_method})</span>}
{p.notes && <span style={{ color: '#9ca3af', marginLeft: 6 }}>— {p.notes}</span>}
</span>
<span style={{ fontWeight: 600, color: '#16a34a', whiteSpace: 'nowrap', marginLeft: 12 }}>{fmt(p.amount)}</span>
</div>
))}
</div>
</div>
)}
{/* Actions */}
{tab.status === 'open' && (
<div style={{ padding: '12px 18px', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{tab.balance > 0.005 && (
<button onClick={() => onPay(tab)}
style={{ padding: '7px 16px', borderRadius: 8, border: 'none', background: '#16a34a', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
Πληρωμή
</button>
)}
{canClose && (
<button onClick={() => onClose(tab)}
style={{ padding: '7px 16px', borderRadius: 8, border: '1px solid #d1d5db', background: 'white', color: '#374151', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
Κλείσιμο Καρτέλας
</button>
)}
<button onClick={() => onForgive(tab)}
style={{ padding: '7px 16px', borderRadius: 8, border: '1px solid #fecaca', background: 'white', color: '#dc2626', fontSize: 13, fontWeight: 500, cursor: 'pointer', marginLeft: 'auto' }}>
Χάρισμα Υπολοίπου
</button>
</div>
)}
</>
)}
</div>
)
}
// ── Filter chip ───────────────────────────────────────────────────────────────
function FilterChip({ label, active, onClick }) {
return (
<button
onClick={onClick}
className={`px-3 py-1 rounded-full text-[12px] font-semibold border transition-colors ${
active
? 'bg-slate-800 text-white border-slate-800'
: 'bg-white text-slate-500 border-slate-200 hover:border-slate-400 hover:text-slate-700'
}`}
>
{label}
</button>
)
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function TabsPage() {
const qc = useQueryClient()
const [statusFilter, setStatusFilter] = useState('open') // 'open' | 'closed' | 'all'
const [search, setSearch] = useState('')
const [modal, setModal] = useState(null)
// Fetch open and closed separately — merge for client-side filtering
const { data: openTabs = [], isLoading: loadingOpen } = useQuery({
queryKey: ['tabs-open'],
queryFn: () => client.get('/api/tabs/').then(r => r.data),
staleTime: 15_000,
})
const { data: closedTabs = [], isLoading: loadingClosed } = useQuery({
queryKey: ['tabs-closed'],
queryFn: () => client.get('/api/tabs/', { params: { tab_status: 'closed' } }).then(r => r.data),
staleTime: 15_000,
})
const tabs = [...openTabs, ...closedTabs]
const isLoading = loadingOpen || loadingClosed
const payTab = useMutation({
mutationFn: ({ id, amount, payment_method, notes }) =>
client.post(`/api/tabs/${id}/pay`, { amount, payment_method, notes }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['tabs-open'] }); qc.invalidateQueries({ queryKey: ['tabs-closed'] })
setModal(null)
toast.success('Πληρωμή καταγράφηκε')
},
onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
})
const closeTab = useMutation({
mutationFn: (id) => client.post(`/api/tabs/${id}/close`, {}),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['tabs-open'] }); qc.invalidateQueries({ queryKey: ['tabs-closed'] })
toast.success('Καρτέλα έκλεισε')
},
onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
})
const forgiveTab = useMutation({
mutationFn: ({ id, reason }) => client.post(`/api/tabs/${id}/forgive`, { reason }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['tabs-open'] }); qc.invalidateQueries({ queryKey: ['tabs-closed'] })
setModal(null)
toast.success('Το υπόλοιπο χαρίστηκε')
},
onError: () => toast.error('Σφάλμα'),
})
// Live client-side filtering
const filtered = useMemo(() => {
let result = tabs
if (statusFilter !== 'all') {
result = result.filter(t => {
if (statusFilter === 'open') return t.status === 'open'
if (statusFilter === 'closed') return t.status === 'closed' || t.status === 'forgiven'
return true
})
}
if (search.trim()) {
const q = search.trim().toLowerCase()
result = result.filter(t => t.customer_name?.toLowerCase().includes(q))
}
return result
}, [tabs, statusFilter, search])
const openCount = tabs.filter(t => t.status === 'open').length
const closedCount = tabs.filter(t => t.status === 'closed' || t.status === 'forgiven').length
const totalOutstanding = tabs.filter(t => t.status === 'open').reduce((s, t) => s + t.balance, 0)
return (
<div className="flex flex-col h-full overflow-hidden">
{/* Toolbar */}
<div className="px-6 py-3 border-b border-slate-200 bg-white shrink-0 flex items-center gap-3 flex-wrap">
{/* Search */}
<div className="relative flex items-center">
<Search className="absolute left-2.5 h-3.5 w-3.5 text-slate-400 pointer-events-none" />
<input
type="text"
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Αναζήτηση πελάτη…"
className="pl-8 pr-3 py-1.5 text-[13px] bg-slate-50 border border-slate-200 rounded-lg w-48 focus:outline-none focus:ring-2 focus:ring-sky-500/30 focus:border-sky-400 transition placeholder:text-slate-400"
/>
</div>
{/* Status filter chips */}
<div className="flex items-center gap-2">
<FilterChip label={`Ανοιχτές (${openCount})`} active={statusFilter === 'open'} onClick={() => setStatusFilter('open')} />
<FilterChip label={`Κλειστές (${closedCount})`} active={statusFilter === 'closed'} onClick={() => setStatusFilter('closed')} />
<FilterChip label="Όλες" active={statusFilter === 'all'} onClick={() => setStatusFilter('all')} />
</div>
{/* Summary */}
<div className="ml-auto text-[12px] text-slate-400">
{statusFilter === 'open' && totalOutstanding > 0 && (
<span>Σύνολο: <strong className="text-red-600">{fmt(totalOutstanding)}</strong></span>
)}
</div>
</div>
{/* Tab list */}
<div className="flex-1 overflow-y-auto px-6 py-4 flex flex-col gap-3">
{isLoading && (
<div className="text-center text-slate-400 text-[13px] py-12">Φόρτωση…</div>
)}
{!isLoading && filtered.length === 0 && (
<div className="text-center text-slate-400 text-[14px] py-12">
{search ? 'Δεν βρέθηκαν αποτελέσματα.' : 'Δεν υπάρχουν καρτέλες.'}
</div>
)}
{filtered.map(tab => (
<TabDetail
key={tab.id}
tab={tab}
defaultExpanded={false}
onPay={t => setModal({ type: 'pay', tab: t })}
onClose={t => closeTab.mutate(t.id)}
onForgive={t => setModal({ type: 'forgive', tab: t })}
/>
))}
</div>
{modal?.type === 'pay' && (
<PayModal
tab={modal.tab}
onClose={() => setModal(null)}
isPending={payTab.isPending}
onPay={(amount, payment_method, notes) => payTab.mutate({ id: modal.tab.id, amount, payment_method, notes })}
/>
)}
{modal?.type === 'forgive' && (
<ForgiveModal
tab={modal.tab}
onClose={() => setModal(null)}
isPending={forgiveTab.isPending}
onForgive={(reason) => forgiveTab.mutate({ id: modal.tab.id, reason })}
/>
)}
</div>
)
}
@@ -1 +0,0 @@
export { default } from '../ContactsPage'
@@ -0,0 +1,59 @@
// A supplier or other contact (plan step 6.13a): name, kind, phone, e-mail, address, notes.
// Clearing a field clears it. `onSaved(contact)` gets the saved contact (the expense dialog picks
// a new supplier at once).
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select, Textarea } from '@xenia/ui'
import client from '../../api/client'
import { CONTACT_TYPES, contactBody, contactForm, contactProblems } from './financeLogic'
export default function ContactDialog({ contact, onClose, onSaved }) {
const { t } = useTranslation('manager')
const isNew = !contact
const [form, setForm] = useState(() => contactForm(contact))
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const wrong = contactProblems(form)
const err = k => (tried && wrong.includes(k) ? t(`finance.contacts.wrong.${k}`) : undefined)
const save = useMutation({
mutationFn: body => (isNew ? client.post('/api/contacts/', body) : client.put(`/api/contacts/${contact.id}`, body)).then(r => r.data),
onSuccess: c => { toast.success(t(isNew ? 'finance.contacts.added' : 'finance.contacts.saved', { name: c.name })); onSaved(c) },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (!wrong.length) save.mutate(contactBody(form)) }
return (
<Dialog open size="md" onClose={onClose} title={isNew ? t('finance.contacts.newTitle') : contact.name}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="contact-save">{isNew ? t('finance.contacts.add') : t('finance.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="contact-dialog">
<div className="grid gap-3 sm:grid-cols-[2fr_1fr]">
<Field label={t('finance.contacts.name')} required error={err('name')}>
<Input value={form.name} autoFocus onChange={e => set('name', e.target.value)} data-testid="contact-name" />
</Field>
<Field label={t('finance.contacts.type')}>
<Select value={form.type} onChange={e => set('type', e.target.value)} options={CONTACT_TYPES.map(k => ({ value: k, label: t(`finance.contacts.types.${k}`) }))} />
</Field>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('finance.contacts.phone')}>
<Input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} data-testid="contact-phone" />
</Field>
<Field label={t('finance.contacts.email')} error={err('email')}>
<Input type="email" value={form.email} onChange={e => set('email', e.target.value)} />
</Field>
</div>
<Field label={t('finance.contacts.address')}>
<Input value={form.address} onChange={e => set('address', e.target.value)} />
</Field>
<Field label={t('finance.notes')} hint={t('finance.contacts.notesHint')}>
<Textarea rows={3} value={form.notes} onChange={e => set('notes', e.target.value)} />
</Field>
</div>
</Dialog>
)
}
@@ -0,0 +1,96 @@
// CRM → Contacts, the supplier book (plan step 6.13a; replaces the v1 ContactsPage): suppliers,
// utilities and other people the venue pays, with their phone (tap to call), e-mail, address and
// notes, and what the venue still owes each one (from Finance → Expenses). New, edit, remove
// (a removed contact stays on its old expenses). Live: `expenses.changed`.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { BookUser, Pencil, Plus, Search, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Input, Select, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { Panel, Table } from '../reports/kit/parts'
import ContactDialog from './ContactDialog'
import { CONTACT_TYPES, filterContacts, owedByContact } from './financeLogic'
const TYPE_TONE = { supplier: 'accent', staff: 'success', utility: 'warning', other: 'neutral' }
export default function ContactsPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [filter, setFilter] = useState({ type: '', q: '' })
const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'remove', contact }
const { data, isPending, refetch } = useLiveQuery({ queryKey: ['contacts'], queryFn: () => client.get('/api/contacts/').then(r => r.data), events: ['expenses.changed'] })
const { data: expenses = [] } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] })
const all = data ?? []
const owed = owedByContact(expenses)
const rows = filterContacts(all, filter)
const set = (k, v) => setFilter(f => ({ ...f, [k]: v }))
const close = () => setDialog(null)
const saved = () => { close(); refetch() }
const remove = useMutation({
mutationFn: c => client.delete(`/api/contacts/${c.id}`),
onSuccess: (_r, c) => { toast.success(t('finance.contacts.removed', { name: c.name })); saved() },
onError: err => toast.error(errorMessage(err, t)),
})
const stop = fn => ev => { ev.stopPropagation(); fn() }
const columns = [
{ key: 'name', label: t('finance.contacts.name'), render: c => (
<span className="grid">
<span className="font-semibold text-ink">{c.name}</span>
{c.notes && <span className="text-caption text-ink-2 line-clamp-1">{c.notes}</span>}
</span>) },
{ key: 'type', label: t('finance.contacts.type'), sort: c => t(`finance.contacts.types.${c.type}`), render: c => <Pill tone={TYPE_TONE[c.type] ?? 'neutral'}>{t(`finance.contacts.types.${c.type}`, { defaultValue: c.type })}</Pill> },
{ key: 'phone', label: t('finance.contacts.phone'), render: c => (c.phone ? <a href={`tel:${c.phone.replace(/\s/g, '')}`} onClick={ev => ev.stopPropagation()} className="text-accent-ink hover:underline">{c.phone}</a> : '') },
{ key: 'email', label: t('finance.contacts.email'), render: c => (c.email ? <a href={`mailto:${c.email}`} onClick={ev => ev.stopPropagation()} className="text-accent-ink hover:underline">{c.email}</a> : '') },
{ key: 'owed', label: t('finance.contacts.owed'), align: 'right', sort: c => owed[c.id]?.due ?? 0, render: c => (owed[c.id]
? <span className="grid"><b className="text-danger-ink">{fmt.formatMoney(owed[c.id].due)}</b><span className="text-caption text-ink-3">{t('finance.contacts.bills', { count: owed[c.id].count })}</span></span> : '') },
{ key: 'actions', label: '', sort: false, render: c => (
<span className="flex justify-end gap-0.5">
<IconButton size="sm" variant="ghost" label={t('finance.contacts.editOf', { name: c.name })} onClick={stop(() => setDialog({ kind: 'edit', contact: c }))}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('finance.contacts.removeOf', { name: c.name })} onClick={stop(() => setDialog({ kind: 'remove', contact: c }))}><Trash2 size={15} /></IconButton>
</span>) },
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="contacts-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('finance.contacts.title')}</h1>
<p className="text-label text-ink-2">{t('finance.contacts.subtitle', { count: all.length })}</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'new' })} data-testid="contact-new">{t('finance.contacts.new')}</Button>
</header>
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-56">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={filter.q} onChange={e => set('q', e.target.value)} placeholder={t('finance.contacts.search')} aria-label={t('finance.contacts.search')} className="pl-9" />
</div>
<Select size="sm" value={filter.type} onChange={e => set('type', e.target.value)} aria-label={t('finance.contacts.type')}
options={[{ value: '', label: t('finance.contacts.allTypes') }, ...CONTACT_TYPES.map(k => ({ value: k, label: t(`finance.contacts.types.${k}`) }))]} />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !all.length ? <EmptyState icon={<BookUser size={28} />} title={t('finance.contacts.none')} description={t('finance.contacts.noneHint')} />
: (
<Panel padded={false}>
<Table columns={columns} rows={rows} onRow={c => setDialog({ kind: 'edit', contact: c })} rowTestId="contact-row"
empty={t('finance.contacts.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} />
</Panel>
)}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ContactDialog contact={dialog.contact} onClose={close} onSaved={saved} />}
{dialog?.kind === 'remove' && (
<Dialog open size="sm" onClose={close} title={t('finance.contacts.removeTitle', { name: dialog.contact.name })} description={t('finance.contacts.removeBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('finance.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.contact)}>{t('finance.contacts.removeYes')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,75 @@
// 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'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select, Textarea } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import ContactDialog from './ContactDialog'
import { CATEGORIES, expenseBody, expenseForm, expenseProblems } from './financeLogic'
export default function ExpenseDialog({ expense, onClose, onSaved }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const qc = useQueryClient()
const isNew = !expense
const [form, setForm] = useState(() => expenseForm(expense, fmt.venueDateKey))
const [tried, setTried] = useState(false)
const [addContact, setAddContact] = useState(false)
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 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 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() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (!wrong.length) save.mutate(expenseBody(form)) }
// 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 ?? '' }] : [])]
return (
<Dialog open size="lg" 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">
<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">
<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>
</div>
<Field label={t('finance.notes')}>
<Textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} />
</Field>
</div>
{addContact && (
<ContactDialog onClose={() => setAddContact(false)}
onSaved={c => { setAddContact(false); qc.invalidateQueries({ queryKey: ['contacts'] }); if (c?.id) set('contact_id', String(c.id)) }} />
)}
</Dialog>
)
}
@@ -0,0 +1,47 @@
// A payment towards an expense (plan step 6.13a): all of what is due (the default) or part of
// it, with a note (how, which receipt). No more than what is due.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input } from '@xenia/ui'
import client from '../../api/client'
import { paymentAmount } from './financeLogic'
export default function ExpensePayDialog({ expense, onClose, onSaved }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const due = expense.due_amount
// In the venue's own way of writing numbers; parseNumber reads it back (1.234,50 or 1,234.50)
const [amount, setAmount] = useState(() => fmt.formatNumber(due, { decimals: 2 }))
const [notes, setNotes] = useState('')
const [tried, setTried] = useState(false)
const value = paymentAmount(amount, due)
const pay = useMutation({
mutationFn: () => client.post(`/api/expenses/${expense.id}/pay`, { amount: value, notes: notes.trim() || null }).then(r => r.data),
onSuccess: e => { toast.success(t(e.status === 'paid' ? 'finance.exp.paidAll' : 'finance.exp.paidPart', { amount: fmt.formatMoney(value), due: fmt.formatMoney(e.due_amount) })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (value != null) pay.mutate() }
return (
<Dialog open size="sm" onClose={onClose} title={t('finance.exp.payTitle')} description={expense.description}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button loading={pay.isPending} onClick={submit} data-testid="expense-pay-save">{t('finance.exp.payYes')}</Button>
</>}>
<div className="grid gap-3" data-testid="expense-pay-dialog">
<p className="flex justify-between rounded-card bg-surface-2 p-3 text-body">
<span className="text-ink-2">{t('finance.exp.due')}</span><b className="tabular-nums text-danger-ink">{fmt.formatMoney(due)}</b>
</p>
<Field label={t('finance.exp.payAmount')} required hint={t('finance.exp.payAmountHint')}
error={tried && value == null ? t('finance.exp.wrong.payment', { due: fmt.formatMoney(due) }) : undefined}>
<Input inputMode="decimal" autoFocus value={amount} onChange={e => setAmount(e.target.value)} data-testid="expense-pay-amount" />
</Field>
<Field label={t('finance.notes')}>
<Input value={notes} onChange={e => setNotes(e.target.value)} placeholder={t('finance.exp.payNoteHint')} />
</Field>
</div>
</Dialog>
)
}
@@ -0,0 +1,170 @@
// Finance → Expenses (plan step 6.13a; replaces the v1 ExpensesPage): what the venue owes and has
// paid. New expense (what, category, supplier, amount, due by), a payment (in parts until it's
// paid), edit, delete; filters (unpaid / status, category, text); what is due and what is late.
// The analysis of a period is Reports → Expenses. Live: `expenses.changed`.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Banknote, Pencil, Plus, Receipt, Search, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Input, Select, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { Panel, Stat, Table } from '../reports/kit/parts'
import ExpenseDialog from './ExpenseDialog'
import ExpensePayDialog from './ExpensePayDialog'
import { CATEGORIES, STATUS_TONE, expenseTotals, filterExpenses, isLate } from './financeLogic'
export default function ExpensesPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [filter, setFilter] = useState({ status: 'unpaid', category: '', q: '' })
const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'pay' | 'view' | 'delete', expense }
const { data, isPending, refetch } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] })
const all = data ?? []
const today = fmt.venueToday()
const rows = filterExpenses(all, filter)
const owed = expenseTotals(all, today, fmt.venueDateKey)
const shown = expenseTotals(rows, today, fmt.venueDateKey)
const set = (k, v) => setFilter(f => ({ ...f, [k]: v }))
const open = (kind, expense = null) => setDialog({ kind, expense })
const close = () => setDialog(null)
const saved = () => { close(); refetch() }
const remove = useMutation({
mutationFn: e => client.delete(`/api/expenses/${e.id}`),
onSuccess: (_r, e) => { toast.success(t('finance.exp.deleted', { what: e.description })); saved() },
onError: err => toast.error(errorMessage(err, t)),
})
const cat = c => t(`finance.categories.${c}`, { defaultValue: c })
const stop = fn => ev => { ev.stopPropagation(); fn() }
const columns = [
{ key: 'description', label: t('finance.exp.what'), render: e => (
<span className="grid">
<span className="font-semibold text-ink">{e.description}</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) },
{ key: 'created_at', label: t('finance.exp.entered'), render: e => fmt.formatDate(e.created_at) },
{ key: 'due_date', label: t('finance.exp.dueBy'), sort: e => e.due_date ?? '', render: e => (e.due_date
? <span className={isLate(e, today, fmt.venueDateKey) ? 'text-danger-ink font-semibold' : ''}>{fmt.formatDate(e.due_date)}</span> : '') },
{ key: 'total_amount', label: t('finance.exp.total'), align: 'right', render: e => fmt.formatMoney(e.total_amount) },
{ key: 'due_amount', label: t('finance.exp.due'), align: 'right', render: e => (e.due_amount > 0 ? <span className="text-danger-ink font-semibold">{fmt.formatMoney(e.due_amount)}</span> : '') },
{ key: 'status', label: t('finance.exp.status'), render: e => (
<span className="flex flex-wrap gap-1">
<Pill tone={STATUS_TONE[e.status] ?? 'neutral'}>{t(`finance.status.${e.status}`, { defaultValue: e.status })}</Pill>
{isLate(e, today, fmt.venueDateKey) && <Pill tone="danger">{t('finance.exp.late')}</Pill>}
</span>) },
{ key: 'actions', label: '', sort: false, render: e => (
<span className="flex justify-end gap-0.5">
{e.status !== 'paid' && <IconButton size="sm" variant="ghost" label={t('finance.exp.payOf', { what: e.description })} onClick={stop(() => open('pay', e))} data-testid="expense-pay"><Banknote size={15} /></IconButton>}
<IconButton size="sm" variant="ghost" label={t('finance.exp.editOf', { what: e.description })} onClick={stop(() => open('edit', e))}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('finance.exp.deleteOf', { what: e.description })} onClick={stop(() => open('delete', e))}><Trash2 size={15} /></IconButton>
</span>) },
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="expenses-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('finance.exp.title')}</h1>
<p className="text-label text-ink-2">{t('finance.exp.subtitle')}</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => open('new')} data-testid="expense-new">{t('finance.exp.new')}</Button>
</header>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('finance.exp.owed')} tone={owed.due ? 'danger' : 'success'} value={fmt.formatMoney(owed.due)}
sub={t('finance.exp.unpaid', { count: owed.unpaid })} testId="expenses-owed" />
<Stat label={t('finance.exp.lateTitle')} tone={owed.late ? 'danger' : undefined} value={fmt.formatNumber(owed.late)} sub={t('finance.exp.lateSub')} />
<Stat label={t('finance.exp.shown')} value={fmt.formatMoney(shown.total)}
sub={t('finance.exp.shownSub', { paid: fmt.formatMoney(shown.paid), count: rows.length })} />
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-56">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={filter.q} onChange={e => set('q', e.target.value)} placeholder={t('finance.exp.search')} aria-label={t('finance.exp.search')} className="pl-9" />
</div>
<Select size="sm" value={filter.status} onChange={e => set('status', e.target.value)} aria-label={t('finance.exp.status')} data-testid="expenses-status"
options={[{ value: '', label: t('finance.exp.all') }, { value: 'unpaid', label: t('finance.exp.unpaidOnly') },
...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))]} />
<Select size="sm" value={filter.category} onChange={e => set('category', e.target.value)} aria-label={t('finance.exp.category')}
options={[{ value: '', label: t('finance.exp.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: cat(c) }))]} />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !all.length ? <EmptyState icon={<Receipt size={28} />} title={t('finance.exp.none')} description={t('finance.exp.noneHint')} />
: (
<Panel padded={false}>
<Table columns={columns} rows={rows} onRow={e => open('view', e)} rowTestId="expense-row" empty={t('finance.exp.noMatch')}
initialSort={{ key: 'created_at', dir: 'desc' }} />
</Panel>
)}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ExpenseDialog expense={dialog.expense} onClose={close} onSaved={saved} />}
{dialog?.kind === 'pay' && <ExpensePayDialog expense={dialog.expense} onClose={close} onSaved={saved} />}
{dialog?.kind === 'view' && (
<ExpenseView expense={dialog.expense} cat={cat} onClose={close}
onPay={() => open('pay', dialog.expense)} onEdit={() => open('edit', dialog.expense)} />
)}
{dialog?.kind === 'delete' && (
<Dialog open size="sm" onClose={close} title={t('finance.exp.deleteTitle', { what: dialog.expense.description })}
description={dialog.expense.payments?.length ? t('finance.exp.deleteBodyPaid', { count: dialog.expense.payments.length }) : t('finance.exp.deleteBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('finance.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.expense)} data-testid="expense-delete-confirm">{t('finance.exp.deleteYes')}</Button>
</>} />
)}
</div>
)
}
/** One expense: amounts, who entered it, notes and every payment. */
function ExpenseView({ expense: e, cat, onClose, onPay, onEdit }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
return (
<Dialog open size="md" onClose={onClose} title={e.description}
description={[cat(e.category), e.contact_name, t('finance.exp.enteredBy', { date: fmt.formatDate(e.created_at), name: e.created_by_name ?? '' })].filter(Boolean).join(' · ')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button variant="secondary" icon={<Pencil size={14} />} onClick={onEdit}>{t('finance.exp.edit')}</Button>
{e.status !== 'paid' && <Button icon={<Banknote size={14} />} onClick={onPay}>{t('finance.exp.pay')}</Button>}
</>}>
<div className="grid gap-3 text-body" data-testid="expense-view">
<div className="grid grid-cols-3 gap-2">
<Figure label={t('finance.exp.total')} value={fmt.formatMoney(e.total_amount)} />
<Figure label={t('finance.exp.paid')} value={fmt.formatMoney(e.paid_amount)} tone="text-success-ink" />
<Figure label={t('finance.exp.due')} value={fmt.formatMoney(e.due_amount)} tone={e.due_amount > 0 ? 'text-danger-ink' : undefined} />
</div>
{e.due_date && <p className="text-label text-ink-2">{t('finance.exp.dueOn', { date: fmt.formatDate(e.due_date) })}</p>}
{e.notes && <p className="text-label text-ink-2 whitespace-pre-wrap">{e.notes}</p>}
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.payments')}</h3>
{e.payments?.length ? (
<ul className="divide-y divide-line">
{e.payments.map(p => (
<li key={p.id} className="py-1.5 flex justify-between gap-3 text-label">
<span>{fmt.formatDateTime(p.paid_at, 'datetimeShort')}{p.paid_by_name ? ` · ${p.paid_by_name}` : ''}{p.notes ? ` · ${p.notes}` : ''}</span>
<b className="tabular-nums text-success-ink">{fmt.formatMoney(p.amount)}</b>
</li>
))}
</ul>
) : <p className="text-label text-ink-3">{t('finance.exp.noPayments')}</p>}
</div>
</Dialog>
)
}
function Figure({ label, value, tone }) {
return (
<div className="rounded-card bg-surface-2 p-3 grid gap-0.5 text-center">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{label}</span>
<span className={`text-body font-semibold tabular-nums ${tone ?? 'text-ink'}`}>{value}</span>
</div>
)
}
@@ -0,0 +1,85 @@
// A tab's payment and forgiving it (plan step 6.13a). A payment: all of what is owed (the
// default) or part, cash / card / other, a note; no more than what is owed. Forgiving writes off
// what is owed, with a reason, and can't be undone.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input } from '@xenia/ui'
import client from '../../api/client'
import { PAY_METHODS, paymentAmount } from './financeLogic'
export default function TabDialogs({ dialog, onClose, onSaved }) {
if (dialog?.kind === 'pay') return <PayDialog tab={dialog.tab} onClose={onClose} onSaved={onSaved} />
if (dialog?.kind === 'forgive') return <ForgiveDialog tab={dialog.tab} onClose={onClose} onSaved={onSaved} />
return null
}
function PayDialog({ tab, onClose, onSaved }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [amount, setAmount] = useState(() => fmt.formatNumber(tab.balance, { decimals: 2 }))
const [method, setMethod] = useState('cash')
const [notes, setNotes] = useState('')
const [tried, setTried] = useState(false)
const value = paymentAmount(amount, tab.balance)
const pay = useMutation({
mutationFn: () => client.post(`/api/tabs/${tab.id}/pay`, { amount: value, payment_method: method, notes: notes.trim() || null }).then(r => r.data),
onSuccess: r => { toast.success(t(r.balance > 0.005 ? 'finance.tabs.paidPart' : 'finance.tabs.paidAll', { amount: fmt.formatMoney(value), balance: fmt.formatMoney(r.balance) })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (value != null) pay.mutate() }
return (
<Dialog open size="sm" onClose={onClose} title={t('finance.tabs.payTitle')} description={tab.customer_name}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button loading={pay.isPending} onClick={submit} data-testid="tab-pay-save">{t('finance.tabs.payYes')}</Button>
</>}>
<div className="grid gap-3" data-testid="tab-pay-dialog">
<p className="flex justify-between rounded-card bg-surface-2 p-3 text-body">
<span className="text-ink-2">{t('finance.tabs.balance')}</span><b className="tabular-nums text-danger-ink">{fmt.formatMoney(tab.balance)}</b>
</p>
<Field label={t('finance.tabs.payAmount')} required
error={tried && value == null ? t('finance.tabs.wrongPayment', { balance: fmt.formatMoney(tab.balance) }) : undefined}>
<Input inputMode="decimal" autoFocus value={amount} onChange={e => setAmount(e.target.value)} data-testid="tab-pay-amount" />
</Field>
<Field label={t('finance.tabs.method')}>
<span className="grid grid-cols-3 gap-1" role="radiogroup" aria-label={t('finance.tabs.method')}>
{PAY_METHODS.map(m => (
<Button key={m} size="sm" variant={method === m ? 'primary' : 'secondary'} role="radio" aria-checked={method === m} onClick={() => setMethod(m)}>
{t(`finance.tabs.methods.${m}`)}
</Button>
))}
</span>
</Field>
<Field label={t('finance.notes')}>
<Input value={notes} onChange={e => setNotes(e.target.value)} />
</Field>
</div>
</Dialog>
)
}
function ForgiveDialog({ tab, onClose, onSaved }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [reason, setReason] = useState('')
const forgive = useMutation({
mutationFn: () => client.post(`/api/tabs/${tab.id}/forgive`, { reason: reason.trim() || null }),
onSuccess: () => { toast.success(t('finance.tabs.forgiven', { name: tab.customer_name, amount: fmt.formatMoney(tab.balance) })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
return (
<Dialog open size="sm" onClose={onClose} title={t('finance.tabs.forgiveTitle', { name: tab.customer_name })}
description={t('finance.tabs.forgiveBody', { amount: fmt.formatMoney(tab.balance) })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button variant="danger" loading={forgive.isPending} onClick={() => forgive.mutate()} data-testid="tab-forgive-confirm">{t('finance.tabs.forgiveYes')}</Button>
</>}>
<Field label={t('finance.tabs.reason')}>
<Input value={reason} autoFocus onChange={e => setReason(e.target.value)} placeholder={t('finance.tabs.reasonHint')} />
</Field>
</Dialog>
)
}
@@ -0,0 +1,164 @@
// Finance → Tabs, pay later (plan step 6.13a; replaces the v1 TabsPage): what each regular
// customer owes. Lines go on a customer's tab from an order (the order's "Put on tab": the tab
// opens by itself). Here: open tabs (who owes most first) or settled ones, search, each tab's
// charges and payments; a payment (cash, card or other; part or all), close one that owes
// nothing, forgive what is owed (with a reason; it can't be undone). Live: `tabs.changed`.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Banknote, CheckCircle2, ChevronDown, CreditCard, HandHeart, Search } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Input, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { Stat } from '../reports/kit/parts'
import TabDialogs from './TabDialogs'
import { TAB_TONE, daysBetween, filterTabs, tabActions, tabTotals } from './financeLogic'
export default function TabsPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [view, setView] = useState('open') // 'open' | 'settled'
const [q, setQ] = useState('')
const [expanded, setExpanded] = useState(null)
const [dialog, setDialog] = useState(null) // { kind: 'pay' | 'forgive', id }
const live = { events: ['tabs.changed'] }
const openQ = useLiveQuery({ queryKey: ['tabs', 'open'], queryFn: () => client.get('/api/tabs/').then(r => r.data), ...live })
const settledQ = useLiveQuery({ queryKey: ['tabs', 'settled'], queryFn: () => client.get('/api/tabs/', { params: { tab_status: 'settled' } }).then(r => r.data), ...live, enabled: view === 'settled' })
const current = view === 'open' ? openQ : settledQ
const rows = filterTabs(current.data ?? [], q)
const totals = tabTotals(openQ.data ?? [])
// The dialogs read the tab from the current list (a payment just made may not be in the row clicked)
const tabNow = dialog && (openQ.data ?? []).find(x => x.id === dialog.id)
const refresh = () => { openQ.refetch(); if (view === 'settled') settledQ.refetch() }
const closeTab = useMutation({
mutationFn: tab => client.post(`/api/tabs/${tab.id}/close`, {}),
onSuccess: (_r, tab) => { toast.success(t('finance.tabs.closed', { name: tab.customer_name })); refresh() },
onError: err => toast.error(errorMessage(err, t)),
})
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="tabs-page">
<div className="max-w-4xl mx-auto grid gap-4">
<header>
<h1 className="text-title font-semibold text-ink">{t('finance.tabs.title')}</h1>
<p className="text-label text-ink-2">{t('finance.tabs.subtitle')}</p>
</header>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('finance.tabs.owed')} tone={totals.owed ? 'danger' : 'success'} value={fmt.formatMoney(totals.owed)}
sub={t('finance.tabs.openCount', { count: totals.count })} testId="tabs-owed" />
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="flex gap-1" role="tablist">
{['open', 'settled'].map(k => (
<Button key={k} size="sm" variant={view === k ? 'primary' : 'ghost'} role="tab" aria-selected={view === k}
onClick={() => { setView(k); setExpanded(null) }} data-testid={`tabs-view-${k}`}>{t(`finance.tabs.views.${k}`)}</Button>
))}
</span>
<div className="relative flex-1 min-w-56">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('finance.tabs.search')} aria-label={t('finance.tabs.search')} className="pl-9" />
</div>
</div>
{current.isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !rows.length ? (
<EmptyState icon={<CreditCard size={28} />} title={q ? t('finance.tabs.noMatch') : t(`finance.tabs.none.${view}`)}
description={!q && view === 'open' ? t('finance.tabs.noneHint') : undefined} />
) : (
<ul className="grid gap-2">
{rows.map(tab => (
<TabCard key={tab.id} tab={tab} open={expanded === tab.id} onToggle={() => setExpanded(e => (e === tab.id ? null : tab.id))}
onPay={() => setDialog({ kind: 'pay', id: tab.id })} onForgive={() => setDialog({ kind: 'forgive', id: tab.id })}
onClose={() => closeTab.mutate(tab)} closing={closeTab.isPending && closeTab.variables?.id === tab.id} />
))}
</ul>
)}
</div>
<TabDialogs dialog={tabNow && !openQ.isFetching ? { kind: dialog.kind, tab: tabNow } : null} onClose={() => setDialog(null)} onSaved={() => { setDialog(null); refresh() }} />
</div>
)
}
function TabCard({ tab, open, onToggle, onPay, onForgive, onClose, closing }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const can = tabActions(tab)
const days = daysBetween(fmt.venueDateKey(tab.opened_at), fmt.venueToday())
const method = m => (m ? t(`finance.tabs.methods.${m}`, { defaultValue: m }) : '')
return (
<li className="rounded-card border border-line bg-surface shadow-raised overflow-hidden" data-testid="tab-card">
<button type="button" onClick={onToggle} aria-expanded={open} className="w-full px-4 py-3 flex flex-wrap items-center gap-3 text-left hover:bg-surface-2">
<ChevronDown size={16} className={cx('text-ink-3 transition-transform', open && 'rotate-180')} aria-hidden="true" />
<span className="grid flex-1 min-w-48">
<span className="text-body font-semibold text-ink">{tab.customer_name}</span>
<span className="text-caption text-ink-2">
{tab.status === 'open'
? t('finance.tabs.openSince', { date: fmt.formatDate(tab.opened_at), count: days })
: t(`finance.tabs.settledOn.${tab.status}`, { date: fmt.formatDate(tab.closed_at) })}
{tab.customer_phone ? ` · ${tab.customer_phone}` : ''}
</span>
</span>
<span className="flex items-center gap-2">
<span className={cx('text-title font-semibold tabular-nums', tab.balance > 0.005 ? 'text-danger-ink' : 'text-ink-2')} data-testid="tab-balance">{fmt.formatMoney(tab.balance)}</span>
<Pill tone={TAB_TONE[tab.status] ?? 'neutral'}>{t(`finance.tabs.status.${tab.status}`, { defaultValue: tab.status })}</Pill>
</span>
</button>
{open && (
<div className="border-t border-line">
<div className="grid grid-cols-3 divide-x divide-line bg-surface-2 text-center">
{[['charged', tab.total_charged, 'text-ink'], ['paid', tab.total_paid, 'text-success-ink'], ['balance', tab.balance, tab.balance > 0.005 ? 'text-danger-ink' : 'text-ink']].map(([k, v, tone]) => (
<span key={k} className="p-2 grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`finance.tabs.${k}`)}</span>
<span className={cx('text-body font-semibold tabular-nums', tone)}>{fmt.formatMoney(v)}</span>
</span>
))}
</div>
<div className="grid gap-3 p-4 sm:grid-cols-2">
<section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('finance.tabs.charges')}</h3>
{tab.entries.length ? (
<ul className="divide-y divide-line text-label">
{tab.entries.map(e => (
<li key={e.id} className="py-1.5 flex justify-between gap-3">
<span className="grid">
<span className="text-ink">{e.description || t('finance.tabs.charge', { id: e.id })}</span>
<span className="text-caption text-ink-3">{fmt.formatDateTime(e.created_at, 'datetimeShort')}{e.created_by_name ? ` · ${e.created_by_name}` : ''}{e.order_id ? ` · ${t('finance.tabs.order', { id: e.order_id })}` : ''}</span>
</span>
<b className="tabular-nums">{fmt.formatMoney(e.amount)}</b>
</li>
))}
</ul>
) : <p className="text-label text-ink-3">{t('finance.tabs.noCharges')}</p>}
</section>
<section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('finance.tabs.payments')}</h3>
{tab.payments.length ? (
<ul className="divide-y divide-line text-label">
{tab.payments.map(p => (
<li key={p.id} className="py-1.5 flex justify-between gap-3">
<span className="grid">
<span className="text-ink">{[method(p.payment_method), p.notes].filter(Boolean).join(' · ')}</span>
<span className="text-caption text-ink-3">{fmt.formatDateTime(p.created_at, 'datetimeShort')}{p.received_by_name ? ` · ${p.received_by_name}` : ''}</span>
</span>
<b className="tabular-nums text-success-ink">{fmt.formatMoney(p.amount)}</b>
</li>
))}
</ul>
) : <p className="text-label text-ink-3">{t('finance.tabs.noPayments')}</p>}
</section>
</div>
{tab.status !== 'open' && tab.notes && <p className="px-4 pb-3 text-label text-ink-2">{tab.notes}</p>}
{(can.pay || can.close || can.forgive) && (
<div className="flex flex-wrap gap-2 px-4 pb-4">
{can.pay && <Button icon={<Banknote size={15} />} onClick={onPay} data-testid="tab-pay">{t('finance.tabs.pay')}</Button>}
{can.close && <Button icon={<CheckCircle2 size={15} />} loading={closing} onClick={onClose} data-testid="tab-close">{t('finance.tabs.close')}</Button>}
{can.forgive && <Button variant="ghost" icon={<HandHeart size={15} />} onClick={onForgive} className="ml-auto" data-testid="tab-forgive">{t('finance.tabs.forgive')}</Button>}
</div>
)}
</div>
)}
</li>
)
}
@@ -0,0 +1,138 @@
// The rules of Finance → Expenses, the supplier book and Finance → Tabs (plan step 6.13a), kept
// out of the components so they are unit-tested (tests/finance.test.mjs). The backend checks the
// same things (routers/expenses.py, routers/tabs.py); these give the message before saving.
import { parseNumber } from '@xenia/i18n/number' // plain JS: Node tests import this file
// As routers/expenses.py CATEGORIES / CONTACT_TYPES and routers/tabs.py METHODS
export const CATEGORIES = ['supplier', 'utilities', 'rent', 'maintenance', 'staff', 'equipment', 'other']
export const CONTACT_TYPES = ['supplier', 'staff', 'utility', 'other']
export const PAY_METHODS = ['cash', 'card', 'other']
export const STATUS_TONE = { paid: 'success', partial: 'warning', due: 'danger' }
export const TAB_TONE = { open: 'danger', closed: 'success', forgiven: 'neutral' }
const money = text => parseNumber(String(text ?? ''), { decimals: 2, allowNegative: false })
const cents = v => Math.round(v * 100)
// ── Expenses ─────────────────────────────────────────────────────────────────
/** The dialog's fields for a new expense or an existing one (amounts as typed text; the due
* date as the venue date 'YYYY-MM-DD' through `dateKey`, useFormat().venueDateKey). */
export function expenseForm(e, dateKey = d => d) {
return {
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 ?? '',
}
}
/** Which fields are wrong: description, total_amount (none, zero, or less than what was paid). */
export function expenseProblems(form, paid = 0) {
const out = []
if (!form.description.trim()) out.push('description')
const 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). */
export function expenseBody(form) {
return {
description: form.description.trim(), category: form.category,
contact_id: form.contact_id ? Number(form.contact_id) : null,
total_amount: money(form.total_amount),
due_date: form.due_date || null, notes: form.notes.trim() || null,
}
}
/** A payment's amount: a number above zero and no more than what is due, or null. */
export function paymentAmount(text, due) {
const v = money(text)
return v > 0 && cents(v) <= cents(due) ? v : null
}
/** Is it late? Due before today (venue dates, 'YYYY-MM-DD') and not paid. */
export function isLate(expense, today, dateKey) {
return expense.status !== 'paid' && !!expense.due_date && dateKey(expense.due_date) < today
}
/** The page's list after its filters: status ('' | 'unpaid' | due | partial | paid), category, text. */
export function filterExpenses(list, { status = '', category = '', q = '' } = {}) {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean)
return list.filter(e => (!status || (status === 'unpaid' ? e.status !== 'paid' : e.status === status))
&& (!category || e.category === category)
&& words.every(w => `${e.description} ${e.contact_name ?? ''} ${e.notes ?? ''}`.toLowerCase().includes(w)))
}
/** Totals of a list: spent, paid, due, how many unpaid, how many late. */
export function expenseTotals(list, today, dateKey) {
const sum = k => Math.round(list.reduce((s, e) => s + (e[k] ?? 0), 0) * 100) / 100
return {
total: sum('total_amount'), paid: sum('paid_amount'), due: sum('due_amount'),
unpaid: list.filter(e => e.status !== 'paid').length,
late: list.filter(e => isLate(e, today, dateKey)).length,
}
}
/** What is owed to each supplier: { [contact_id]: { due, count } } from the expenses. */
export function owedByContact(expenses) {
const out = {}
for (const e of expenses) {
if (!e.contact_id || !(e.due_amount > 0)) continue
const o = (out[e.contact_id] ??= { due: 0, count: 0 })
o.due = Math.round((o.due + e.due_amount) * 100) / 100
o.count += 1
}
return out
}
// ── Suppliers and contacts ───────────────────────────────────────────────────
export function contactForm(c) {
return { name: c?.name ?? '', type: c?.type ?? 'supplier', phone: c?.phone ?? '', email: c?.email ?? '', address: c?.address ?? '', notes: c?.notes ?? '' }
}
export function contactProblems(form) {
const out = []
if (!form.name.trim()) out.push('name')
if (form.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) out.push('email')
return out
}
/** Empty fields are sent as null, so clearing a phone number clears it. */
export function contactBody(form) {
const v = k => form[k].trim() || null
return { name: form.name.trim(), type: form.type, phone: v('phone'), email: v('email'), address: v('address'), notes: v('notes') }
}
export function filterContacts(list, { type = '', q = '' } = {}) {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean)
return list.filter(c => (!type || c.type === type)
&& words.every(w => `${c.name} ${c.phone ?? ''} ${c.email ?? ''} ${c.notes ?? ''}`.toLowerCase().includes(w)))
}
// ── Tabs ─────────────────────────────────────────────────────────────────────
/** Whole venue days a tab has been open ('YYYY-MM-DD' keys). */
export function daysBetween(fromKey, toKey) {
return Math.max(0, Math.round((Date.parse(`${toKey}T00:00:00Z`) - Date.parse(`${fromKey}T00:00:00Z`)) / 86_400_000))
}
/** What can be done with a tab now. */
export function tabActions(tab) {
const open = tab.status === 'open'
return {
pay: open && tab.balance > 0.005,
close: open && tab.balance <= 0.005 && tab.entries.length > 0,
forgive: open && tab.balance > 0.005,
}
}
export function filterTabs(list, q = '') {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean)
return list.filter(tab => words.every(w => `${tab.customer_name ?? ''} ${tab.customer_phone ?? ''}`.toLowerCase().includes(w)))
}
export function tabTotals(open) {
return { owed: Math.round(open.reduce((s, tab) => s + tab.balance, 0) * 100) / 100, count: open.length }
}
@@ -1 +0,0 @@
export { default } from '../ExpensesPage'
@@ -1 +0,0 @@
export { default } from '../TabsPage'
@@ -6,7 +6,7 @@ import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react'
import { useCan } from '@xenia/access'
import { useCan, useModule } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
@@ -21,6 +21,8 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
const { t } = useTranslation('manager')
const { formatMoney, formatTime } = useFormat()
const canDiscount = useCan('pricing.discounts.apply')
const tabsOn = useModule('tabs')
const canTab = useCan('tabs.manage') && tabsOn // what the tab route checks (6.13a)
const [selected, setSelected] = useState([])
const [cancelling, setCancelling] = useState(false)
const [discounting, setDiscounting] = useState(false)
@@ -94,7 +96,7 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
<div className="sticky bottom-0 flex flex-wrap items-center gap-2 px-4 py-3 border-t border-line bg-surface-2" data-testid="line-actions">
<span className="flex-1 text-label text-ink-2">{t('orders.lines.picked', { count: picked.length, amount: formatMoney(amount) })}</span>
<Button size="sm" variant="ghost" onClick={() => setSelected([])}>{t('orders.lines.clear')}</Button>
{order.customer_id && <Button size="sm" variant="secondary" icon={<Receipt size={14} />} loading={toTab.isPending} onClick={() => toTab.mutate()}>{t('orders.lines.toTab')}</Button>}
{order.customer_id && canTab && <Button size="sm" variant="secondary" icon={<Receipt size={14} />} loading={toTab.isPending} onClick={() => toTab.mutate()}>{t('orders.lines.toTab')}</Button>}
{canDiscount && <Button size="sm" variant="secondary" icon={<Percent size={14} />} onClick={() => setDiscounting(true)} data-testid="lines-discount">{t('orders.lines.discount')}</Button>}
<Button size="sm" variant="danger" icon={<Ban size={14} />} onClick={() => setCancelling(true)} data-testid="lines-cancel">{t('orders.lines.cancel')}</Button>
<Button size="sm" icon={<CreditCard size={14} />} onClick={() => onPay(picked, amount, () => setSelected([]))} data-testid="lines-pay">{t('orders.lines.pay')}</Button>
@@ -1,6 +1,7 @@
// Reports → Expenses (plan step 6.12c; replaces the v1 expenses report): what the venue spent in
// a period (by the day each expense was entered), paid and still due; split by category or by
// supplier; every expense, a tap shows its payments. Entering expenses is Finance → Expenses.
// The period is filtered by the server (venue dates, 6.13a); categories / statuses are `finance.*` texts.
import { useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Select } from '@xenia/ui'
@@ -11,9 +12,8 @@ import { BarList } from '../kit/charts'
import { Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts'
import { PeriodPicker } from '../kit/Period'
import { defaultPeriod } from '../kit/reportLogic'
import { CATEGORIES, STATUS_TONE } from '../../finance/financeLogic'
const STATUS_TONE = { paid: 'success', partial: 'warning', due: 'danger' }
const CATEGORIES = ['supplier', 'utilities', 'rent', 'maintenance', 'staff', 'equipment', 'other'] // as Finance → Expenses saves them (models/expenses.py)
export default function ExpensesReport() {
const { t } = useTranslation('manager')
@@ -28,11 +28,10 @@ function Expenses() {
const [category, setCategory] = useState('')
const [split, setSplit] = useState('category')
const [open, setOpen] = useState(null)
const params = { ...(status ? { status } : {}), ...(category ? { category } : {}) }
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-expenses', params], queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data) })
const catName = c => t(`reports.exp.categories.${c}`, { defaultValue: c })
const inPeriod = e => { const d = fmt.venueDateKey(e.created_at); return (!period.from || d >= period.from) && (!period.to || d <= period.to) }
const rows = (data ?? []).filter(inPeriod)
const params = { ...(period.from ? { from: period.from } : {}), ...(period.to ? { to: period.to } : {}), ...(status ? { status } : {}), ...(category ? { category } : {}) }
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-expenses', params], queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data), events: ['expenses.changed'] })
const catName = c => t(`finance.categories.${c}`, { defaultValue: c })
const rows = data ?? []
const sum = k => rows.reduce((s, e) => s + (e[k] ?? 0), 0)
const groups = Object.values(rows.reduce((m, e) => {
const k = split === 'category' ? e.category : (e.contact_name || t('reports.exp.noSupplier'))
@@ -48,13 +47,13 @@ function Expenses() {
{ key: 'contact_name', label: t('reports.exp.supplier'), render: e => e.contact_name || '' },
{ key: 'total_amount', label: t('reports.exp.total'), align: 'right', render: e => fmt.formatMoney(e.total_amount) },
{ key: 'due_amount', label: t('reports.exp.due'), align: 'right', render: e => (e.due_amount ? <span className="text-danger-ink">{fmt.formatMoney(e.due_amount)}</span> : '') },
{ key: 'status', label: t('reports.status'), render: e => <Pill tone={STATUS_TONE[e.status] ?? 'neutral'}>{t(`reports.exp.status.${e.status}`, { defaultValue: e.status })}</Pill> },
{ key: 'status', label: t('reports.status'), render: e => <Pill tone={STATUS_TONE[e.status] ?? 'neutral'}>{t(`finance.status.${e.status}`, { defaultValue: e.status })}</Pill> },
]
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} allowDay={false} right={<span className="flex gap-2 items-end">
<Select size="sm" value={status} onChange={e => setStatus(e.target.value)} aria-label={t('reports.status')}
options={[{ value: '', label: t('reports.store.anyStatus') }, ...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`reports.exp.status.${s}`) }))]} />
options={[{ value: '', label: t('reports.store.anyStatus') }, ...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))]} />
<Select size="sm" value={category} onChange={e => setCategory(e.target.value)} aria-label={t('reports.prod.category')}
options={[{ value: '', label: t('reports.prod.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: catName(c) }))]} />
</span>} />
+3 -3
View File
@@ -41,15 +41,15 @@ export const NAV = [
{
group: 'crm', icon: BookUser, label: 'nav.crm',
children: [
{ to: '/crm/contacts', icon: BookUser, label: 'nav.contacts', module: 'expenses', perm: DASH },
{ to: '/crm/contacts', icon: BookUser, label: 'nav.contacts', module: 'expenses', perm: 'expenses.manage' },
{ to: '/crm/customers', icon: Users, label: 'nav.customers', module: 'crm', perm: DASH },
],
},
{
group: 'financials', icon: Receipt, label: 'nav.finance',
children: [
{ to: '/financials/expenses', icon: Receipt, label: 'nav.expenses', module: 'expenses', perm: DASH },
{ to: '/financials/tabs', icon: CreditCard, label: 'nav.tabs', module: 'tabs', perm: DASH },
{ to: '/financials/expenses', icon: Receipt, label: 'nav.expenses', module: 'expenses', perm: 'expenses.manage' },
{ to: '/financials/tabs', icon: CreditCard, label: 'nav.tabs', module: 'tabs', perm: 'tabs.manage' },
],
},
],