74 lines
2.4 KiB
JavaScript
74 lines
2.4 KiB
JavaScript
import { fetchWithAuth } from '../fetchWithAuth';
|
|
import { extractApiError } from '../api/apiError';
|
|
|
|
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) {
|
|
const errMsg = await extractApiError(res);
|
|
showMessage(errMsg, '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) {
|
|
const errMsg = await extractApiError(response);
|
|
throw new Error(errMsg);
|
|
}
|
|
|
|
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');
|
|
}
|
|
}; |