From 5b5d3d23066e22e058c176e20168e4de74f58bce Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Sat, 25 Jul 2026 15:14:15 +0200 Subject: [PATCH] fix(billing): stop stranding customers whose payment failed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A declined card left the account in a state with no way out. `past_due` grants no minutes, so the metering layer resolved the user to the free plan — which meant /api/me reported status=null, the account page swapped "Manage billing" for "Upgrade" (hiding the only button that fixes a card), and the checkout guard then rejected the upgrade with a 409 that every call site swallowed into a generic "Could not start checkout." Silently free, unwarned, unable to pay. Found on 25-jul-2026 in prod: 14 subscriptions in this state, all first charges that failed when the (now retired) 3-day trial ended. The trial is gone, but the trap is not — a renewal failure or an abandoned 3DS payment reproduces it. - metering: split `_subscription_row` (raw) from `_active_subscription` (entitling), and expose both on the balance. Entitlement logic is unchanged. - /api/me: report status/interval from a row needing attention when no subscription entitles, plus `has_billing_account` to route the portal button. - checkout: drop `incomplete` from the blocking states. Stripe collects nothing on it and expires it within 24h, so blocking only stopped the user's retry. Give past_due/unpaid a message that names the problem and the fix. - account page: explain the failed payment inline with a link to the portal instead of showing a bare "past_due" chip, and keep the portal reachable for any Stripe relationship, live or broken. - api client: throw a typed ApiError carrying the server's detail so callers stop replacing real, actionable messages with generic copy. Verified against a real DB: past_due stays blocked but visible and fixable, incomplete can retry, canceled is silent and can subscribe again. --- cloud/auth.py | 20 ++++- cloud/billing.py | 38 +++++---- cloud/config.py | 14 ++++ cloud/metering.py | 29 +++++-- dashboard/src/components/AccountPage.jsx | 40 ++++++++-- dashboard/src/components/PlanChoiceModal.jsx | 2 +- dashboard/src/components/PricingSection.jsx | 2 +- dashboard/src/components/TopUpModal.jsx | 2 +- dashboard/src/lib/api.js | 20 ++++- tests/test_billing_states.py | 82 ++++++++++++++++++++ 10 files changed, 215 insertions(+), 34 deletions(-) create mode 100644 tests/test_billing_states.py diff --git a/cloud/auth.py b/cloud/auth.py index f0cab14..7c7ab04 100644 --- a/cloud/auth.py +++ b/cloud/auth.py @@ -18,7 +18,7 @@ from pydantic import BaseModel, EmailStr from sqlalchemy import select, func, and_ from .config import settings -from . import database, metering, email_policy +from . import config, database, metering, email_policy from .models import User, MagicLinkToken, UploadPostProfile router = APIRouter() @@ -205,14 +205,26 @@ async def get_me(request: Request): async with database.session() as session: bal = await metering._balance(session, user.id) sub = bal["_sub"] + # Report the entitling subscription when there is one; otherwise fall back to + # a row that needs the customer's attention (card declined, payment never + # finished). Without this a past_due customer sees a plain free account and + # never learns their card failed. `plan` stays as computed — the entitlement + # really is free — so the UI shows "free plan" plus the warning badge. + attention = bal["_sub_row"] + if attention is not None and attention.status not in config.BILLING_ATTENTION_STATES: + attention = None + shown = sub or attention return { "user": {"id": str(user.id), "email": user.email}, "entitled": user.entitled, "plan": bal["plan"], - "status": sub.status if sub else None, - "interval": sub.interval if sub else None, + "status": shown.status if shown else None, + "interval": shown.interval if shown else None, "period_end": bal["period_end"].isoformat() if bal["period_end"] else None, - "cancel_at_period_end": sub.cancel_at_period_end if sub else False, + "cancel_at_period_end": shown.cancel_at_period_end if shown else False, + # Drives the "Manage billing" route in the UI: any Stripe relationship, + # live or broken, must keep the portal reachable. + "has_billing_account": bool(sub or attention), "minutes": { "plan_allowance": bal["plan_allowance"], "plan_used": bal["plan_used"], diff --git a/cloud/billing.py b/cloud/billing.py index ca632b7..1c53e6a 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -16,7 +16,7 @@ from pydantic import BaseModel from sqlalchemy import select from .config import settings, PLAN_MINUTES, TRIAL_DAYS, SUBSCRIPTION_LOOKUP_KEYS, TOPUP_LOOKUP_KEYS -from . import database +from . import config, database from .models import User, Subscription, CreditTopup, StripeEvent from .auth import get_current_user_required @@ -102,21 +102,24 @@ async def ensure_stripe_customer(user_id, email) -> str: return cust.id -async def _active_sub_exists(user_id) -> bool: +async def _blocking_sub_status(user_id): + """Return the status of a subscription that must block a new checkout, else None.""" async with database.session() as s: sub = (await s.execute( select(Subscription).where(Subscription.user_id == user_id) )).scalar_one_or_none() - # Block a second checkout for ANY non-terminal subscription, not just - # active/trialing. A first charge that fails leaves the sub in past_due / - # unpaid / incomplete; those must still block, otherwise the user can spawn a - # second subscription while the first one keeps dunning (real case: annual - # trial -> end-trial -> card declined -> past_due, then a fresh monthly sub). + # Block a second checkout while a subscription is live or actively dunning: + # past_due / unpaid / paused all have Stripe still retrying a charge, so a + # fresh subscription would double-bill (real case: annual trial -> end-trial + # -> card declined -> past_due, then a fresh monthly sub). + # + # 'incomplete' is deliberately NOT here. It means a checkout was started and + # the payment never completed (3DS abandoned, card declined at confirm) — + # nothing is being collected, and Stripe expires the row within 24h. Blocking + # it only stops the retry, exactly when the user is most willing to pay. # Terminal states (canceled, incomplete_expired) do NOT block. Free-plan # users have no Subscription row at all, so their upgrade checkout passes. - return bool(sub and sub.status in ( - "active", "trialing", "past_due", "unpaid", "incomplete", "paused", - )) + return sub.status if (sub and sub.status in config.CHECKOUT_BLOCKING_STATES) else None # --------------------------------------------------------------------------- # @@ -141,9 +144,18 @@ async def create_checkout(body: CheckoutRequest, request: Request): raise HTTPException(status_code=400, detail="Unknown price") mode = "subscription" if entry["kind"] == "subscription" else "payment" - if mode == "subscription" and await _active_sub_exists(user.id): - raise HTTPException(status_code=409, - detail="You already have an active plan. Manage it from your account.") + if mode == "subscription": + blocked = await _blocking_sub_status(user.id) + if blocked in ("past_due", "unpaid"): + # Their card failed. Telling them "you already have a plan" is both + # false (they get no minutes) and a dead end — point at the portal. + raise HTTPException(status_code=409, detail=( + "Your last payment didn't go through, so we can't start a new plan " + "yet. Update your card under Manage billing and it resumes right away.")) + if blocked: + raise HTTPException( + status_code=409, + detail="You already have an active plan. Manage it from your account.") customer_id = await ensure_stripe_customer(user.id, user.email) fe = settings.frontend_url diff --git a/cloud/config.py b/cloud/config.py index 4d87df4..d900d2d 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -47,6 +47,20 @@ FREE_CLIP_RETENTION_DAYS = 7 # cancel (grandfathering). TRIAL_DAYS = 0 +# Subscription states that grant no minutes but still need the customer to act +# (fix a card, finish a payment). They must stay VISIBLE in /api/me and keep the +# billing-portal route reachable — otherwise the account silently reads as free +# and the user has no way out. Terminal states (canceled, incomplete_expired) +# are deliberately absent: nothing to fix, so nothing to nag about. +BILLING_ATTENTION_STATES = ("past_due", "unpaid", "incomplete", "paused") + +# Subscription states that must block a NEW subscription checkout. Narrower than +# BILLING_ATTENTION_STATES on purpose: Stripe is still trying to collect on +# past_due/unpaid/paused, so a second subscription would double-bill. It is NOT +# collecting on 'incomplete' (payment abandoned at 3DS/confirm, expired by Stripe +# within 24h), so blocking that would only stop the retry. +CHECKOUT_BLOCKING_STATES = ("active", "trialing", "past_due", "unpaid", "paused") + # Minute cap DURING the trial (across all plans). Kept for grandfathered # 'trialing' subscriptions; removable once no subscription has status # 'trialing'. diff --git a/cloud/metering.py b/cloud/metering.py index bc87915..01282ee 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -111,13 +111,28 @@ def probe_url_minutes(url: str) -> float: # --------------------------------------------------------------------------- # # Balance computation (assumes caller holds the user lock when mutating) # --------------------------------------------------------------------------- # -async def _active_subscription(session, user_id): - row = (await session.execute( +async def _subscription_row(session, user_id): + """The user's subscription row whatever its status (None if never subscribed). + + Distinct from ``_active_subscription``: a row in a state that grants no + minutes (past_due, incomplete, ...) still has to be visible to the UI, or a + customer whose card failed silently reads as a plain free account with no + way to fix it. Entitlement decisions must use ``_active_subscription``. + """ + return (await session.execute( select(Subscription).where(Subscription.user_id == user_id) )).scalar_one_or_none() - if row and row.status in ("active", "trialing") and row.current_period_end > _now(): - return row - return None + + +def _entitles(row) -> bool: + """True if this subscription row grants plan minutes right now.""" + return bool(row and row.status in ("active", "trialing") + and row.current_period_end > _now()) + + +async def _active_subscription(session, user_id): + row = await _subscription_row(session, user_id) + return row if _entitles(row) else None def free_plan_eligible(user) -> bool: @@ -184,7 +199,8 @@ async def _balance(session, user_id, user=None): ``user`` may be a pre-fetched ``User`` row to save a lookup; it is only consulted on the subscription-less path (free-plan eligibility). """ - sub = await _active_subscription(session, user_id) + sub_row = await _subscription_row(session, user_id) + sub = sub_row if _entitles(sub_row) else None if sub: plan_name = sub.plan plan_allowance = _D(sub.minutes_per_period) @@ -222,6 +238,7 @@ async def _balance(session, user_id, user=None): "remaining": float(plan_remaining + topup_remaining), "period_end": period_end, "_sub": sub, + "_sub_row": sub_row, "_plan_remaining_d": plan_remaining, "_topups": topups, } diff --git a/dashboard/src/components/AccountPage.jsx b/dashboard/src/components/AccountPage.jsx index 4ec9bd9..0611139 100644 --- a/dashboard/src/components/AccountPage.jsx +++ b/dashboard/src/components/AccountPage.jsx @@ -6,6 +6,10 @@ import { track } from '../lib/analytics'; const fmt1 = (n) => Math.round((n || 0) * 10) / 10; +// Mirrors cloud/config.BILLING_ATTENTION_STATES: states where the customer has +// to do something (fix a card, finish a payment) before minutes come back. +const PAYMENT_ISSUE_STATES = ['past_due', 'unpaid', 'incomplete', 'paused']; + // Account/billing page: plan, usage meter, top-ups, manage billing, logout. export default function AccountPage() { const { me, refreshMe, logout, plan, minutes } = useAuth(); @@ -84,7 +88,7 @@ export default function AccountPage() { body: JSON.stringify({ price_id }), }); window.location.href = url; - } catch (e) { setBusy(false); alert('Could not start checkout.'); } + } catch (e) { setBusy(false); alert(e?.detail || 'Could not start checkout.'); } }, []); if (!me) return
; @@ -117,24 +121,46 @@ export default function AccountPage() {
{plan ? `${plan} plan` : 'No active plan'} - {me.status && me.status !== 'active' && ( + {/* Payment-issue states get the explanatory banner below instead — + showing raw Stripe jargon ("past_due") twice explains nothing. */} + {me.status && me.status !== 'active' + && !PAYMENT_ISSUE_STATES.includes(me.status) && ( {me.status} )} {me.cancel_at_period_end && ( cancels at period end )}
- {plan === 'free' ? ( - - ) : ( + {/* Any Stripe relationship — live OR broken (past_due, unpaid) — must + keep the portal reachable. A declined card demotes `plan` to free, + so keying this off the plan alone hid the one button that fixes it. */} + {me.has_billing_account ? ( + ) : ( + )}
+ {/* A bare "past_due" chip explains nothing. Say what happened and what + fixes it — this is the whole reason the account reads as free. */} + {PAYMENT_ISSUE_STATES.includes(me.status) && ( +
+ We couldn't charge your card.{' '} + {me.status === 'incomplete' + ? 'Your payment was never completed, so the plan never started.' + : 'Your plan is paused and you\'re on free minutes until it goes through.'}{' '} + {' '} + and it resumes right away. +
+ )} +
Plan minutes diff --git a/dashboard/src/components/PlanChoiceModal.jsx b/dashboard/src/components/PlanChoiceModal.jsx index 0810104..3669610 100644 --- a/dashboard/src/components/PlanChoiceModal.jsx +++ b/dashboard/src/components/PlanChoiceModal.jsx @@ -32,7 +32,7 @@ export default function PlanChoiceModal({ onClose }) { body: JSON.stringify({ price_id }), }); window.location.href = url; - } catch (e) { setBusy(null); alert('Could not start checkout. Please try again.'); } + } catch (e) { setBusy(null); alert(e?.detail || 'Could not start checkout. Please try again.'); } }; const startFree = () => { diff --git a/dashboard/src/components/PricingSection.jsx b/dashboard/src/components/PricingSection.jsx index d5b3214..b120549 100644 --- a/dashboard/src/components/PricingSection.jsx +++ b/dashboard/src/components/PricingSection.jsx @@ -52,7 +52,7 @@ export default function PricingSection({ onRequireLogin }) { window.location.href = url; } catch (e) { setBusyPrice(null); - alert('Could not start checkout. Please try again.'); + alert(e?.detail || 'Could not start checkout. Please try again.'); } }; diff --git a/dashboard/src/components/TopUpModal.jsx b/dashboard/src/components/TopUpModal.jsx index 8269598..471dc07 100644 --- a/dashboard/src/components/TopUpModal.jsx +++ b/dashboard/src/components/TopUpModal.jsx @@ -58,7 +58,7 @@ export default function TopUpModal({ onClose, required, remaining, context = 'wa body: JSON.stringify({ price_id: entry.price_id }), }); window.location.href = url; - } catch (e) { setBusyPrice(null); alert('Could not start checkout.'); } + } catch (e) { setBusyPrice(null); alert(e?.detail || 'Could not start checkout.'); } }; const fmt = (a, c) => new Intl.NumberFormat('en-US', { diff --git a/dashboard/src/lib/api.js b/dashboard/src/lib/api.js index 0819d45..5a9a59a 100644 --- a/dashboard/src/lib/api.js +++ b/dashboard/src/lib/api.js @@ -37,12 +37,30 @@ export async function apiFetch(path, options = {}) { return res; } +// A failed request, carrying the server's own explanation. Callers that show an +// alert should prefer `detail` — the generic "something went wrong" strings hid +// real, actionable messages (e.g. a declined card blocking checkout). +export class ApiError extends Error { + constructor(status, detail, raw) { + super(`${status}: ${raw}`); // message kept verbatim for existing callers + this.name = 'ApiError'; + this.status = status; + this.detail = detail; + } +} + // Convenience JSON helper. export async function apiJson(path, options = {}) { const res = await apiFetch(path, options); if (!res.ok) { const text = await res.text().catch(() => ''); - throw new Error(`${res.status}: ${text}`); + let detail = ''; + try { + const d = JSON.parse(text).detail; + // FastAPI details are strings here, but validation errors arrive as objects. + if (typeof d === 'string') detail = d; + } catch (_) { /* not JSON — leave detail empty and fall back to the caller's copy */ } + throw new ApiError(res.status, detail, text); } return res.json(); } diff --git a/tests/test_billing_states.py b/tests/test_billing_states.py new file mode 100644 index 0000000..100ddc6 --- /dev/null +++ b/tests/test_billing_states.py @@ -0,0 +1,82 @@ +"""Subscription-state gates: who is entitled, who is blocked from checkout, and +who must still be able to reach the billing portal. + +Regression cover for the past_due dead end found in prod on 25-jul-2026: a +customer whose card was declined read as a plain free account (no warning, no +portal button) AND was blocked from starting a new checkout — no way out. +""" +from datetime import datetime, timezone, timedelta +from types import SimpleNamespace + +import pytest + +from cloud import config, metering + + +def _sub(status="active", period_end=None): + return SimpleNamespace( + status=status, + current_period_end=period_end or (datetime.now(timezone.utc) + timedelta(days=20)), + ) + + +class TestEntitles: + """Only a live subscription inside its period grants plan minutes.""" + + @pytest.mark.parametrize("status", ["active", "trialing"]) + def test_live_states_entitle(self, status): + assert metering._entitles(_sub(status)) is True + + @pytest.mark.parametrize("status", [ + "past_due", "unpaid", "incomplete", "paused", "canceled", "incomplete_expired", + ]) + def test_everything_else_does_not_entitle(self, status): + assert metering._entitles(_sub(status)) is False + + def test_expired_period_does_not_entitle(self): + past = datetime.now(timezone.utc) - timedelta(days=1) + assert metering._entitles(_sub("active", period_end=past)) is False + + def test_no_subscription_does_not_entitle(self): + assert metering._entitles(None) is False + + +class TestCheckoutBlockingStates: + """Block only while Stripe is actually trying to collect.""" + + @pytest.mark.parametrize("status", ["active", "trialing", "past_due", "unpaid", "paused"]) + def test_dunning_or_live_blocks_a_second_subscription(self, status): + assert status in config.CHECKOUT_BLOCKING_STATES + + def test_incomplete_does_not_block_the_retry(self): + # Payment abandoned at 3DS/confirm. Nothing is being collected and Stripe + # expires the row within 24h, so blocking only stops the user paying. + assert "incomplete" not in config.CHECKOUT_BLOCKING_STATES + + @pytest.mark.parametrize("status", ["canceled", "incomplete_expired"]) + def test_terminal_states_do_not_block(self, status): + assert status not in config.CHECKOUT_BLOCKING_STATES + + +class TestAttentionStates: + """States the account page must surface so the customer can act.""" + + @pytest.mark.parametrize("status", ["past_due", "unpaid", "incomplete", "paused"]) + def test_broken_payment_is_visible(self, status): + assert status in config.BILLING_ATTENTION_STATES + + @pytest.mark.parametrize("status", ["canceled", "incomplete_expired"]) + def test_terminal_states_are_not_nagged_about(self, status): + assert status not in config.BILLING_ATTENTION_STATES + + def test_none_of_them_entitle_minutes(self): + # The whole point: these look like "free" to the metering layer, which is + # why they have to be reported separately or they vanish from the UI. + for status in config.BILLING_ATTENTION_STATES: + assert metering._entitles(_sub(status)) is False + + def test_every_blocking_state_is_either_live_or_flagged(self): + # A state that blocks checkout but is invisible in /api/me would recreate + # the dead end, so the two sets must stay reconciled. + for status in config.CHECKOUT_BLOCKING_STATES: + assert status in ("active", "trialing") or status in config.BILLING_ATTENTION_STATES