""" tenants.py — per-tenant billing configuration registry. Loads tenant definitions from a JSON file (TENANTS_CONFIG_PATH, defaulting to tenants.json) mapping a tenant_slug (the URL segment each client's Stripe webhook is registered against, e.g. /webhook/stripe/) to that tenant's own Frappe credentials and Stripe webhook secret. Real values live in tenants.json (gitignored, never committed); tenants.example.json documents the shape with placeholders, the same pattern as .env/.env.example. Also owns the one FrappeClient instance per tenant, cached for the life of the process so each tenant's circuit breaker state persists across requests — ENTERPRISE_STANDARDS.md's "circuit breaker singletons... instantiated once, imported everywhere, never instantiated inside a service" rule, just keyed per tenant instead of a single global instance, since each tenant has its own independent Frappe API to guard. """ import json import os from datetime import datetime, timedelta, timezone from .frappe_client import FrappeClient def _default_config_path(): """Resolve the tenants config path from TENANTS_CONFIG_PATH, defaulting to a local file for tests/dev.""" return os.environ.get("TENANTS_CONFIG_PATH", "tenants.json") class TenantConfig: """ One tenant's billing configuration, loaded from tenants.json. trial_start_date/trial_days are optional and independent of Stripe entirely — see trial_has_expired(). A tenant with neither set (the default for an existing entry) never gets locked out by the trial timer, only by a real invoice.payment_failed. stripe_restricted_key/stripe_customer_id/stripe_payment_link_url are also optional, and back the billing status page's read-only Stripe lookups (see stripe_status.py) — a tenant without them configured just gets an "unconfigured" billing status rather than an error. Deliberately a Stripe Restricted key (read-only, scoped to Invoices + Subscriptions), never the full secret key: this code only ever needs to look, never charge, refund, or modify anything. """ def __init__( self, slug, frappe_api_url, frappe_api_key, frappe_api_secret, stripe_webhook_secret, trial_start_date=None, trial_days=None, stripe_restricted_key=None, stripe_customer_id=None, stripe_payment_link_url=None, ): self.slug = slug self.frappe_api_url = frappe_api_url self.frappe_api_key = frappe_api_key self.frappe_api_secret = frappe_api_secret self.stripe_webhook_secret = stripe_webhook_secret self.trial_start_date = trial_start_date self.trial_days = trial_days self.stripe_restricted_key = stripe_restricted_key self.stripe_customer_id = stripe_customer_id self.stripe_payment_link_url = stripe_payment_link_url def trial_has_expired(tenant, now=None): """ True if this tenant has a configured trial (both trial_start_date and trial_days set) and that window has fully elapsed as of `now`. Data flow: tenant (TenantConfig) — read-only; trial_start_date/trial_days now (datetime|None) — defaults to the real current UTC time; overridable so tests don't depend on the real clock returns (bool) """ if not tenant.trial_start_date or tenant.trial_days is None: return False now = now or datetime.now(timezone.utc) start = datetime.fromisoformat(tenant.trial_start_date) if start.tzinfo is None: start = start.replace(tzinfo=timezone.utc) return now >= start + timedelta(days=tenant.trial_days) def load_tenants(config_path=None): """ Reads the tenants JSON file into a dict of slug -> TenantConfig. Data flow: config_path (str) — path to tenants.json; defaults to TENANTS_CONFIG_PATH returns (dict) — {tenant_slug: TenantConfig} Steps: 1. Read and parse the JSON file 2. Build one TenantConfig per entry, keyed by its slug """ # Step 1: read the raw config path = config_path or _default_config_path() with open(path) as f: raw = json.load(f) # Step 2: one TenantConfig per configured tenant, keyed by slug tenants = {} for slug, entry in raw.items(): tenants[slug] = TenantConfig( slug=slug, frappe_api_url=entry["frappe_api_url"], frappe_api_key=entry["frappe_api_key"], frappe_api_secret=entry["frappe_api_secret"], stripe_webhook_secret=entry["stripe_webhook_secret"], trial_start_date=entry.get("trial_start_date"), trial_days=entry.get("trial_days"), stripe_restricted_key=entry.get("stripe_restricted_key"), stripe_customer_id=entry.get("stripe_customer_id"), stripe_payment_link_url=entry.get("stripe_payment_link_url"), ) return tenants class TenantRegistry: """ Holds every configured tenant plus one cached FrappeClient per tenant. Data flow: tenants (dict) — {tenant_slug: TenantConfig}, from load_tenants() methods below — look up a tenant, or its cached FrappeClient """ def __init__(self, tenants): self._tenants = tenants self._frappe_clients = {} def get(self, slug): """Returns the TenantConfig for slug, or None if unknown.""" return self._tenants.get(slug) def frappe_client_for(self, slug): """ Returns the cached FrappeClient for this tenant, constructing it on first use so its circuit breaker starts CLOSED once and stays that way across requests, rather than resetting on every call. Data flow: slug (str) — a slug already confirmed to exist via get() returns (FrappeClient) — the same instance for every call with this slug """ if slug not in self._frappe_clients: tenant = self._tenants[slug] self._frappe_clients[slug] = FrappeClient( base_url=tenant.frappe_api_url, api_key=tenant.frappe_api_key, api_secret=tenant.frappe_api_secret, ) return self._frappe_clients[slug] def all_slugs(self): """Returns every configured tenant slug, for /health to report per-tenant reachability.""" return list(self._tenants.keys())