Lo mismo que COVE_XML
This commit is contained in:
@@ -6,6 +6,15 @@ from typing import Dict, Any
|
||||
import xml.etree.ElementTree as ET
|
||||
import base64
|
||||
import re
|
||||
import os
|
||||
from cryptography.hazmat.primitives import serialization, hashes
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from dotenv import load_dotenv
|
||||
from pathlib import Path
|
||||
from core.config import settings
|
||||
|
||||
# Cargar variables de entorno
|
||||
load_dotenv()
|
||||
|
||||
from schemas.serviceSchema import ServiceBaseSchema
|
||||
|
||||
@@ -14,6 +23,26 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
from controllers.XMLController import xml_controller
|
||||
|
||||
def load_cert_base64(cert_path: str) -> str:
|
||||
with open(cert_path, 'rb') as cert_file:
|
||||
cert_data = cert_file.read()
|
||||
return base64.b64encode(cert_data).decode()
|
||||
|
||||
def sign_chain_original(key_path: str, password: str, cadena_original: str) -> str:
|
||||
with open(key_path, 'rb') as key_file:
|
||||
private_key = serialization.load_pem_private_key(
|
||||
key_file.read(),
|
||||
password=password.encode() if password else None
|
||||
)
|
||||
|
||||
signature = private_key.sign(
|
||||
cadena_original.encode(),
|
||||
padding.PKCS1v15(),
|
||||
hashes.SHA256()
|
||||
)
|
||||
|
||||
return base64.b64encode(signature).decode()
|
||||
|
||||
|
||||
def validate_pedimento_data(response_service: Dict[str, Any], credenciales: Dict[str, Any]) -> tuple: # Testeado
|
||||
"""
|
||||
@@ -881,4 +910,86 @@ async def get_soap_edocument(credenciales, response_service, soap_controller, ed
|
||||
logger.error(f"Traceback: {traceback.format_exc()}")
|
||||
raise HTTPException(status_code=500, detail=f"Error interno al procesar acuse: {str(e)}")
|
||||
|
||||
async def get_soap_cove(credenciales, response_service, soap_controller, cove, idx):
|
||||
"""
|
||||
Procesa la petición SOAP para obtener el COVE de un pedimento y guarda el documento.
|
||||
|
||||
Args:
|
||||
credenciales: Diccionario con credenciales VUCEM (usuario, password)
|
||||
response_service: Respuesta del servicio con datos del pedimento
|
||||
soap_controller: Instancia del controlador SOAP
|
||||
|
||||
Returns:
|
||||
dict: Respuesta con el servicio, respuesta SOAP y documento guardado
|
||||
|
||||
Raises:
|
||||
HTTPException: Si hay errores en la petición SOAP o al guardar el documento
|
||||
"""
|
||||
try:
|
||||
# Extraer credenciales
|
||||
username, password, aduana, patente, pedimento, numero_operacion = validate_pedimento_data(response_service, credenciales)
|
||||
|
||||
# Cadena original que vas a firmar
|
||||
cadena_original = f"|{username}|{cove['numero_cove']}|"
|
||||
|
||||
# Obtener certificado base64 y firma
|
||||
certificado = load_cert_base64(settings.CERT_PATH)
|
||||
firma = sign_chain_original(settings.KEY_PATH, settings.KEY_PASSWORD, cadena_original)
|
||||
|
||||
logger.info(f"Datos para SOAP - Usuario: {username}, Aduana: {aduana}, Patente: {patente}, Pedimento: {pedimento}, Numero Operacion: {numero_operacion}")
|
||||
|
||||
# Generar template SOAP
|
||||
soap_xml = soap_controller.generate_cove_template(
|
||||
username=username,
|
||||
password=password,
|
||||
certificado=certificado,
|
||||
firma=firma,
|
||||
cove=cove['numero_cove']
|
||||
)
|
||||
|
||||
### >>> AQUÍ SE AÑADE EL LOGGER.DEBUG <<< ###
|
||||
logger.debug(f"XML SOAP generado: {soap_xml}") # 👈 Registra el XML completo
|
||||
|
||||
# Realizar petición SOAP
|
||||
logger.info("Realizando petición SOAP...")
|
||||
|
||||
soap_response = await soap_controller.make_request_async(
|
||||
"ventanilla/ConsultarEdocumentService?wsdl",
|
||||
data=soap_xml,
|
||||
)
|
||||
|
||||
if (soap_response) and (not soap_error(soap_response)):
|
||||
logger.info(f"Petición SOAP exitosa - Status: {soap_response.status_code}")
|
||||
|
||||
remesas = 1 if response_service['pedimento'].get('remesas', 0) else 0
|
||||
patente = response_service['pedimento'].get('patente', 'N/A')
|
||||
aduana = response_service['pedimento'].get('aduana', 'N/A')
|
||||
no_partidas = response_service['pedimento'].get('numero_partidas', 0)
|
||||
tipo_operacion = response_service['pedimento'].get('tipo_operacion', 'N/A')
|
||||
pedimento = response_service['pedimento'].get('pedimento', 'N/A')
|
||||
|
||||
_file_name = f"vu_COVE_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}_{idx}.xml"
|
||||
|
||||
document_response = await rest_controller.post_document(
|
||||
soap_response=soap_response,
|
||||
organizacion=response_service['organizacion'],
|
||||
pedimento=response_service['pedimento']['id'],
|
||||
file_name=_file_name,
|
||||
document_type=8
|
||||
)
|
||||
|
||||
return {
|
||||
"servicio": response_service,
|
||||
"documento": document_response
|
||||
}
|
||||
else:
|
||||
logger.error("Error en petición SOAP")
|
||||
raise HTTPException(status_code=500, detail="Error en la petición SOAP al servicio VUCEM")
|
||||
except HTTPException:
|
||||
# Re-lanzar HTTPExceptions sin modificar
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error inesperado en get_acuse cove: {e}")
|
||||
import traceback
|
||||
logger.error(f"Traceback: {traceback.format_exc()}")
|
||||
raise HTTPException(status_code=500, detail=f"Error interno al procesar acuse cove: {str(e)}")
|
||||
|
||||
Reference in New Issue
Block a user