edoc serv
This commit is contained in:
@@ -61,6 +61,7 @@ class EdocRESTController(APIRESTController):
|
||||
"""
|
||||
return await self._make_request_async('PUT', f'customs/edocuments/{edocument_id}/', data=data)
|
||||
|
||||
|
||||
# Instancias de los controladores que serán importadas en services.py
|
||||
edocs_vu_controller = EdocVuController()
|
||||
edocs_rest_controller = EdocRESTController()
|
||||
@@ -1,7 +1,7 @@
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from typing import Dict, Any, Optional
|
||||
from .schemas import EdocumentsSchema, EdocumentsMasivoSchema
|
||||
from .tasks import process_edoc_download_request, process_edocs_masivo_download_request
|
||||
from .tasks import process_edoc_download_request
|
||||
from api.api_v2.modules.authentication.services import get_current_user
|
||||
|
||||
router = APIRouter()
|
||||
@@ -33,7 +33,7 @@ async def download_edocs_masivo(edoc_request: EdocumentsMasivoSchema):
|
||||
edoc_dict = {
|
||||
"pedimento": edoc_request_dict.get('pedimento'),
|
||||
"credencial": edoc_request_dict.get('credencial'),
|
||||
"edoc": edoc.get('edoc')
|
||||
"edoc": edoc
|
||||
}
|
||||
task = process_edoc_download_request.delay(edoc_dict)
|
||||
task_ids.append(task.id)
|
||||
|
||||
@@ -73,22 +73,22 @@ def _get_file_name(**kwargs) -> str:
|
||||
# --- FUNCIONES DE SERVICIO ---
|
||||
|
||||
async def obtener_edoc(**kwargs):
|
||||
|
||||
credencial = kwargs.get('credencial', {})
|
||||
usuario = credencial.get('user', '')
|
||||
password = credencial.get('password', '')
|
||||
doc = kwargs.get('edoc', {})
|
||||
numero_documento = kwargs['edoc'].get('numero_edocument', '')
|
||||
soap_headers = {
|
||||
'Content-Type': 'text/xml; charset=utf-8',
|
||||
'SOAPAction': 'http://tempuri.org/IServicioEdocument/GetDocumento'
|
||||
}
|
||||
soap_xml = edocs_vu_controller.generate_edocument_template(username=usuario, password=password, idEDocument=numero_documento)
|
||||
print(soap_xml)
|
||||
response = await edocs_vu_controller.make_request_async(
|
||||
"Ventanilla-HA/ServicioEdocument/ServicioEdocument.svc",
|
||||
data=soap_xml,
|
||||
headers=soap_headers
|
||||
)
|
||||
print(response.text)
|
||||
if response is None:
|
||||
raise Exception("No se obtuvo respuesta del servicio SOAP.")
|
||||
|
||||
@@ -139,10 +139,12 @@ async def obtener_edoc(**kwargs):
|
||||
logger.info("Documento enviado, actualizando status de Edoc")
|
||||
|
||||
edoc_status_response = await change_edocument_status(
|
||||
edoc=kwargs.get('edoc'),
|
||||
edoc=doc,
|
||||
status=True,
|
||||
pedimento=pedimento
|
||||
)
|
||||
|
||||
print(edoc_status_response)
|
||||
|
||||
return {
|
||||
"document_response": rest_response,
|
||||
@@ -155,7 +157,7 @@ async def obtener_edoc(**kwargs):
|
||||
async def change_edocument_status(edoc: dict, status: bool, pedimento: dict):
|
||||
data = {
|
||||
"id": edoc.get("id"),
|
||||
"edocument_descargado": status,
|
||||
"acuse_descargado": status,
|
||||
"numero_edocument": edoc.get("numero_edocument"),
|
||||
"pedimento": pedimento.get("id"),
|
||||
"organizacion": pedimento.get("organizacion"),
|
||||
@@ -165,31 +167,7 @@ async def change_edocument_status(edoc: dict, status: bool, pedimento: dict):
|
||||
|
||||
return response
|
||||
|
||||
async def obtener_edocs_masivo(**kwargs):
|
||||
logger.info("Iniciando la orquestación de descarga masiva de Edocs.")
|
||||
numeros_documentos = kwargs.get("edocs", [])
|
||||
if not numeros_documentos:
|
||||
return {"status": "warning", "message": "No se encontraron números de documento para procesar."}
|
||||
|
||||
for edoc in numeros_documentos:
|
||||
try:
|
||||
logger.info(f"Procesando Edoc: {edoc.get('numero_edocument', 'N/A')}")
|
||||
edoc = {
|
||||
"edoc": edoc,
|
||||
"pedimento": kwargs.get("pedimento"),
|
||||
"credencial": kwargs.get("credencial")
|
||||
}
|
||||
await obtener_edoc(**edoc)
|
||||
logger.info(f"Edoc {edoc.get('numero_edocument', 'N/A')} procesado exitosamente.")
|
||||
except Exception as e:
|
||||
logger.error(f"Error procesando Edoc {edoc.get('numero_edocument', 'N/A')}: {str(e)}", exc_info=True)
|
||||
continue # Continuar con el siguiente edoc en caso de error
|
||||
|
||||
return {
|
||||
"status": "pending",
|
||||
"total_documentos": len(numeros_documentos),
|
||||
"message": "La orquestación de descarga masiva ha sido registrada."
|
||||
}
|
||||
|
||||
|
||||
def extract_pdf_bytes_from_xml_content(xml_content: str):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from celery_app import celery_app
|
||||
|
||||
from .services import obtener_edoc, obtener_edocs_masivo
|
||||
from .services import obtener_edoc
|
||||
import asyncio # Necesario para ejecutar funciones async dentro de Celery
|
||||
|
||||
@celery_app.task(bind=True)
|
||||
@@ -23,21 +23,3 @@ def process_edoc_download_request(self, edoc_data: dict):
|
||||
# Es crucial volver a lanzar la excepción para que Celery la marque como fallida
|
||||
raise e
|
||||
|
||||
@celery_app.task(bind=True)
|
||||
def process_edocs_masivo_download_request(self, edoc_data: dict):
|
||||
"""
|
||||
Tarea de Celery para procesar la descarga de múltiples documentos edoc.
|
||||
Esta tarea orquesta la ejecución, pero puede delegar en el servicio.
|
||||
"""
|
||||
try:
|
||||
# Ejecutar la función asíncrona dentro del hilo síncrono de Celery
|
||||
loop = asyncio.get_event_loop()
|
||||
result = loop.run_until_complete(obtener_edocs_masivo(**edoc_data))
|
||||
|
||||
return {"status": "success", "result": result}
|
||||
except Exception as e:
|
||||
self.update_state(
|
||||
state='FAILURE',
|
||||
meta={'exc_type': type(e).__name__, 'exc_message': str(e)}
|
||||
)
|
||||
raise
|
||||
Reference in New Issue
Block a user