import httpx from typing import Optional TNS_BASE = "https://api.tns.co" async def get_tns_token(empresa: str, usuario: str, password: str) -> tuple: """Hace login en TNS v2 y devuelve (token, error_msg).""" try: async with httpx.AsyncClient(timeout=30) as client: resp = await client.post( f"{TNS_BASE}/v2/Acceso/Login", json={"codigoEmpresa": empresa, "nombreUsuario": usuario, "contrasenia": password}, ) body = resp.json() if resp.is_success and body.get("status"): return body["data"], None return None, body.get("message") or f"HTTP {resp.status_code}" except Exception as e: return None, str(e) async def send_json( url: str, json_data: dict, method: str = "POST", headers: Optional[dict] = None, timeout: int = 30, ) -> dict: default_headers = {"Content-Type": "application/json"} if headers: default_headers.update(headers) try: async with httpx.AsyncClient(timeout=timeout) as client: if method == "POST": resp = await client.post(url, json=json_data, headers=default_headers) elif method == "PUT": resp = await client.put(url, json=json_data, headers=default_headers) else: resp = await client.get(url, headers=default_headers) return { "status_code": resp.status_code, "success": resp.is_success, "body": resp.text, "headers": dict(resp.headers), } except httpx.TimeoutException: return {"status_code": 0, "success": False, "body": "Timeout", "headers": {}} except Exception as e: return {"status_code": 0, "success": False, "body": str(e), "headers": {}}