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 REASONS = [
{ id: 'kitchen_error', label: 'Λάθος κουζίνας', color: '#dc2626' },
{ id: 'dropped', label: 'Έπεσε', color: '#d97706' },
{ id: 'expired', label: 'Έληξε', color: '#7c3aed' },
{ id: 'other', label: 'Άλλο', color: '#6b7280' },
]
// ── 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' })
}
// ── Log form ──────────────────────────────────────────────────────────────────
function LogForm({ products, onLog, isPending }) {
const [productId, setProductId] = useState('')
const [qty, setQty] = useState('1')
const [reason, setReason] = useState('kitchen_error')
const [notes, setNotes] = useState('')
const canLog = productId && parseFloat(qty) > 0
function submit() {
if (!canLog) return
onLog({
product_id: Number(productId),
quantity: parseFloat(qty),
reason,
reason_notes: notes.trim() || null,
})
setProductId('')
setQty('1')
setReason('kitchen_error')
setNotes('')
}
const inputStyle = {
width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit', background: 'white',
boxSizing: 'border-box',
}
return (
Καταγραφή Απόβλητου
{REASONS.map(r => (
))}
setNotes(e.target.value)}
placeholder="π.χ. Ο πελάτης επέστρεψε ελαττωματικό…" />
)
}
// ── Waste entry row ───────────────────────────────────────────────────────────
function WasteRow({ entry, canDelete, onDelete }) {
const reasonCfg = REASONS.find(r => r.id === entry.reason) || { label: entry.reason, color: '#6b7280' }
return (
{entry.product_name}
×{entry.quantity}
{reasonCfg.label}
{fmtDateTime(entry.logged_at)} · {entry.logged_by_name}
{entry.reason_notes && — {entry.reason_notes}}
{entry.total_cost != null ? (
{fmt(entry.total_cost)}
) : (
χωρίς κόστος
)}
{entry.unit_cost_snapshot != null && (
{fmt(entry.unit_cost_snapshot)}/τεμ.
)}
{canDelete && (
)}
)
}
// ── Main page ─────────────────────────────────────────────────────────────────
export default function WastePage() {
const qc = useQueryClient()
const [showHistory, setShowHistory] = useState(false)
const [histFrom, setHistFrom] = useState(() => new Date().toISOString().slice(0, 10))
const [histTo, setHistTo] = useState(() => new Date().toISOString().slice(0, 10))
const { data: productsData = [] } = useQuery({
queryKey: ['meta-products'],
queryFn: () => client.get('/api/reports/meta/products').then(r => r.data.products),
staleTime: 5 * 60_000,
})
const { data: bdData } = useQuery({
queryKey: ['business-day'],
queryFn: () => client.get('/api/business-day/current').then(r => r.data),
staleTime: 30_000,
})
const activeDayId = bdData?.id ?? null
// Today's entries — scoped to active business day (or all if no active day)
const { data: todayData } = useQuery({
queryKey: ['waste-today', activeDayId],
queryFn: () => client.get('/api/waste/', { params: activeDayId ? { business_day_id: activeDayId } : {} }).then(r => r.data),
staleTime: 15_000,
})
// Historical entries
const { data: histData, refetch: refetchHist } = useQuery({
queryKey: ['waste-history', histFrom, histTo],
queryFn: () => client.get('/api/waste/', { params: { from: histFrom + 'T00:00:00', to: histTo + 'T23:59:59' } }).then(r => r.data),
staleTime: 30_000,
enabled: showHistory,
})
const todayEntries = todayData?.entries || []
const histEntries = histData?.entries || []
const todayCost = todayEntries.reduce((s, e) => s + (e.total_cost || 0), 0)
const todayCount = todayEntries.length
const logWaste = useMutation({
mutationFn: (body) => client.post('/api/waste/', body),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['waste-today'] })
qc.invalidateQueries({ queryKey: ['waste-history'] })
toast.success('Καταγράφηκε')
},
onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
})
const deleteWaste = useMutation({
mutationFn: (id) => client.delete(`/api/waste/${id}`),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['waste-today'] })
qc.invalidateQueries({ queryKey: ['waste-history'] })
toast.success('Διαγράφηκε')
},
onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
})
return (
{/* Header */}
Σήμερα: {todayCount} καταχωρήσεις
{todayCost > 0 && · εκτιμώμενο κόστος {todayCost.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €}
{/* Log form */}
logWaste.mutate(body)} isPending={logWaste.isPending} />
{/* Today's entries */}
{activeDayId ? 'Σήμερα' : 'Τελευταίες καταχωρήσεις'}
{todayEntries.length === 0 ? (
Καμία καταχώρηση ακόμα.
) : (
{todayEntries.map(e => (
deleteWaste.mutate(id)} />
))}
)}
{/* History toggle */}
{showHistory && (
setHistFrom(e.target.value)}
style={{ padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, outline: 'none' }} />
setHistTo(e.target.value)}
style={{ padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, outline: 'none' }} />
{histEntries.length === 0 ? (
Δεν βρέθηκαν καταχωρήσεις.
) : (
{histEntries.map(e => (
{}} />
))}
{histEntries.length} καταχωρήσεις · εκτιμώμενο κόστος{' '}
{histEntries.reduce((s, e) => s + (e.total_cost || 0), 0).toLocaleString('el-GR', { minimumFractionDigits: 2 })} €
)}
)}
)
}