Se agrego coves

This commit is contained in:
2025-08-06 14:28:34 -06:00
parent 543a3558ca
commit ea40a0c74e
3 changed files with 34 additions and 26 deletions

View File

@@ -1142,16 +1142,14 @@ async def get_cove(request: ServiceRemesaSchema):
# Obtener COVES # Obtener COVES
logger.info("Obteniendo COVES...") logger.info("Obteniendo COVES...")
try: try:
coves = await rest_controller.get_coves(service_data['pedimento']['id']) coves = await rest_controller.get_coves(service_data['pedimento']['id'])
if not coves: if not coves:
logger.warning("No se encontraron COVES para el pedimento") logger.warning("No se encontraron COVES para el pedimento")
await _update_service_status(service_data['id'], ESTADO_ERROR, service_data, operation_name) await _update_service_status(service_data['id'], ESTADO_ERROR, service_data, operation_name)
raise HTTPException(status_code=404, detail="No se encontraron COVES para el pedimento") raise HTTPException(status_code=404, detail="No se encontraron COVES para el pedimento")
logger.info(f"Se encontraron {len(coves)} COVES") logger.info(f"Se encontraron {len(coves)} COVES")
except HTTPException: except HTTPException:
raise raise
except Exception as e: except Exception as e:
@@ -1183,7 +1181,7 @@ async def get_cove(request: ServiceRemesaSchema):
try: try:
logger.info(f"Procesando cove para documento {idx + 1}: {cove['numero_cove']}") logger.info(f"Procesando cove para documento {idx + 1}: {cove['numero_cove']}")
# Procesar cove del documento
soap_response = await get_soap_cove( soap_response = await get_soap_cove(
credenciales=credentials, credenciales=credentials,
response_service=service_data, response_service=service_data,

View File

@@ -253,25 +253,27 @@ class APIController:
""" """
return await self._make_request_async('PUT', f'customs/edocuments/{edocument_id}/', data=data) return await self._make_request_async('PUT', f'customs/edocuments/{edocument_id}/', data=data)
async def get_cer(self, id: str) -> Dict[str, Any]: async def get_cer(self, id: str) -> bytes:
""" """
Método para obtener un certificado específico desde la API. Método para obtener un certificado específico desde la API (como binario).
Args: Args:
id: UUID del certificado a consultar id: UUID del certificado a consultar
Returns:
bytes: Contenido binario del certificado
""" """
return await self._make_request_async('GET', f'vucem/vucem/{id}/download_cer/') return await self._make_request_async('GET', f'vucem/vucem/{id}/download_cer/', return_bytes=True)
async def get_key(self, id: str) -> Dict[str, Any]: async def get_key(self, id: str) -> bytes:
""" """
Método para obtener una llave específica desde la API. Método para obtener una llave específica desde la API (como binario).
Args: Args:
id: UUID de la llave a consultar id: UUID de la llave a consultar
Returns:
bytes: Contenido binario de la llave
""" """
return await self._make_request_async('GET', f'vucem/vucem/{id}/download_key/') return await self._make_request_async('GET', f'vucem/vucem/{id}/download_key/', return_bytes=True)
async def _make_request_async(self, method: str, endpoint: str, data=None): async def _make_request_async(self, method: str, endpoint: str, data=None, return_bytes: bool = False):
""" """
Método asíncrono para hacer peticiones a la API usando httpx. Método asíncrono para hacer peticiones a la API usando httpx.
""" """
@@ -296,9 +298,11 @@ class APIController:
response.raise_for_status() response.raise_for_status()
logger.info(f"Respuesta exitosa: {response.status_code}") logger.info(f"Respuesta exitosa: {response.status_code}")
if return_bytes:
result = response.json() if response.content else {} return response.content
return result else:
result = response.json() if response.content else {}
return result
except httpx.TimeoutException as e: except httpx.TimeoutException as e:
logger.error(f"Timeout en petición a {url}: {e}") logger.error(f"Timeout en petición a {url}: {e}")

View File

@@ -934,13 +934,19 @@ async def get_soap_cove(credenciales, response_service, soap_controller, cove, i
# Cadena original que vas a firmar # Cadena original que vas a firmar
cadena_original = f"|{username}|{cove['numero_cove']}|" cadena_original = f"|{username}|{cove['numero_cove']}|"
# Obtener certificado base64 y firma # Obtener certificado base64 y firma (await async calls)
cer = rest_controller.get_cer(credenciales['id']) cer = await rest_controller.get_cer(credenciales['id'])
if cer is None:
logger.error(f"No se pudo obtener el certificado (cer) para credencial ID: {credenciales['id']}")
raise HTTPException(status_code=500, detail="No se pudo obtener el certificado para firmar el COVE")
certificado = base64.b64encode(cer).decode('utf-8') certificado = base64.b64encode(cer).decode('utf-8')
# Obtener la key como binario y guardarla en un archivo temporal # Obtener la key como binario y guardarla en un archivo temporal
import tempfile import tempfile
key_bytes = rest_controller.get_key(credenciales['id']) key_bytes = await rest_controller.get_key(credenciales['id'])
if key_bytes is None:
logger.error(f"No se pudo obtener la llave privada (key) para credencial ID: {credenciales['id']}")
raise HTTPException(status_code=500, detail="No se pudo obtener la llave privada para firmar el COVE")
with tempfile.NamedTemporaryFile(delete=False) as tmp_key_file: with tempfile.NamedTemporaryFile(delete=False) as tmp_key_file:
tmp_key_file.write(key_bytes) tmp_key_file.write(key_bytes)
tmp_key_path = tmp_key_file.name tmp_key_path = tmp_key_file.name