diff --git a/src/pages/Expedientes.jsx b/src/pages/Expedientes.jsx index 1417854..67e446b 100644 --- a/src/pages/Expedientes.jsx +++ b/src/pages/Expedientes.jsx @@ -230,6 +230,125 @@ export default function Documents() { // } // // showMessage('Error durante la descarga masiva', 'error'); // }; + + // accionar pedimento completo si no se proceso + const handleEjecutarServicio = async (pedimentoId, org) => { + try { + showMessage(`Procesando pedimento ${pedimentoId}...`, 'info'); + + // Construir el body de la petición + const body = { + organizacion: org, // Ajusta según tu organización, puede ser string o número + pedimento: pedimentoId.toString() // Convertir a string si es necesario + }; + + // Endpoint para pedimento completo + const MICROSERVICE_URL = import.meta.env.VITE_EFC_MICROSERVICE_URL; + const endpoint = `${MICROSERVICE_URL}/services/pedimento_completo`; + + const response = await postWithAuth(endpoint, body); + + if (!response.ok) { + const errorData = await response.json().catch(() => ({})); + throw new Error(errorData.message || errorData.detail || `Error ${response.status}: ${response.statusText}`); + } + + const result = await response.json(); + console.log('Resultado del servicio:', result); + + showMessage(`Pedimento ${pedimentoId} procesado correctamente`, 'success'); + + // Opcional: Refrescar la lista después de procesar + setTimeout(() => { + refetch(); + }, 2000); + + } catch (error) { + console.error('Error ejecutando servicio:', error); + showMessage(`Error al procesar pedimento ${pedimentoId}: ${error.message}`, 'error'); + } + }; + + // Agrega esta función después de handleEjecutarServicio + const handleProcesarMultiplesPedimentos = async () => { + const pedimentosNoProcesados = currentDocuments.filter(ped => selectedDocuments.includes(ped.id) && !ped.existe_expediente); + + if (pedimentosNoProcesados.length === 0) { + showMessage('No hay pedimentos seleccionados que estén sin procesar', 'warning'); + return; + } + + if (pedimentosNoProcesados.length > 200) { + showMessage(`Máximo 200 pedimentos por solicitud. Seleccionados: ${pedimentosNoProcesados.length}`, 'warning'); + return; + } + + try { + showMessage(`Iniciando procesamiento de ${pedimentosNoProcesados.length} pedimentos...`, 'info'); + + const pedimentosData = pedimentosNoProcesados.map(ped => ({ + id: ped.id, + pedimento_app: ped.pedimento_app, + aduana: ped.aduana, + patente: ped.patente, + pedimento: ped.pedimento, + organizacion: ped.organizacion + })); + + const MICROSERVICE_URL = import.meta.env.VITE_EFC_MICROSERVICE_URL; + const response = await postWithAuth(`${MICROSERVICE_URL}/async/services/pedimento_completo/multiple`, { + organizacion: pedimentosNoProcesados[0].organizacion.toString(), + pedimentos: pedimentosNoProcesados.map(p => p.id.toString()) + }); + + if (!response.ok) { + const errorData = await response.json().catch(() => ({})); + throw new Error(errorData.message || errorData.detail || `Error ${response.status}: ${response.statusText}`); + } + + const result = await response.json(); + + showMessage( + `Tarea iniciada: ${result.total_pedimentos} pedimentos encolados. Task ID: ${result.task_id}`, + 'success' + ); + + setSelectedDocuments([]); + setIsSelectAll(false); + + // Opcional: Iniciar polling para monitorear el progreso + // const intervalId = setInterval(async () => { + // const statusResponse = await fetchWithAuth(`${MICROSERVICE_URL}/async/task-status/${result.task_id}`); + + // if (statusResponse.ok) { + // const status = await statusResponse.json(); + + // if (status.status === 'SUCCESS') { + // clearInterval(intervalId); + // const { success_count, failed_count, elapsed_seconds } = status.result; + // showMessage( + // `Procesamiento completado: ${success_count} exitosos, ${failed_count} fallidos. Tiempo: ${elapsed_seconds}s`, + // failed_count > 0 ? 'warning' : 'success' + // ); + // refetch(); // Refrescar la lista + // } else if (status.status === 'FAILURE') { + // clearInterval(intervalId); + // showMessage(`Error en el procesamiento: ${status.message}`, 'error'); + // } else if (status.status === 'PROGRESS' && status.progress) { + // const { current, total, current_pedimento, percentage } = status.progress; + // console.log(`Progreso: ${percentage}% - ${current}/${total}: ${current_pedimento}`); + // } + // } + // }, 5000); + + setTimeout(() => clearInterval(intervalId), 600000); + + } catch (error) { + console.error('Error procesando múltiples pedimentos:', error); + showMessage(`Error: ${error.message}`, 'error'); + } + }; + // Función para descargar documentos seleccionados const handleDownloadSelected = async () => { if (selectedDocuments.length === 0) { @@ -945,6 +1064,21 @@ const downloadExpediente = async (pedimentoId, pedimentoName, setSuccess, showMe
+ {/* NUEVO BOTÓN PARA PROCESAR MÚLTIPLES */} + + + {/* Botón existente de eliminar */} + )} + {/* handleEjecutarServicio */}