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 (
{isNew ? 'Νέα Επαφή' : 'Επεξεργασία Επαφής'}
)
}
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 (
{/* Header */}
Επαφές / Προμηθευτές
{contacts.length} ενεργές επαφές
{/* Table */}
{isLoading &&
Φόρτωση…
}
{!isLoading && contacts.length === 0 && (
Δεν υπάρχουν επαφές ακόμα. Προσθέστε τον πρώτο προμηθευτή.
)}
{contacts.length > 0 && (
{['Όνομα', 'Τύπος', 'Τηλέφωνο', 'Email', ''].map(h => (
| {h} |
))}
{contacts.map((c, i) => {
const tc = TYPE_COLORS[c.type] || TYPE_COLORS.other
return (
|
{c.name}
{c.notes && {c.notes.slice(0, 60)}{c.notes.length > 60 ? '…' : ''} }
|
{TYPE_LABELS[c.type] || c.type}
|
{c.phone || '—'} |
{c.email || '—'} |
|
)
})}
)}
{modal && (
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,
})}
/>
)}
)
}