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 (
{isNew ? 'Νέο Έξοδο' : 'Επεξεργασία Εξόδου'}
)
}
// ── 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 (
Καταγραφή Πληρωμής
{expense.description}
)
}
// ── 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 (
<>
|
{expense.description}
{expense.contact_name && {expense.contact_name} }
|
{catLabel} |
{fmt(expense.total_amount)} |
{expense.paid_amount > 0 ? fmt(expense.paid_amount) : '—'} |
{expense.due_amount > 0 ? fmt(expense.due_amount) : '—'} |
{sc.label}
|
{expense.due_date ? fmtDate(expense.due_date) : '—'} |
{expense.status !== 'paid' && (
)}
|
{isExpanded && (
{expense.notes && (
📝 {expense.notes}
)}
Καταχωρήθηκε από {expense.created_by_name} · {fmtDate(expense.created_at)}
{expense.payments.length > 0 && (
Ιστορικό Πληρωμών
{expense.payments.map(p => (
{p.paid_by_name} · {fmtDateTime(p.paid_at)}
{p.notes && — {p.notes}}
{fmt(p.amount)}
))}
)}
{expense.payments.length === 0 && expense.status === 'due' && (
Δεν έχουν καταγραφεί πληρωμές.
)}
|
)}
>
)
}
// ── 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 (
{/* Header */}
{pendingCount} εκκρεμή · Σύνολο οφειλών: 0 ? '#dc2626' : '#16a34a' }}>{fmt(totalDue)}
{/* Filters */}
{/* Status filter */}
{[['all', 'Όλα'], ['due', 'Οφείλεται'], ['partial', 'Μερική'], ['paid', 'Πληρώθηκε']].map(([v, l]) => (
))}
{/* Category filter */}
{/* Table */}
{isLoading &&
Φόρτωση…
}
{!isLoading && expenses.length === 0 && (
Δεν βρέθηκαν έξοδα για τα επιλεγμένα φίλτρα.
)}
{expenses.length > 0 && (
{['Περιγραφή', 'Κατηγορία', 'Σύνολο', 'Πληρωμένο', 'Εκκρεμεί', 'Κατάσταση', 'Ημ/νία', ''].map(h => (
| {h} |
))}
{expenses.map(e => (
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) }}
/>
))}
)}
{/* Expense create/edit modal */}
{modal?.type === 'expense' && (
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' && (
setModal(null)}
isPending={payExpense.isPending}
onPay={(amount, notes) => payExpense.mutate({ id: modal.expense.id, amount, notes })}
/>
)}
)
}