import { useState, useEffect, useMemo } from 'react'; import { sheetsApi } from '../api/client'; import { useAuth } from '../context/AuthContext'; import { emptyGastoRow, formatMoney } from '../utils/calc'; export default function GastoSheet({ sheetType, title, defaultClasificacion }) { const { canEdit } = useAuth(); const editable = canEdit(sheetType); const [rows, setRows] = useState([emptyGastoRow()]); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [message, setMessage] = useState(null); const [error, setError] = useState(null); useEffect(() => { (async () => { try { const data = await sheetsApi.get(sheetType); const loaded = data.rows?.length ? data.rows : [emptyGastoRow()]; setRows( loaded.map((r) => ({ ...r, clasificacion: r.clasificacion || defaultClasificacion, })) ); } catch (e) { setError(e.message); } finally { setLoading(false); } })(); }, [sheetType, defaultClasificacion]); const total = useMemo( () => rows.reduce((acc, r) => acc + (Number(r.monto) || 0), 0), [rows] ); const updateRow = (index, field, value) => { setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r))); }; const addRow = () => setRows((prev) => [...prev, { ...emptyGastoRow(), clasificacion: defaultClasificacion }]); const removeRow = (index) => setRows((prev) => (prev.length > 1 ? prev.filter((_, i) => i !== index) : prev)); const handleSave = async () => { if (!editable) return; setSaving(true); setMessage(null); setError(null); try { const data = await sheetsApi.save(sheetType, { rows }); setRows(data.rows?.length ? data.rows : [{ ...emptyGastoRow(), clasificacion: defaultClasificacion }]); setMessage('Planilla guardada correctamente'); } catch (e) { setError(e.message); } finally { setSaving(false); } }; if (loading) return

Cargando planilla…

; return (

{title}

{error &&
{error}
} {message &&
{message}
} {!editable &&
Solo lectura
}
{editable && ( <> )}
{editable && } {rows.map((row, i) => ( {editable && ( )} ))}
Fecha Detalle Impuestos Nº Factura Monto Clasificación
updateRow(i, 'fecha', e.target.value)} /> updateRow(i, 'detalle', e.target.value)} /> updateRow(i, 'impuestos', e.target.value)} /> updateRow(i, 'numeroFactura', e.target.value)} /> updateRow(i, 'monto', e.target.value)} />
Total gastos: {formatMoney(total)}
); }