158 lines
5.8 KiB
Python
158 lines
5.8 KiB
Python
import requests
|
|
from app.config import logger
|
|
from typing import Optional, Dict, Any, Tuple
|
|
|
|
|
|
def estado_factura(uuid_str: str,
|
|
config,
|
|
) -> Tuple[bool, Optional[Dict[str, Any]], Optional[str]]:
|
|
"""
|
|
Llama al endpoint de Verifacti para cosultar el estado de registro.
|
|
|
|
Retorna:
|
|
(ok, data, error)
|
|
- ok: True si la llamada fue exitosa y resultado == 'IDENTIFICADO'
|
|
- data: dict con la respuesta JSON completa
|
|
- error: mensaje de error si algo falló
|
|
"""
|
|
url = config['VERIFACTU_BASE_URL'] + "/verifactu/status"
|
|
timeout: int = 10
|
|
headers = {"Content-Type": "application/json",
|
|
"Accept": "application/json"}
|
|
headers["Authorization"] = "Bearer " + config['VERIFACTU_API_KEY']
|
|
params = {"uuid": uuid_str}
|
|
|
|
try:
|
|
resp = requests.get(
|
|
url, headers=headers, params=params, timeout=timeout)
|
|
|
|
if resp.status_code == 200:
|
|
try:
|
|
data = resp.json()
|
|
except ValueError:
|
|
return {"ok": False, "status": 200, "error": "Respuesta 200 sin JSON válido", "raw": resp.text}
|
|
return {"ok": True, "status": 200, "data": data}
|
|
|
|
if resp.status_code == 400:
|
|
try:
|
|
body = resp.json()
|
|
msg = body.get(
|
|
"error") or "Error de validación (400) sin detalle"
|
|
except ValueError:
|
|
msg = f"Error de validación (400): {resp.text}"
|
|
return {"ok": False, "status": 400, "error": msg}
|
|
|
|
# Otros códigos: devuelve mensaje genérico, intenta extraer JSON si existe
|
|
try:
|
|
body = resp.json()
|
|
msg = body.get("error") or body
|
|
return {"ok": False, "status": resp.status_code, "error": str(msg)}
|
|
except ValueError:
|
|
return {"ok": False, "status": resp.status_code, "error": f"HTTP {resp.status_code}", "raw": resp.text}
|
|
|
|
except requests.RequestException as e:
|
|
logger.error("Error de conexión con la API Verifacti: %s", e)
|
|
return False, None, str(e)
|
|
except ValueError as e:
|
|
logger.error("Respuesta no es JSON válido: %s", e)
|
|
return False, None, "Respuesta no es JSON válido"
|
|
|
|
|
|
def crear_factura(payload,
|
|
config,
|
|
) -> Tuple[bool, Optional[Dict[str, Any]], Optional[str]]:
|
|
"""
|
|
Llama al endpoint de Verifacti para crear una factura.
|
|
|
|
Retorna:
|
|
(ok, data, error)
|
|
- ok: True si la llamada fue exitosa y resultado == 'IDENTIFICADO'
|
|
- data: dict con la respuesta JSON completa
|
|
- error: mensaje de error si algo falló
|
|
"""
|
|
url = config['VERIFACTU_BASE_URL'] + "/verifactu/create"
|
|
timeout: int = 10
|
|
headers = {"Content-Type": "application/json",
|
|
"Accept": "application/json"}
|
|
headers["Authorization"] = "Bearer " + config['VERIFACTU_API_KEY']
|
|
|
|
try:
|
|
resp = requests.post(
|
|
url, json=payload, headers=headers, timeout=timeout)
|
|
|
|
if resp.status_code == 200:
|
|
try:
|
|
data = resp.json()
|
|
# logger.info(data)
|
|
except ValueError:
|
|
return {"ok": False, "status": 200, "error": "Respuesta 200 sin JSON válido", "raw": resp.text}
|
|
return {"ok": True, "status": 200, "data": data}
|
|
|
|
if resp.status_code == 400:
|
|
try:
|
|
body = resp.json()
|
|
msg = body.get(
|
|
"error") or "Error de validación (400) sin detalle"
|
|
except ValueError:
|
|
msg = f"Error de validación (400): {resp.text}"
|
|
return {"ok": False, "status": 400, "error": msg}
|
|
|
|
# Otros códigos: devuelve mensaje genérico, intenta extraer JSON si existe
|
|
try:
|
|
body = resp.json()
|
|
msg = body.get("error") or body
|
|
return {"ok": False, "status": resp.status_code, "error": str(msg)}
|
|
except ValueError:
|
|
return {"ok": False, "status": resp.status_code, "error": f"HTTP {resp.status_code}", "raw": resp.text}
|
|
|
|
except requests.RequestException as e:
|
|
logger.error("Error de conexión con la API Verifacti: %s", e)
|
|
return False, None, str(e)
|
|
except ValueError as e:
|
|
logger.error("Respuesta no es JSON válido: %s", e)
|
|
return False, None, "Respuesta no es JSON válido"
|
|
|
|
|
|
def validar_nif(
|
|
nif: str,
|
|
nombre: str,
|
|
config,
|
|
) -> Tuple[bool, Optional[Dict[str, Any]], Optional[str]]:
|
|
"""
|
|
Llama al endpoint de Verifacti para validar un NIF.
|
|
|
|
Retorna:
|
|
(ok, data, error)
|
|
- ok: True si la llamada fue exitosa y resultado == 'IDENTIFICADO'
|
|
- data: dict con la respuesta JSON completa
|
|
- error: mensaje de error si algo falló
|
|
"""
|
|
url = config['VERIFACTU_BASE_URL'] + "/nifs/validar"
|
|
timeout: int = 10
|
|
headers = {"Content-Type": "application/json",
|
|
"Accept": "application/json"}
|
|
headers["Authorization"] = "Bearer " + config['VERIFACTU_NIFS_API_KEY']
|
|
payload = {"nif": nif,
|
|
"nombre": nombre,
|
|
}
|
|
|
|
try:
|
|
resp = requests.post(
|
|
url, json=payload, headers=headers, timeout=timeout)
|
|
if resp.status_code != 200:
|
|
logger.info(f"ERRRRRROOOOOOORRRRR LLAMADA REST API")
|
|
# return False, None, f"HTTP {resp.status_code}: {resp.text}"
|
|
|
|
data = resp.json()
|
|
resultado = data.get("resultado", "NO IDENTIFICADO")
|
|
logger.info(f"Resultado Verifacti: {resultado}")
|
|
|
|
return resultado == "IDENTIFICADO"
|
|
|
|
except requests.RequestException as e:
|
|
logger.error("Error de conexión con la API Verifacti: %s", e)
|
|
return False, None, str(e)
|
|
except ValueError as e:
|
|
logger.error("Respuesta no es JSON válido: %s", e)
|
|
return False, None, "Respuesta no es JSON válido"
|