diff --git a/src/pages/Documents.jsx b/src/pages/Documents.jsx index eb4547b..50c77ec 100644 --- a/src/pages/Documents.jsx +++ b/src/pages/Documents.jsx @@ -13,68 +13,11 @@ import { fetchPedimentoDocuments } from '../api/documentos.ts'; import { useNotification } from '../context/NotificationContext'; // import { usePolling } from '../hooks/usePolling'; import { Link } from 'react-router-dom'; +import { downloadFile, downloadBulkZip } from '../utils/downloadUtils'; 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() { const focusKeeperRef = useRef(null); diff --git a/src/pages/PedimentoDetail.jsx b/src/pages/PedimentoDetail.jsx index 4894b5d..b841c17 100644 --- a/src/pages/PedimentoDetail.jsx +++ b/src/pages/PedimentoDetail.jsx @@ -23,6 +23,7 @@ import { fetchPedimentoEdocuments, downloadEdocument, downloadAcuseEdocument } f import { getTaskStatusLabel, getTaskStatusColor, isTaskActionable, isTaskFinal } from '../api/taskStatus'; import { useParams, Link } from 'react-router-dom'; import { useNotification } from '../context/NotificationContext'; +import { downloadFile, downloadBulkZip } from '../utils/downloadUtils'; const API_URL = import.meta.env.VITE_EFC_API_URL; const MICROSERVICE_URL = import.meta.env.VITE_EFC_MICROSERVICE_URL; @@ -102,7 +103,7 @@ function formatXml(xml) { 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() { // Estados principales diff --git a/src/utils/downloadUtils.js b/src/utils/downloadUtils.js new file mode 100644 index 0000000..6fdcd8d --- /dev/null +++ b/src/utils/downloadUtils.js @@ -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'); + } +}; \ No newline at end of file