import { useState, useEffect, useMemo } from 'react'; import { sheetsApi } from '../api/client'; import { useAuth } from '../context/AuthContext'; import { calcIngresoRow, emptyIngresoRow, formatMoney } from '../utils/calc'; export default function IngresoSheet({ sheetType, title }) { const { canEdit } = useAuth(); const editable = canEdit(sheetType); const [rows, setRows] = useState([emptyIngresoRow()]); 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); setRows(data.rows?.length ? data.rows : [emptyIngresoRow()]); } catch (e) { setError(e.message); } finally { setLoading(false); } })(); }, [sheetType]); const totals = useMemo(() => { let totalIngresos = 0; let totalUtilidad = 0; rows.forEach((row) => { const { precioTotal, utilidad } = calcIngresoRow(row); totalIngresos += precioTotal; totalUtilidad += utilidad; }); return { totalIngresos, totalUtilidad }; }, [rows]); const updateRow = (index, field, value) => { setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r))); }; const addRow = () => setRows((prev) => [...prev, emptyIngresoRow()]); 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 : [emptyIngresoRow()]); setMessage('Planilla guardada correctamente'); } catch (e) { setError(e.message); } finally { setSaving(false); } }; if (loading) return
Cargando planilla…
; return (| Fecha | Cliente | Detalle | Cantidad | P. Unitario | C. Unitario | Precio Total | Utilidad | {editable &&} |
|---|---|---|---|---|---|---|---|---|
| updateRow(i, 'fecha', e.target.value)} /> | updateRow(i, 'cliente', e.target.value)} /> | updateRow(i, 'detalle', e.target.value)} /> | updateRow(i, 'cantidad', e.target.value)} /> | updateRow(i, 'precioUnitario', e.target.value)} /> | updateRow(i, 'costoUnitario', e.target.value)} /> | {formatMoney(precioTotal)} | {formatMoney(utilidad)} | {editable && ()} |