- 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
69 lines
2.3 KiB
JavaScript
69 lines
2.3 KiB
JavaScript
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');
|
|
}
|
|
}; |