import React, { useEffect, useState } from 'react'; import fetchWithAuth from '../fetchWithAuth'; import { useNotification } from '../context/NotificationContext'; import { extractApiError } from '../api/apiError'; const initialFilters = { pedimento_app: '', aduana: '', patente: '', regimen: '', agente_aduanal: '', tipo_operacion: '', fecha_pago_gte: '', fecha_pago_lte: '', contribuyente__rfc: '', }; export default function TableroAlmacenamiento() { const { showMessage } = useNotification(); const [filters, setFilters] = useState(initialFilters); const [summary, setSummary] = useState(null); const [isLoading, setIsLoading] = useState(false); const [reports, setReports] = useState([]); const handleGenerateReport = async () => { try { const params = Object.entries(filters) .filter(([_, v]) => v) .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) .join('&'); const url = `${import.meta.env.VITE_EFC_API_URL}/reports/table-summary/${params ? `?${params}` : ''}`; const res = await fetchWithAuth(url, { method: 'POST' }); if (!res.ok) { const errMsg = await extractApiError(res); throw new Error(errMsg); } showMessage('Reporte solicitado correctamente. Aparecerá en el historial cuando esté listo.', 'success'); } catch (err) { showMessage(err.message || 'No se pudo generar el reporte', 'error'); } }; const handleDownloadReport = async (reportId) => { try { const url = `${import.meta.env.VITE_EFC_API_URL}/reports/report-document-download/${reportId}/`; const res = await fetchWithAuth(url); if (!res.ok) { const errMsg = await extractApiError(res); throw new Error(errMsg); } const blob = await res.blob(); let filename = `reporte_${reportId}.csv`; const disposition = res.headers.get('Content-Disposition'); if (disposition && disposition.includes('filename=')) { filename = disposition.split('filename=')[1].replace(/"/g, '').trim(); } const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); } catch (err) { showMessage(err.message || 'No se pudo descargar el reporte', 'error'); } }; // Fetch summary data const fetchSummary = async () => { setIsLoading(true); try { const params = Object.entries(filters) .filter(([_, v]) => v) .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) .join('&'); const url = `${import.meta.env.VITE_EFC_API_URL}/reports/dashboard/summary/${params ? `?${params}` : ''}`; const res = await fetchWithAuth(url); if (!res.ok) { const errMsg = await extractApiError(res); throw new Error(errMsg); } const data = await res.json(); setSummary(data); } catch (err) { showMessage(err.message || 'Error al cargar el resumen', 'error'); setSummary(null); } setIsLoading(false); }; // Fetch report list from API useEffect(() => { const fetchReports = async () => { try { const url = `${import.meta.env.VITE_EFC_API_URL}/reports/report-document-list/`; const res = await fetchWithAuth(url); if (!res.ok) throw new Error('Error al obtener el historial de reportes'); const data = await res.json(); setReports(data); } catch (err) { showMessage(err.message || 'Error al cargar el historial de reportes', 'error'); setReports([]); } }; fetchReports(); }, []); useEffect(() => { fetchSummary(); }, []); const handleFilterChange = (e) => { setFilters({ ...filters, [e.target.name]: e.target.value }); }; return (
{/* Header */}

Resumen de Cumplimiento

{/* Filtros */}
{ e.preventDefault(); fetchSummary(); }} className="bg-white rounded-lg shadow-sm border border-slate-200 p-4">
{Object.keys(initialFilters).map((key) => (
))}
{/* Cards */}
{isLoading ? (
Cargando resumen...
) : summary ? ( <>
{/* ...Tarjetas existentes... */} {/* ...aquí van las Card como antes... */} {/* ...no se repite para brevedad... */}
{/* Tabla de reportes debajo de las tarjetas */}

Historial de Reportes

{reports.length > 0 ? ( reports.map((r) => ( )) ) : ( )}
ID Estado Creado Finalizado Error Descargar
{r.report_id} {r.status} {r.created_at} {r.finished_at} {r.error_message ? r.error_message : '-'} {r.status === 'ready' ? ( ) : ( - )}
No hay reportes disponibles.
) : (
No hay datos para mostrar.
)}
); }