From b879e5c24df03036077bf3e42e4352fb38eb7d34 Mon Sep 17 00:00:00 2001 From: Luis Date: Fri, 2 Jan 2026 08:37:59 -0700 Subject: [PATCH] fix: Ajuste en micorservicios para guardar las peticiones a VU --- api/api_v2/modules/pedimentos/routers.py | 44 ++++++++++++++++++ api/api_v2/modules/pedimentos/services.py | 56 ++++++++++++++++++++++- 2 files changed, 99 insertions(+), 1 deletion(-) diff --git a/api/api_v2/modules/pedimentos/routers.py b/api/api_v2/modules/pedimentos/routers.py index 1f9f792..cc7e914 100644 --- a/api/api_v2/modules/pedimentos/routers.py +++ b/api/api_v2/modules/pedimentos/routers.py @@ -1,7 +1,9 @@ +# microservice\api\api_v2\modules\pedimentos\routers.py from fastapi import APIRouter, BackgroundTasks, status, HTTPException from fastapi.responses import JSONResponse from .schemas import PedimentoCompletoRequestSchema from .tasks import process_pedimento_completo_request +from .services import put_pedimento_data_vu from api.api_v2.modules.tasks.services import register_task import logging logger = logging.getLogger("app.api") @@ -22,3 +24,45 @@ async def download_pedimento_completo(Pedimento: PedimentoCompletoRequestSchema) "detail": "La solicitud de descarga del pedimento completo ha sido enviada.", "task_id": task.id } + +@router.post("/services/auditar_pedimento_completo", status_code=status.HTTP_202_ACCEPTED) +async def auditar_pedimento_completo(Pedimento: PedimentoCompletoRequestSchema): + """ + Endpoint para auditar la descarga completa de un pedimento vu. + + Versión sincrónica que llama directamente al servicio. + """ + + try: + # Convertir el modelo Pydantic a diccionario + pedimento_dict = Pedimento.model_dump() + + # Llamar directamente al servicio + result = await put_pedimento_data_vu(**pedimento_dict) + + return { + "status": "completed", + "detail": "La descarga del pedimento completo se ha completado exitosamente.", + "result": { + "documento": result.get("documento"), + "xml_content": result.get("xml_content"), + } + } + # return { + # "status": "completed", + # "detail": "La descarga del pedimento completo se ha completado exitosamente.", + # "result": { + # "documento": "Simulated Documento Content", + # "xml_content": "Simulated XML Content", + # } + # } + except HTTPException as e: + raise e + except Exception as e: + logger.error(f"Error inesperado en auditar_pedimento_completo: {e}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"Error interno del servidor auditar pedimento completo: {str(e)}" + ) + + diff --git a/api/api_v2/modules/pedimentos/services.py b/api/api_v2/modules/pedimentos/services.py index 21db566..d55e39b 100644 --- a/api/api_v2/modules/pedimentos/services.py +++ b/api/api_v2/modules/pedimentos/services.py @@ -1,3 +1,4 @@ +# microservice\api\api_v2\modules\pedimentos\services.py """Servicios para el manejo de pedimentos completos.""" import logging @@ -58,6 +59,21 @@ async def consume_ws_get_pedimento_completo(**kwargs) -> Dict[str, Any]: pedimento=pedimento_data.get('pedimento') ) + # Enviar documento + try: + + file_name_request = f"VU_PC_{pedimento_data.get('pedimento_app', 'unknown')}_REQUEST.xml" + + document_response = await pedimento_rest_controller.post_document( + soap_response=soap_xml, + organizacion=pedimento_data.get('organizacion'), + pedimento=pedimento_data.get('id'), + file_name=file_name_request, + document_type=13, + ) + except Exception as e: + logger.error(f"Error al enviar documento request: {e}") + soap_headers = { 'Content-Type': 'text/xml; charset=utf-8' } @@ -100,7 +116,7 @@ async def consume_ws_get_pedimento_completo(**kwargs) -> Dict[str, Any]: organizacion=pedimento_data.get('organizacion'), pedimento=pedimento_data.get('id'), file_name=file_name, - document_type=2, + document_type=2, ) except Exception as e: logger.error(f"Error al enviar documento: {e}") @@ -191,6 +207,44 @@ async def put_pedimento_data(**kwargs) -> Dict[str, Any]: logger.info("Procesamiento de pedimento completo finalizado") return result +async def put_pedimento_data_vu(**kwargs) -> Dict[str, Any]: + """ + Actualiza la información del pedimento en el sistema REST. + + Args: + **kwargs: Datos de credencial y pedimento + + Returns: + Dict con resultados del procesamiento + + Raises: + HTTPException: Si hay errores críticos en el procesamiento + """ + # Inicializar variables de respuesta + result = { + "documento": None, + "xml_content": None + + } + + # Obtener datos del servicio web + try: + ws_data = await consume_ws_get_pedimento_completo(**kwargs) + result["documento"] = ws_data.get("documento", None) + xml_content = ws_data.get('xml_content', {}) + result["xml_content"] = xml_content + + if not xml_content: + logger.warning("No se obtuvo contenido XML del servicio web") + return result + + except HTTPException: + raise # Re-lanzar HTTPExceptions + except Exception as e: + logger.error(f"Error inesperado al consumir servicio web: {e}") + raise HTTPException(status_code=500, detail=f"Error al obtener datos del pedimento: {str(e)}") + + return result async def _update_pedimento_info(kwargs: Dict[str, Any], xml_content: Dict[str, Any]) -> Optional[Dict[str, Any]]: """