""" stripe_status.py — read-only Stripe lookups backing the billing status page: subscription state + days until next bill, and recent invoices with their hosted receipt/PDF links. Uses a Stripe Restricted API key (read-only, scoped to Invoices + Subscriptions) per tenant via stripe.StripeClient — a per-call client object, not the shared global stripe.api_key, since this process serves multiple tenants concurrently and mutating one shared global key per request would race across tenants. Least privilege: this code only ever needs to look, never charge, refund, or modify anything. """ from datetime import datetime, timezone import stripe class StripeStatusError(Exception): """Raised for any Stripe API failure. Never leaks a raw Stripe error message upstream.""" def _iso(unix_timestamp): """Converts a Stripe API's Unix timestamp field into an ISO 8601 UTC string.""" return datetime.fromtimestamp(unix_timestamp, tz=timezone.utc).isoformat() def get_billing_status(tenant, limit=12): """ Fetches this tenant's current subscription status and recent invoices. Data flow: tenant (TenantConfig) — needs stripe_restricted_key + stripe_customer_id limit (int) — max invoices to return, most recent first returns (dict) — { "subscription_status": str | None, # e.g. "trialing", "active", "past_due" "current_period_end": iso8601 str | None, "trial_end": iso8601 str | None, "invoices": [{"id", "created", "amount_paid", "currency", "status", "hosted_invoice_url"}, ...], "payment_link_url": str | None, } Steps: 1. A tenant with no Stripe read-access configured yet gets an "unconfigured" status rather than an error — this is an optional, opt-in feature per tenant, same as the trial timer 2. Fetch this customer's most recent Subscription 3. Fetch this customer's most recent Invoices """ # Step 1: nothing configured — a normal, expected state, not a failure if not tenant.stripe_restricted_key or not tenant.stripe_customer_id: return { "subscription_status": None, "current_period_end": None, "trial_end": None, "invoices": [], "payment_link_url": tenant.stripe_payment_link_url, } client = stripe.StripeClient(tenant.stripe_restricted_key) try: # Step 2: this tenant's current subscription, if any subs = client.subscriptions.list(params={"customer": tenant.stripe_customer_id, "limit": 1}) # Step 3: most recent invoices first invoices = client.invoices.list(params={"customer": tenant.stripe_customer_id, "limit": limit}) except stripe.StripeError as exc: raise StripeStatusError("Failed to fetch billing status from Stripe") from exc sub = subs.data[0] if subs.data else None return { "subscription_status": sub.status if sub else None, "current_period_end": _iso(sub.current_period_end) if sub else None, "trial_end": _iso(sub.trial_end) if sub and sub.trial_end else None, "invoices": [ { "id": inv.id, "created": _iso(inv.created), "amount_paid": inv.amount_paid, "currency": inv.currency, "status": inv.status, "hosted_invoice_url": inv.hosted_invoice_url, } for inv in invoices.data ], "payment_link_url": tenant.stripe_payment_link_url, }