subscription_view.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. """Surface-agnostic core for the ``/subscription`` TUI screen.
  2. Companion to :mod:`agent.billing_view` — same fail-open philosophy (``logged_in=False``
  3. when not logged in / portal unreachable; never crash) and decimal money end-to-end.
  4. The TUI drives plan changes in-terminal (preview, then schedule a downgrade/cancel/resume
  5. or apply an upgrade); the portal deep-link (``portal_url`` + ``org_id``) is the fallback
  6. for an upgrade that needs 3DS / was declined. A 404 from NAS takes the fail-open path.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. import os
  11. from dataclasses import dataclass
  12. from decimal import Decimal
  13. from typing import Any, Optional
  14. from agent.billing_view import OrgRoleCapability, fetch_portal_state, format_money, parse_money, parse_org_fields
  15. logger = logging.getLogger(__name__)
  16. @dataclass(frozen=True)
  17. class CurrentSubscription:
  18. """Active subscription (``None``, not this object, = no plan). NAS guarantees ``tier_id`` /
  19. ``tier_name`` / ``monthly_credits`` / ``cycle_ends_at`` are set; the rest are optional."""
  20. tier_id: Optional[str] = None
  21. tier_name: Optional[str] = None
  22. monthly_credits: Optional[Decimal] = None
  23. credits_remaining: Optional[Decimal] = None
  24. cycle_ends_at: Optional[str] = None # ISO
  25. pending_downgrade_tier_name: Optional[str] = None
  26. pending_downgrade_at: Optional[str] = None # ISO
  27. cancel_at_period_end: bool = False
  28. cancellation_effective_at: Optional[str] = None # ISO
  29. @dataclass(frozen=True)
  30. class SubscriptionTier:
  31. """Tier-picker row (NAS ``SubscriptionTierOption``). ``is_current`` = active plan (shown, not
  32. selectable); ``is_enabled=False`` = grandfathered, no longer selectable; ``tier_order`` sorts
  33. the picker and drives the upgrade-vs-downgrade hint."""
  34. tier_id: str
  35. name: str
  36. tier_order: int = 0
  37. dollars_per_month: Optional[Decimal] = None
  38. monthly_credits: Optional[Decimal] = None
  39. is_current: bool = False
  40. is_enabled: bool = True
  41. @dataclass(frozen=True)
  42. class SubscriptionChangePreview:
  43. """Parsed ``POST /api/billing/subscription/preview``. ``effect``: ``charge_now`` (upgrade; prorated
  44. ``amount_due_now_cents``) · ``scheduled`` (downgrade / same-price change at ``effective_at``) ·
  45. ``no_op`` (already on target) · ``blocked`` (commit refused; ``reason`` says why)."""
  46. effect: str
  47. reason: Optional[str] = None
  48. current_tier_id: Optional[str] = None
  49. current_tier_name: Optional[str] = None
  50. target_tier_id: Optional[str] = None
  51. target_tier_name: Optional[str] = None
  52. monthly_credits_delta: Optional[Decimal] = None
  53. amount_due_now_cents: Optional[int] = None
  54. effective_at: Optional[str] = None # ISO
  55. @dataclass(frozen=True)
  56. class SubscriptionState(OrgRoleCapability):
  57. """Parsed ``GET /api/billing/subscription``. Fail-open: ``logged_in=False``
  58. (empty fields) when not logged in or the portal is unreachable."""
  59. logged_in: bool
  60. org_name: Optional[str] = None
  61. org_id: Optional[str] = None
  62. role: Optional[str] = None # "OWNER" | "ADMIN" | "FINANCE_ADMIN" | "SECURITY_ADMIN" | "MEMBER"
  63. can_change_plan_raw: Optional[bool] = None
  64. context: str = "personal" # "personal" | "team"
  65. current: Optional[CurrentSubscription] = None
  66. tiers: tuple[SubscriptionTier, ...] = () # selectable catalog (picker)
  67. portal_url: Optional[str] = None
  68. error: Optional[str] = None # set when the fetch failed (vs cleanly not-logged-in)
  69. # ── Payload parsing ──────────────────────────────────────────────────────────
  70. def _tier_id(raw: Any) -> Optional[str]:
  71. """Real tier id of a NAS dict, else None ("no plan" is ``current: null``; junk is skipped)."""
  72. return (raw.get("tierId") or raw.get("id") or None) if isinstance(raw, dict) else None
  73. def _parse_current(raw: Any) -> Optional[CurrentSubscription]:
  74. tier_id = _tier_id(raw)
  75. if not tier_id:
  76. return None
  77. return CurrentSubscription(
  78. tier_id=tier_id,
  79. tier_name=raw.get("tierName") or raw.get("name"),
  80. monthly_credits=parse_money(raw.get("monthlyCredits")),
  81. credits_remaining=parse_money(raw.get("creditsRemaining")),
  82. cycle_ends_at=raw.get("cycleEndsAt"),
  83. pending_downgrade_tier_name=raw.get("pendingDowngradeTierName"),
  84. pending_downgrade_at=raw.get("pendingDowngradeAt"),
  85. cancel_at_period_end=bool(raw.get("cancelAtPeriodEnd")),
  86. cancellation_effective_at=raw.get("cancellationEffectiveAt") or None,
  87. )
  88. def _coalesce(*vals: Any) -> Any:
  89. """First non-``None`` value (NAS sends ``0`` for the free tier, which ``x or default`` would drop)."""
  90. return next((v for v in vals if v is not None), None)
  91. def _parse_tier(raw: Any) -> Optional[SubscriptionTier]:
  92. tier_id = _tier_id(raw)
  93. if not tier_id:
  94. return None
  95. return SubscriptionTier(
  96. tier_id=tier_id,
  97. name=raw.get("name") or "",
  98. tier_order=int(_coalesce(raw.get("tierOrder"), 0)),
  99. dollars_per_month=parse_money(raw.get("dollarsPerMonthDisplay")),
  100. monthly_credits=parse_money(raw.get("monthlyCredits")),
  101. is_current=bool(raw.get("isCurrent")),
  102. is_enabled=bool(_coalesce(raw.get("isEnabled"), True)),
  103. )
  104. def subscription_change_preview_from_payload(payload: dict[str, Any]) -> SubscriptionChangePreview:
  105. """Map a raw ``/subscription/preview`` JSON dict into :class:`SubscriptionChangePreview`."""
  106. effect = payload.get("effect")
  107. cents = payload.get("amountDueNowCents")
  108. return SubscriptionChangePreview(
  109. # Unrecognized/missing effect → ``blocked``: fail safe, never charge on a malformed quote.
  110. effect=effect if isinstance(effect, str) else "blocked",
  111. reason=payload.get("reason") or None,
  112. current_tier_id=payload.get("currentTierId"),
  113. current_tier_name=payload.get("currentTierName"),
  114. target_tier_id=payload.get("targetTierId"),
  115. target_tier_name=payload.get("targetTierName"),
  116. monthly_credits_delta=parse_money(payload.get("monthlyCreditsDelta")),
  117. amount_due_now_cents=int(cents) if isinstance(cents, (int, float)) else None,
  118. effective_at=payload.get("effectiveAt") or None,
  119. )
  120. def subscription_state_from_payload(payload: dict[str, Any], *, portal_url: Optional[str] = None) -> SubscriptionState:
  121. """Map a raw ``/api/billing/subscription`` JSON dict into :class:`SubscriptionState`."""
  122. org, can_change_plan_raw = parse_org_fields(payload)
  123. raw_context, raw_tiers = payload.get("context"), payload.get("tiers")
  124. return SubscriptionState(
  125. logged_in=True,
  126. org_name=org.get("name"),
  127. org_id=org.get("id") or None,
  128. role=org.get("role"),
  129. can_change_plan_raw=can_change_plan_raw,
  130. context=raw_context if raw_context in ("personal", "team") else "personal",
  131. current=_parse_current(payload.get("current")),
  132. tiers=tuple(filter(None, map(_parse_tier, raw_tiers))) if isinstance(raw_tiers, list) else (),
  133. portal_url=portal_url,
  134. )
  135. # ── Fail-open builders (the surface front doors) ─────────────────────────────
  136. def build_subscription_state(*, timeout: float = 15.0) -> SubscriptionState:
  137. """Fetch + parse ``GET /api/billing/subscription``; fail-open like ``fetch_portal_state``.
  138. ``HERMES_DEV_SUBSCRIPTION_FIXTURE`` short-circuits to a fixture so every state is testable offline."""
  139. fixture = dev_fixture_subscription_state()
  140. if fixture is not None:
  141. return fixture
  142. return fetch_portal_state(
  143. "get_subscription_state", "subscription",
  144. failed=lambda **kw: SubscriptionState(logged_in=False, **kw),
  145. parse=lambda payload, portal_url: subscription_state_from_payload(payload, portal_url=portal_url),
  146. portal_fallback=lambda base: base, timeout=timeout, log=logger,
  147. )
  148. def subscription_manage_url(state: SubscriptionState, tier_id: Optional[str] = None) -> Optional[str]:
  149. """Build ``{portal_origin}/manage-subscription?org_id=<id>[&plan=<tier_id>]`` (None if unresolvable).
  150. Mirrors the TUI's ``buildManageUrl``: the target is NAS's OWN ``/manage-subscription`` page
  151. (NOT the Stripe Billing Portal). ``org_id`` pins the account in multi-org situations; ``tier_id``
  152. (the stable ``tiers[]`` id, never a name/slug) preselects the plan — the portal ignores an
  153. unknown tier, so it's appended unconditionally.
  154. """
  155. from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
  156. try:
  157. parts = urlsplit(state.portal_url or "")
  158. except Exception:
  159. return None
  160. if parts.scheme not in ("http", "https") or not parts.netloc:
  161. return None
  162. # Preserve unrelated portal query params; org_id / plan are contract-owned
  163. # (org_id before plan — insertion order is the emitted query order).
  164. params = dict(parse_qsl(parts.query, keep_blank_values=True))
  165. params.pop("org_id", None)
  166. params.pop("plan", None)
  167. if state.org_id:
  168. params["org_id"] = state.org_id
  169. if tier_id:
  170. params["plan"] = tier_id
  171. return urlunsplit((parts.scheme, parts.netloc, "/manage-subscription", urlencode(params), ""))
  172. # ── Shared plan-catalog helpers (CLI Free catalog + paid picker) ─────────────
  173. def selectable_tiers(state: SubscriptionState) -> list[SubscriptionTier]:
  174. """Enabled paid tiers other than the current plan, cheapest first (dropping to free is a cancellation)."""
  175. return sorted(
  176. (t for t in (state.tiers or ()) if t.is_enabled and not t.is_current and (t.tier_order or 0) > 0),
  177. key=lambda t: t.tier_order or 0,
  178. )
  179. def format_tier_row(tier: SubscriptionTier) -> str:
  180. """``name · $X/mo[ · $Y credits/mo]`` (grouped money, like the TUI); credits suffix only when > 0."""
  181. row = f"{tier.name} · {format_money(tier.dollars_per_month, grouped=True)}/mo"
  182. mc = tier.monthly_credits
  183. if mc is not None and mc > 0:
  184. row += f" · {format_money(mc, grouped=True)} credits/mo"
  185. return row
  186. def is_upgrade(state: SubscriptionState, tier_id: str) -> bool:
  187. """True when ``tier_id`` ranks above the current plan by ``tier_order``. Prefers the
  188. active subscription's tier; falls back to the ``tiers[]`` ``is_current`` marker, else 0."""
  189. tiers = state.tiers or ()
  190. orders = {t.tier_id: (t.tier_order or 0) for t in tiers}
  191. cur_id = state.current.tier_id if state.current else None
  192. cur_order = orders[cur_id] if cur_id in orders else next((t.tier_order or 0 for t in tiers if t.is_current), 0)
  193. return orders.get(tier_id, 0) > cur_order
  194. # ── Dev fixtures (env-var driven, no live portal) ────────────────────────────
  195. _DEV_FIXTURE_PORTAL = "https://portal.nousresearch.com/billing"
  196. _DEV_TIER_SPECS = (("free", "Free", 0, "0", "0"), ("plus", "Plus", 1, "20", "1000"),
  197. ("super", "Super", 2, "40", "3000"), ("ultra", "Ultra", 3, "80", "7000"))
  198. _DEV_FIXTURE_ALIASES = {"logged_out": "logged-out", "loggedout": "logged-out", "mid-tier": "mid",
  199. "top-tier": "top", "member": "not-admin"}
  200. def _dev_tiers(current_id: Optional[str]) -> tuple[SubscriptionTier, ...]:
  201. """Sample plan catalog for fixtures (marks ``current_id`` as the active tier)."""
  202. return tuple(
  203. SubscriptionTier(
  204. tier_id=tid, name=name, tier_order=order, dollars_per_month=parse_money(dpm),
  205. monthly_credits=parse_money(mc), is_current=(tid == current_id), is_enabled=True,
  206. )
  207. for tid, name, order, dpm, mc in _DEV_TIER_SPECS
  208. )
  209. def _dev_plan(tier_id: str, remaining: str, **over: Any) -> dict[str, Any]:
  210. """``current`` + ``tiers`` fixture fields for being on ``tier_id`` with ``remaining`` credits left."""
  211. tid, name, _order, _dpm, mc = next(spec for spec in _DEV_TIER_SPECS if spec[0] == tier_id)
  212. current = CurrentSubscription(
  213. tier_id=tid, tier_name=name, monthly_credits=Decimal(mc), credits_remaining=Decimal(remaining),
  214. cycle_ends_at="2026-07-01", **over,
  215. )
  216. return dict(current=current, tiers=_dev_tiers(tid))
  217. def dev_fixture_subscription_state() -> Optional[SubscriptionState]:
  218. """``HERMES_DEV_SUBSCRIPTION_FIXTURE`` (``free | mid | top | not-admin | downgrade | cancel | team |
  219. logged-out``) -> fixture state; None when unset; unknown name → logged-out with ``error`` set."""
  220. name = (os.getenv("HERMES_DEV_SUBSCRIPTION_FIXTURE") or "").strip().lower()
  221. if not name:
  222. return None
  223. name = _DEV_FIXTURE_ALIASES.get(name, name)
  224. if name == "logged-out":
  225. return SubscriptionState(logged_in=False)
  226. common = dict(logged_in=True, org_name="Acme Inc", org_id="org_acme", role="OWNER", portal_url=_DEV_FIXTURE_PORTAL)
  227. states: dict[str, dict[str, Any]] = {
  228. "free": dict(current=None, tiers=_dev_tiers(None)),
  229. "mid": _dev_plan("plus", "420"),
  230. "top": _dev_plan("ultra", "5000"),
  231. "not-admin": {**_dev_plan("plus", "420"), "role": "MEMBER"},
  232. "downgrade": _dev_plan("super", "1500", pending_downgrade_tier_name="Plus", pending_downgrade_at="2026-07-15"),
  233. "cancel": _dev_plan("plus", "420", cancel_at_period_end=True, cancellation_effective_at="2026-07-01"),
  234. "team": dict(context="team", current=None, org_name="Acme Engineering", org_id="org_eng"),
  235. }
  236. if name not in states:
  237. return SubscriptionState(logged_in=False, error=f"unknown HERMES_DEV_SUBSCRIPTION_FIXTURE: {name}")
  238. return SubscriptionState(**{**common, **states[name]})