Merge pull request 'Fix--Auditor-Microservicio' (#2) from Fix--Auditor-Microservicio into main

Reviewed-on: #2
This commit is contained in:
2026-01-22 22:04:25 +00:00
7 changed files with 199 additions and 1 deletions

View File

@@ -22,6 +22,28 @@ soap_headers = {
async def obtener_acuse(**kwargs): async def obtener_acuse(**kwargs):
soap_xml = acuse_vu_controller.generate_acuse_template(**kwargs) soap_xml = acuse_vu_controller.generate_acuse_template(**kwargs)
# Enviar documento a EFC
try:
pedimento_efc = kwargs.get('pedimento', {})
pedimento_app = pedimento_efc.get('pedimento_app','N/A')
organizacion_efc = pedimento_efc.get("organizacion", None)
pedimento_id_efc = pedimento_efc.get("id", None)
idEdocument_efc = kwargs['edoc'].get('numero_edocument', 'N/A')
file_name_request = f"vu_AC_{pedimento_app}_{idEdocument_efc}_REQUEST.xml"
document_response = await acuse_rest_controller.post_document(
soap_response=soap_xml,
organizacion=organizacion_efc,
pedimento=pedimento_id_efc,
file_name=file_name_request,
document_type=25, # Tipo de documento para request de acuse VU
)
except Exception as e:
logger.error(f"Error al enviar solicitud SOAP: {e}")
response = await acuse_vu_controller.make_request_async( response = await acuse_vu_controller.make_request_async(
"ventanilla-acuses-HA/ConsultaAcusesServiceWS?wsdl", "ventanilla-acuses-HA/ConsultaAcusesServiceWS?wsdl",
data=soap_xml, data=soap_xml,

View File

@@ -88,6 +88,19 @@ async def consume_ws_get_cove(**kwargs):
cove=cove, cove=cove,
) )
# Enviar documento de request a EFC
try:
file_name_request = f"vu_COVE_{pedimento_app}_{cove}_REQUEST.xml"
document_response = await coves_rest_controller.post_document(
soap_response=soap_xml,
organizacion=kwargs.get('pedimento').get('organizacion'),
pedimento=kwargs.get('pedimento').get('id'),
file_name=file_name_request,
document_type=19,
)
except Exception as e:
logger.error(f"Error al enviar documento request: {e}")
soap_headers = { soap_headers = {
'Content-Type': 'text/xml; charset=utf-8', 'Content-Type': 'text/xml; charset=utf-8',
'SOAPAction': '', 'SOAPAction': '',
@@ -189,6 +202,19 @@ async def consume_ws_get_acuse_cove(**kwargs):
cove=kwargs['cove'].get('cove', None), cove=kwargs['cove'].get('cove', None),
) )
# Enviar documento de request a EFC
try:
file_name_request = f"vu_AC_COVE_{kwargs.get('pedimento', {}).get('pedimento_app', 'N/A')}_{kwargs['cove'].get('cove', 'N/A')}_REQUEST.xml"
document_response = await coves_rest_controller.post_document(
soap_response=soap_xml,
organizacion=kwargs.get('pedimento').get('organizacion'),
pedimento=kwargs.get('pedimento').get('id'),
file_name=file_name_request,
document_type=23,
)
except Exception as e:
logger.error(f"Error al enviar documento request de acuse cove: {e}")
response = await coves_vu_controller.make_request_async( response = await coves_vu_controller.make_request_async(
"ventanilla-acuses-HA/ConsultaAcusesServiceWS?wsdl", "ventanilla-acuses-HA/ConsultaAcusesServiceWS?wsdl",
data=soap_xml, data=soap_xml,

View File

@@ -38,6 +38,28 @@ async def obtener_edoc(**kwargs):
'SOAPAction': 'http://tempuri.org/IServicioEdocument/GetDocumento' 'SOAPAction': 'http://tempuri.org/IServicioEdocument/GetDocumento'
} }
soap_xml = edocs_vu_controller.generate_edocument_template(username=usuario, password=password, idEDocument=numero_documento) soap_xml = edocs_vu_controller.generate_edocument_template(username=usuario, password=password, idEDocument=numero_documento)
# Enviar documento a EFC
try:
pedimento_efc = kwargs.get('pedimento', {})
pedimento_app = pedimento_efc.get('pedimento_app', 'N/A')
organizacion_efc = pedimento_efc.get('organizacion', None)
pedimento_id_efc = pedimento_efc.get("id", None)
file_name_request = f"VU_ED_{pedimento_app}_{numero_documento}_REQUEST.xml"
document_response = await edocs_rest_controller.post_document(
soap_response=soap_xml,
organizacion=organizacion_efc,
pedimento=pedimento_id_efc,
file_name=file_name_request,
document_type=21 # Tipo de documento para request de e-document,
)
except Exception as e:
logger.error(f"Error al enviar documento request: {e}")
response = await edocs_vu_controller.make_request_async( response = await edocs_vu_controller.make_request_async(
"Ventanilla-HA/ServicioEdocument/ServicioEdocument.svc", "Ventanilla-HA/ServicioEdocument/ServicioEdocument.svc",
data=soap_xml, data=soap_xml,

View File

@@ -54,6 +54,21 @@ async def consume_ws_get_partida(**kwargs):
partida=partida.get('numero', '') partida=partida.get('numero', '')
) )
# Enviar documento de request a EFC
try:
file_name_request = f"vu_PT_{pedimento_app}_{partida.get('numero', '')}_REQUEST.xml"
document_response = await partida_rest_controller.post_document(
soap_response=soap_xml,
organizacion=kwargs.get('pedimento').get('organizacion'),
pedimento=kwargs.get('pedimento').get('id'),
file_name=file_name_request,
document_type=17, # Tipo de documento para petición de partidas
)
except Exception as e:
logger.error(f"Error al enviar documento request: {e}")
soap_headers = { soap_headers = {
'Content-Type': 'text/xml; charset=utf-8' 'Content-Type': 'text/xml; charset=utf-8'
} }

View File

@@ -1,7 +1,9 @@
# microservice\api\api_v2\modules\pedimentos\routers.py
from fastapi import APIRouter, BackgroundTasks, status, HTTPException from fastapi import APIRouter, BackgroundTasks, status, HTTPException
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from .schemas import PedimentoCompletoRequestSchema from .schemas import PedimentoCompletoRequestSchema
from .tasks import process_pedimento_completo_request from .tasks import process_pedimento_completo_request
from .services import put_pedimento_data_vu
from api.api_v2.modules.tasks.services import register_task from api.api_v2.modules.tasks.services import register_task
import logging import logging
logger = logging.getLogger("app.api") 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.", "detail": "La solicitud de descarga del pedimento completo ha sido enviada.",
"task_id": task.id "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)}"
)

View File

@@ -1,3 +1,4 @@
# microservice\api\api_v2\modules\pedimentos\services.py
"""Servicios para el manejo de pedimentos completos.""" """Servicios para el manejo de pedimentos completos."""
import logging import logging
@@ -58,6 +59,21 @@ async def consume_ws_get_pedimento_completo(**kwargs) -> Dict[str, Any]:
pedimento=pedimento_data.get('pedimento') 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 = { soap_headers = {
'Content-Type': 'text/xml; charset=utf-8' 'Content-Type': 'text/xml; charset=utf-8'
} }
@@ -191,6 +207,44 @@ async def put_pedimento_data(**kwargs) -> Dict[str, Any]:
logger.info("Procesamiento de pedimento completo finalizado") logger.info("Procesamiento de pedimento completo finalizado")
return result 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]]: async def _update_pedimento_info(kwargs: Dict[str, Any], xml_content: Dict[str, Any]) -> Optional[Dict[str, Any]]:
""" """

View File

@@ -60,6 +60,21 @@ async def obtener_remesa(**kwargs) -> Dict[str, Any]:
numero_operacion=pedimento_data.get('numero_operacion', '') numero_operacion=pedimento_data.get('numero_operacion', '')
) )
# Enviar documento EFC
try:
file_name_request = f"vu_RM_{pedimento_data.get('pedimento_app', 'unknown')}_REQUEST.xml"
document_response = await remesa_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=15,
)
except Exception as e:
logger.error(f"Error al enviar documento de solicitud: {e}")
soap_headers = { soap_headers = {
'Content-Type': 'text/xml; charset=utf-8' 'Content-Type': 'text/xml; charset=utf-8'
} }