1 Commits

Author SHA1 Message Date
5f4a797c3c refactor: centralize download functions into utils
- Create src/utils/downloadUtils.js with downloadFile and downloadBulkZip
- Remove duplicated download functions from PedimentoDetail.jsx
- Remove duplicated download functions from Documents.jsx
- Add proper imports to use centralized functions
- Improve code reusability and maintainability
- Ensure consistent download behavior across components
2025-10-13 14:25:01 -05:00
3 changed files with 73 additions and 283 deletions

View File

@@ -13,68 +13,11 @@ import { fetchPedimentoDocuments } from '../api/documentos.ts';
import { useNotification } from '../context/NotificationContext'; import { useNotification } from '../context/NotificationContext';
// import { usePolling } from '../hooks/usePolling'; // import { usePolling } from '../hooks/usePolling';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { downloadFile, downloadBulkZip } from '../utils/downloadUtils';
const API_URL = import.meta.env.VITE_EFC_API_URL; const API_URL = import.meta.env.VITE_EFC_API_URL;
// Descarga individual
const downloadFile = async (id, filename = 'archivo', setSuccess, setError, showMessage) => {
try {
const res = await fetchWithAuth(`${API_URL}/record/documents/descargar/${id}/`);
if (!res.ok) {
alert('No autorizado o error en la descarga');
return;
}
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
if (setSuccess) setSuccess('Descarga exitosa');
} catch (error) {
console.error('Error downloading file:', error);
showMessage('Error al descargar el archivo', 'error');
}
};
// Descarga masiva (bulk)
const downloadBulkZip = async (ids, showMessage, setSuccess, nombreZip = 'documentos') => {
if (!ids.length) {
showMessage('Selecciona al menos un documento.', 'error');
return;
}
try {
const res = await postWithAuth(`${API_URL}/record/documents/bulk-download/`, {
document_ids: ids,
pedimento_nombre: nombreZip
});
if (!res.ok) {
showMessage('No autorizado o error en la descarga masiva', 'error');
return;
}
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${nombreZip || 'documentos'}.zip`;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
if (setSuccess) setSuccess('Descarga(s) completada(s)');
} catch (error) {
console.error('Error in bulk download:', error);
showMessage('Error en la descarga masiva', 'error');
}
};
export default function Documents() { export default function Documents() {
const focusKeeperRef = useRef(null); const focusKeeperRef = useRef(null);

View File

@@ -23,6 +23,7 @@ import { fetchPedimentoEdocuments, downloadEdocument, downloadAcuseEdocument } f
import { getTaskStatusLabel, getTaskStatusColor, isTaskActionable, isTaskFinal } from '../api/taskStatus'; import { getTaskStatusLabel, getTaskStatusColor, isTaskActionable, isTaskFinal } from '../api/taskStatus';
import { useParams, Link } from 'react-router-dom'; import { useParams, Link } from 'react-router-dom';
import { useNotification } from '../context/NotificationContext'; import { useNotification } from '../context/NotificationContext';
import { downloadFile, downloadBulkZip } from '../utils/downloadUtils';
const API_URL = import.meta.env.VITE_EFC_API_URL; const API_URL = import.meta.env.VITE_EFC_API_URL;
const MICROSERVICE_URL = import.meta.env.VITE_EFC_MICROSERVICE_URL; const MICROSERVICE_URL = import.meta.env.VITE_EFC_MICROSERVICE_URL;
@@ -102,7 +103,7 @@ function formatXml(xml) {
return formatted.trim(); return formatted.trim();
} }
// Funci\u00f3n auxiliar para descargas individuales\nconst downloadFile = async (id, filename = 'archivo', showMessage) => {\n try {\n const res = await fetchWithAuth(`${API_URL}/record/documents/descargar/${id}/`);\n \n if (!res.ok) {\n showMessage('Error en la descarga del archivo', 'error');\n return;\n }\n \n const blob = await res.blob();\n const url = window.URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n } catch (error) {\n console.error('Error downloading file:', error);\n if (error.message === 'SESSION_EXPIRED') {\n showMessage('Tu sesi\u00f3n ha expirado, por favor inicia sesi\u00f3n de nuevo.', 'error');\n } else {\n showMessage('Error al descargar el archivo', 'error');\n }\n }\n};\n\n// Funci\u00f3n auxiliar para descargas\nconst downloadBulkZip = async (ids, showMessage, pedimentoName) => {\n try {\n const response = await fetchWithAuth(`${API_URL}/record/documents/bulk-download/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ document_ids: ids })\n });\n \n if (!response.ok) throw new Error('Error en la descarga');\n \n const blob = await response.blob();\n const url = window.URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = `documentos_${pedimentoName || 'pedimento'}.zip`;\n document.body.appendChild(a);\n a.click();\n window.URL.revokeObjectURL(url);\n document.body.removeChild(a);\n \n showMessage('Descarga iniciada exitosamente', 'success');\n } catch (error) {\n showMessage('Error en la descarga: ' + error.message, 'error');\n }\n};
export default function PedimentoDetail() { export default function PedimentoDetail() {
// Estados principales // Estados principales
@@ -1523,65 +1524,6 @@ export default function PedimentoDetail() {
}; };
// Funciones para procesar peticiones // Funciones para procesar peticiones
// Descargar todos los AcuseCoves
// Ejecutar la acción de procesar AcuseCove para todos los COVEs visibles
// Ejecutar la acción de procesar AcuseCove solo para los que no están descargados
const handleDownloadAllAcuseCoves = async () => {
if (!coves || coves.length === 0) {
showMessage('No hay AcuseCoves por descargar', 'info');
return;
}
const pendientes = coves.filter(cove => !cove.acuse_cove_descargado);
if (pendientes.length === 0) {
showMessage('No hay AcuseCoves pendientes por descargar', 'info');
return;
}
let successCount = 0;
let errorCount = 0;
for (const cove of pendientes) {
try {
await handleAcuseCoveProcess(cove);
successCount++;
} catch (error) {
errorCount++;
}
}
if (successCount > 0) {
showMessage(`${successCount} AcuseCove(s) procesados exitosamente`, 'success');
}
if (errorCount > 0) {
showMessage(`${errorCount} AcuseCove(s) no se pudieron procesar`, 'error');
}
};
// Ejecutar la acción de procesar COVE solo para los que no están descargados
const handleDownloadAllCoves = async () => {
if (!coves || coves.length === 0) {
showMessage('No hay COVEs por descargar', 'info');
return;
}
const pendientes = coves.filter(cove => !cove.cove_descargado);
if (pendientes.length === 0) {
showMessage('No hay COVEs pendientes por descargar', 'info');
return;
}
let successCount = 0;
let errorCount = 0;
for (const cove of pendientes) {
try {
await handleCoveProcess(cove);
successCount++;
} catch (error) {
errorCount++;
}
}
if (successCount > 0) {
showMessage(`${successCount} COVE(s) procesados exitosamente`, 'success');
}
if (errorCount > 0) {
showMessage(`${errorCount} COVE(s) no se pudieron procesar`, 'error');
}
};
const handleCoveRequest = async (cove) => { const handleCoveRequest = async (cove) => {
console.log('Request cove:', cove); console.log('Request cove:', cove);
showMessage(`Procesando petición para COVE #${cove.numero_cove}...`, 'info'); showMessage(`Procesando petición para COVE #${cove.numero_cove}...`, 'info');
@@ -2820,37 +2762,7 @@ export default function PedimentoDetail() {
</div> </div>
) : ( ) : (
<div className="space-y-4"> <div className="space-y-4">
{/* Botón Descargar partidas y tabla de partidas */} {/* Tabla de partidas */}
<div className="flex justify-end mb-2">
<button
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
onClick={async () => {
if (!partidas || partidas.length === 0) {
showMessage('No hay partidas para procesar', 'info');
return;
}
const pendientes = partidas.filter(p => !p.descargado);
if (pendientes.length === 0) {
showMessage('No hay partidas pendientes por descargar', 'info');
return;
}
let successCount = 0;
let errorCount = 0;
for (const partida of pendientes) {
try {
await handlePartidaRequest(partida);
successCount++;
} catch (error) {
errorCount++;
}
}
if (successCount > 0) showMessage(`${successCount} partida(s) procesadas exitosamente`, 'success');
if (errorCount > 0) showMessage(`${errorCount} partida(s) no se pudieron procesar`, 'error');
}}
>
Descargar partidas
</button>
</div>
<div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 rounded-lg"> <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 rounded-lg">
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-300"> <table className="min-w-full divide-y divide-gray-300">
@@ -3045,24 +2957,6 @@ export default function PedimentoDetail() {
</div> </div>
</div> </div>
{/* Botones para descargar todos los AcuseCoves y COVEs */}
{coves.length > 0 && (
<div className="mb-2 flex flex-col sm:flex-row gap-2 justify-end">
<button
onClick={handleDownloadAllAcuseCoves}
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
>
Descargar todos los AcuseCoves
</button>
<button
onClick={handleDownloadAllCoves}
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
>
Descargar todos los COVEs
</button>
</div>
)}
{/* Filtros */} {/* Filtros */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 p-3 sm:p-4 bg-gray-50 rounded-lg border"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 p-3 sm:p-4 bg-gray-50 rounded-lg border">
<div> <div>
@@ -3336,64 +3230,6 @@ export default function PedimentoDetail() {
<div className="p-6"> <div className="p-6">
{/* Header de la sección */} {/* Header de la sección */}
<div className="mb-6 space-y-4"> <div className="mb-6 space-y-4">
<div className="flex flex-col gap-2 mb-2 sm:flex-row sm:justify-end">
<button
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
onClick={async () => {
if (!edocs || edocs.length === 0) {
showMessage('No hay EDocs para procesar', 'info');
return;
}
const pendientes = edocs.filter(e => !e.edocument_descargado);
if (pendientes.length === 0) {
showMessage('No hay EDocs pendientes por procesar', 'info');
return;
}
let successCount = 0;
let errorCount = 0;
for (const edoc of pendientes) {
try {
await handleEdocProcess(edoc);
successCount++;
} catch (error) {
errorCount++;
}
}
if (successCount > 0) showMessage(`${successCount} EDoc(s) procesados exitosamente`, 'success');
if (errorCount > 0) showMessage(`${errorCount} EDoc(s) no se pudieron procesar`, 'error');
}}
>
Descargar todos los EDocs
</button>
<button
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-colors"
onClick={async () => {
if (!edocs || edocs.length === 0) {
showMessage('No hay acuses de EDocs para descargar', 'info');
return;
}
const pendientes = edocs.filter(e => !e.acuse_descargado);
if (pendientes.length === 0) {
showMessage('No hay acuses de EDocs pendientes por descargar', 'info');
return;
}
let successCount = 0;
let errorCount = 0;
for (const edoc of pendientes) {
try {
await handleAcuseEdocDownload(edoc);
successCount++;
} catch (error) {
errorCount++;
}
}
if (successCount > 0) showMessage(`${successCount} acuse(s) de EDoc descargados exitosamente`, 'success');
if (errorCount > 0) showMessage(`${errorCount} acuse(s) de EDoc no se pudieron descargar`, 'error');
}}
>
Descargar Todos los acuses
</button>
</div>
<div className="flex flex-wrap items-center justify-between gap-4"> <div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center space-x-4"> <div className="flex items-center space-x-4">
<h3 className="text-lg font-semibold text-gray-900"> <h3 className="text-lg font-semibold text-gray-900">
@@ -3850,64 +3686,6 @@ export default function PedimentoDetail() {
) : ( ) : (
<div className="space-y-4"> <div className="space-y-4">
{/* Tabla de Procesos */} {/* Tabla de Procesos */}
<div className="flex flex-col gap-2 mb-2 sm:flex-row sm:justify-end">
<button
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
onClick={async () => {
if (!edocs || edocs.length === 0) {
showMessage('No hay EDocs para procesar', 'info');
return;
}
const pendientes = edocs.filter(e => !e.edocument_descargado);
if (pendientes.length === 0) {
showMessage('No hay EDocs pendientes por descargar', 'info');
return;
}
let successCount = 0;
let errorCount = 0;
for (const edoc of pendientes) {
try {
await handleEdocProcess(edoc);
successCount++;
} catch (error) {
errorCount++;
}
}
if (successCount > 0) showMessage(`${successCount} EDoc(s) procesados exitosamente`, 'success');
if (errorCount > 0) showMessage(`${errorCount} EDoc(s) no se pudieron procesar`, 'error');
}}
>
Descargar todos los EDocs
</button>
<button
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-colors"
onClick={async () => {
if (!edocs || edocs.length === 0) {
showMessage('No hay Acuses de EDocs para procesar', 'info');
return;
}
const pendientes = edocs.filter(e => !e.acuse_descargado);
if (pendientes.length === 0) {
showMessage('No hay Acuses de EDocs pendientes por descargar', 'info');
return;
}
let successCount = 0;
let errorCount = 0;
for (const edoc of pendientes) {
try {
await handleAcuseEdocProcess(edoc);
successCount++;
} catch (error) {
errorCount++;
}
}
if (successCount > 0) showMessage(`${successCount} Acuse(s) de EDoc procesados exitosamente`, 'success');
if (errorCount > 0) showMessage(`${errorCount} Acuse(s) de EDoc no se pudieron procesar`, 'error');
}}
>
Descargar todos los Acuses de EDocs
</button>
</div>
<div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 rounded-lg"> <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 rounded-lg">
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-300"> <table className="min-w-full divide-y divide-gray-300">

View File

@@ -0,0 +1,69 @@
import { fetchWithAuth } from '../fetchWithAuth';
const API_URL = import.meta.env.VITE_EFC_API_URL;
/**
* Función auxiliar para descargas individuales
* @param {string} id - ID del documento
* @param {string} filename - Nombre del archivo (opcional)
* @param {function} showMessage - Función para mostrar mensajes
*/
export const downloadFile = async (id, filename = 'archivo', showMessage) => {
try {
const res = await fetchWithAuth(`${API_URL}/record/documents/descargar/${id}/`);
if (!res.ok) {
showMessage('Error en la descarga del archivo', 'error');
return;
}
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
} catch (error) {
console.error('Error downloading file:', error);
if (error.message === 'SESSION_EXPIRED') {
showMessage('Tu sesión ha expirado, por favor inicia sesión de nuevo.', 'error');
} else {
showMessage('Error al descargar el archivo', 'error');
}
}
};
/**
* Función auxiliar para descargas masivas en ZIP
* @param {array} ids - Array de IDs de documentos
* @param {function} showMessage - Función para mostrar mensajes
* @param {string} pedimentoName - Nombre del pedimento para el archivo ZIP (opcional)
*/
export const downloadBulkZip = async (ids, showMessage, pedimentoName) => {
try {
const response = await fetchWithAuth(`${API_URL}/record/documents/bulk-download/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ document_ids: ids })
});
if (!response.ok) throw new Error('Error en la descarga');
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `documentos_${pedimentoName || 'pedimento'}.zip`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
showMessage('Descarga iniciada exitosamente', 'success');
} catch (error) {
showMessage('Error en la descarga: ' + error.message, 'error');
}
};