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
This commit is contained in:
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user