#!/usr/bin/env python3 """TaxVega Python SDK — stdlib only (urllib), no dependencies. Canon: TaxVega computes and proves (tv1_* digests); it never moves money. Money always flows through the merchant's own gateway. Usage: from tv_client import TaxVegaClient tv = TaxVegaClient("https://taxvega.makomemory.com", key="tv_...") res = tv.resolve("DE", buyer="b2c", vat_valid=False) print(res["rate"], res["rule_digest"]) CLI (handy for smoke tests): TAXVEGA_ENGINE=https://taxvega.makomemory.com python3 tv_client.py resolve DE b2c TAXVEGA_KEY=tv_... python3 tv_client.py chain demo python3 tv_client.py rules RU Fail-closed contract: any failure raises TaxVegaError (with .code) — the caller gets no tax numbers it did not receive from the engine. Transient failures (network, HTTP 429, 5xx) are retried 3 times with backoff; 4xx never retry. """ import json import os import sys import time import urllib.error import urllib.parse import urllib.request __version__ = "1.0.0" RETRIES = 3 BACKOFF = 0.5 # seconds; doubles each retry class TaxVegaError(Exception): """Base error. .code: HTTP status (int) or 'network'/'parse'; .detail: engine message.""" def __init__(self, code, detail=""): self.code = code self.detail = detail or "" super().__init__("TaxVega {}{}".format(code, (": " + detail) if detail else "")) class TaxVegaAuthError(TaxVegaError): # 401 — missing/invalid auth for this endpoint pass class TaxVegaPaymentRequiredError(TaxVegaError): # 402 — unknown/rejected cabinet key pass class TaxVegaRateLimitError(TaxVegaError): # 429 — quota exceeded (retried) pass class TaxVegaServerError(TaxVegaError): # 5xx — engine failure (retried) pass class TaxVegaUnavailableError(TaxVegaError): # network unreachable / unparsable answer pass class TaxVegaClient(object): def __init__(self, engine_url, key=None, timeout=10.0, retries=RETRIES): self.engine_url = engine_url.rstrip("/") self.key = key self.timeout = timeout self.retries = retries # ---------- transport ---------- def _request(self, method, path, params=None, body=None): url = self.engine_url + path if params: url += "?" + urllib.parse.urlencode(params) headers = {"Accept": "application/json", "User-Agent": "TaxVega-Python/" + __version__} if self.key: headers["Authorization"] = "Bearer " + self.key # never put the key in the URL data = json.dumps(body).encode("utf-8") if body is not None else None if data: headers["Content-Type"] = "application/json" last_err = None for attempt in range(self.retries): if attempt: time.sleep(BACKOFF * (2 ** (attempt - 1))) # 0.5s, 1s try: req = urllib.request.Request(url, data=data, headers=headers, method=method) with urllib.request.urlopen(req, timeout=self.timeout) as r: return json.loads(r.read().decode("utf-8")) except urllib.error.HTTPError as e: detail = "" try: detail = json.loads(e.read().decode("utf-8")).get("error", "") except Exception: pass err = self._map_http(e.code, detail) if e.code == 429 or e.code >= 500: last_err = err continue # transient — retry raise err # 4xx — do not retry except (urllib.error.URLError, OSError, TimeoutError) as e: last_err = TaxVegaUnavailableError("network", str(getattr(e, "reason", e))) continue # transient — retry raise last_err or TaxVegaUnavailableError("network", "exhausted retries") @staticmethod def _map_http(status, detail): if status == 401: return TaxVegaAuthError(status, detail) if status == 402: return TaxVegaPaymentRequiredError(status, detail) if status == 429: return TaxVegaRateLimitError(status, detail) if status >= 500: return TaxVegaServerError(status, detail) return TaxVegaError(status, detail) # ---------- API ---------- def resolve(self, country, buyer="b2c", vat_valid=False): """Resolve the tax moment for a sale: regime, rate, tv1_* digest.""" return self._request("GET", "/v1/resolve", params={ "country": country, "buyer": buyer, "vat_valid": 1 if vat_valid else 0, }) def chain(self, participants, links): """Multi-party chain. participants: [{id, kind, country, role}]; links: [{from, to, type, amount}]. Requires a cabinet key (Bearer tv_...).""" return self._request("POST", "/v1/chain", body={ "participants": participants, "links": links, }) def public_rules(self, country=None): """Public rules table for a country (sources + effective dates + digest).""" return self._request("GET", "/v1/public/rules", params={"country": country} if country else None) # ---------- CLI smoke tool ---------- def _cli(argv): engine = os.environ.get("TAXVEGA_ENGINE", "http://127.0.0.1:8797") tv = TaxVegaClient(engine, key=os.environ.get("TAXVEGA_KEY") or None) cmd = argv[0] if argv else "help" if cmd == "resolve" and len(argv) >= 2: out = tv.resolve(argv[1], buyer=argv[2] if len(argv) > 2 else "b2c", vat_valid=len(argv) > 3 and argv[3] == "1") elif cmd == "rules": out = tv.public_rules(argv[1] if len(argv) > 1 else None) elif cmd == "chain" and argv[-1] == "demo": out = tv.chain( [{"id": "p0", "kind": "company", "country": "RU", "role": "seller"}, {"id": "p1", "kind": "company", "country": "DE", "role": "buyer"}], [{"from": "p0", "to": "p1", "type": "goods", "amount": 100000}]) else: print("usage: resolve COUNTRY [b2c|b2b [1]] | rules [COUNTRY] | chain demo " "(env: TAXVEGA_ENGINE, TAXVEGA_KEY)") return 2 print(json.dumps(out, ensure_ascii=False, indent=2)) return 0 if __name__ == "__main__": try: sys.exit(_cli(sys.argv[1:])) except TaxVegaError as e: print("TaxVegaError: code={} detail={}".format(e.code, e.detail), file=sys.stderr) sys.exit(1)