fix(billing): stop stranding customers whose payment failed

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.
This commit is contained in:
juancarlos.cavero 2026-07-25 15:14:15 +02:00
parent c88239921e
commit 5b5d3d2306
10 changed files with 215 additions and 34 deletions

View file

@ -18,7 +18,7 @@ from pydantic import BaseModel, EmailStr
from sqlalchemy import select, func, and_ from sqlalchemy import select, func, and_
from .config import settings from .config import settings
from . import database, metering, email_policy from . import config, database, metering, email_policy
from .models import User, MagicLinkToken, UploadPostProfile from .models import User, MagicLinkToken, UploadPostProfile
router = APIRouter() router = APIRouter()
@ -205,14 +205,26 @@ async def get_me(request: Request):
async with database.session() as session: async with database.session() as session:
bal = await metering._balance(session, user.id) bal = await metering._balance(session, user.id)
sub = bal["_sub"] 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 { return {
"user": {"id": str(user.id), "email": user.email}, "user": {"id": str(user.id), "email": user.email},
"entitled": user.entitled, "entitled": user.entitled,
"plan": bal["plan"], "plan": bal["plan"],
"status": sub.status if sub else None, "status": shown.status if shown else None,
"interval": sub.interval if sub else None, "interval": shown.interval if shown else None,
"period_end": bal["period_end"].isoformat() if bal["period_end"] 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": { "minutes": {
"plan_allowance": bal["plan_allowance"], "plan_allowance": bal["plan_allowance"],
"plan_used": bal["plan_used"], "plan_used": bal["plan_used"],

View file

@ -16,7 +16,7 @@ from pydantic import BaseModel
from sqlalchemy import select from sqlalchemy import select
from .config import settings, PLAN_MINUTES, TRIAL_DAYS, SUBSCRIPTION_LOOKUP_KEYS, TOPUP_LOOKUP_KEYS 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 .models import User, Subscription, CreditTopup, StripeEvent
from .auth import get_current_user_required from .auth import get_current_user_required
@ -102,21 +102,24 @@ async def ensure_stripe_customer(user_id, email) -> str:
return cust.id 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: async with database.session() as s:
sub = (await s.execute( sub = (await s.execute(
select(Subscription).where(Subscription.user_id == user_id) select(Subscription).where(Subscription.user_id == user_id)
)).scalar_one_or_none() )).scalar_one_or_none()
# Block a second checkout for ANY non-terminal subscription, not just # Block a second checkout while a subscription is live or actively dunning:
# active/trialing. A first charge that fails leaves the sub in past_due / # past_due / unpaid / paused all have Stripe still retrying a charge, so a
# unpaid / incomplete; those must still block, otherwise the user can spawn a # fresh subscription would double-bill (real case: annual trial -> end-trial
# second subscription while the first one keeps dunning (real case: annual # -> card declined -> past_due, then a fresh monthly sub).
# 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 # Terminal states (canceled, incomplete_expired) do NOT block. Free-plan
# users have no Subscription row at all, so their upgrade checkout passes. # users have no Subscription row at all, so their upgrade checkout passes.
return bool(sub and sub.status in ( return sub.status if (sub and sub.status in config.CHECKOUT_BLOCKING_STATES) else None
"active", "trialing", "past_due", "unpaid", "incomplete", "paused",
))
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
@ -141,8 +144,17 @@ async def create_checkout(body: CheckoutRequest, request: Request):
raise HTTPException(status_code=400, detail="Unknown price") raise HTTPException(status_code=400, detail="Unknown price")
mode = "subscription" if entry["kind"] == "subscription" else "payment" mode = "subscription" if entry["kind"] == "subscription" else "payment"
if mode == "subscription" and await _active_sub_exists(user.id): if mode == "subscription":
raise HTTPException(status_code=409, 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.") detail="You already have an active plan. Manage it from your account.")
customer_id = await ensure_stripe_customer(user.id, user.email) customer_id = await ensure_stripe_customer(user.id, user.email)

View file

@ -47,6 +47,20 @@ FREE_CLIP_RETENTION_DAYS = 7
# cancel (grandfathering). # cancel (grandfathering).
TRIAL_DAYS = 0 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 # Minute cap DURING the trial (across all plans). Kept for grandfathered
# 'trialing' subscriptions; removable once no subscription has status # 'trialing' subscriptions; removable once no subscription has status
# 'trialing'. # 'trialing'.

View file

@ -111,13 +111,28 @@ def probe_url_minutes(url: str) -> float:
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# Balance computation (assumes caller holds the user lock when mutating) # Balance computation (assumes caller holds the user lock when mutating)
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
async def _active_subscription(session, user_id): async def _subscription_row(session, user_id):
row = (await session.execute( """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) select(Subscription).where(Subscription.user_id == user_id)
)).scalar_one_or_none() )).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: 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 ``user`` may be a pre-fetched ``User`` row to save a lookup; it is only
consulted on the subscription-less path (free-plan eligibility). 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: if sub:
plan_name = sub.plan plan_name = sub.plan
plan_allowance = _D(sub.minutes_per_period) 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), "remaining": float(plan_remaining + topup_remaining),
"period_end": period_end, "period_end": period_end,
"_sub": sub, "_sub": sub,
"_sub_row": sub_row,
"_plan_remaining_d": plan_remaining, "_plan_remaining_d": plan_remaining,
"_topups": topups, "_topups": topups,
} }

View file

@ -6,6 +6,10 @@ import { track } from '../lib/analytics';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10; 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. // Account/billing page: plan, usage meter, top-ups, manage billing, logout.
export default function AccountPage() { export default function AccountPage() {
const { me, refreshMe, logout, plan, minutes } = useAuth(); const { me, refreshMe, logout, plan, minutes } = useAuth();
@ -84,7 +88,7 @@ export default function AccountPage() {
body: JSON.stringify({ price_id }), body: JSON.stringify({ price_id }),
}); });
window.location.href = url; 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 <div className="flex justify-center py-16"><Loader2 className="animate-spin text-brass" /></div>; if (!me) return <div className="flex justify-center py-16"><Loader2 className="animate-spin text-brass" /></div>;
@ -117,24 +121,46 @@ export default function AccountPage() {
<div className="flex items-center justify-between gap-4 mb-4"> <div className="flex items-center justify-between gap-4 mb-4">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="text-ink font-medium capitalize">{plan ? `${plan} plan` : 'No active plan'}</span> <span className="text-ink font-medium capitalize">{plan ? `${plan} plan` : 'No active plan'}</span>
{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) && (
<span className="badge-warn">{me.status}</span> <span className="badge-warn">{me.status}</span>
)} )}
{me.cancel_at_period_end && ( {me.cancel_at_period_end && (
<span className="badge-warn">cancels at period end</span> <span className="badge-warn">cancels at period end</span>
)} )}
</div> </div>
{plan === 'free' ? ( {/* Any Stripe relationship — live OR broken (past_due, unpaid) — must
<button onClick={() => { window.location.hash = '#/pricing'; }} className="btn-primary px-4 py-2 shrink-0 text-xs"> keep the portal reachable. A declined card demotes `plan` to free,
Upgrade so keying this off the plan alone hid the one button that fixes it. */}
</button> {me.has_billing_account ? (
) : (
<button onClick={openPortal} disabled={busy} className="btn-ghost px-4 py-2 shrink-0"> <button onClick={openPortal} disabled={busy} className="btn-ghost px-4 py-2 shrink-0">
<CreditCard size={16} /> Manage billing <CreditCard size={16} /> Manage billing
</button> </button>
) : (
<button onClick={() => { window.location.hash = '#/pricing'; }} className="btn-primary px-4 py-2 shrink-0 text-xs">
Upgrade
</button>
)} )}
</div> </div>
{/* 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) && (
<div className="mb-4 rounded-card border border-warn/40 bg-warn/5 p-3 text-sm text-ink2">
<b className="text-ink">We couldn't charge your card.</b>{' '}
{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.'}{' '}
<button onClick={openPortal} disabled={busy}
className="underline underline-offset-2 hover:text-ink">
Update your card
</button>{' '}
and it resumes right away.
</div>
)}
<div className="space-y-2"> <div className="space-y-2">
<div className="flex justify-between text-sm"> <div className="flex justify-between text-sm">
<span className="text-muted lowercase">Plan minutes</span> <span className="text-muted lowercase">Plan minutes</span>

View file

@ -32,7 +32,7 @@ export default function PlanChoiceModal({ onClose }) {
body: JSON.stringify({ price_id }), body: JSON.stringify({ price_id }),
}); });
window.location.href = url; 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 = () => { const startFree = () => {

View file

@ -52,7 +52,7 @@ export default function PricingSection({ onRequireLogin }) {
window.location.href = url; window.location.href = url;
} catch (e) { } catch (e) {
setBusyPrice(null); setBusyPrice(null);
alert('Could not start checkout. Please try again.'); alert(e?.detail || 'Could not start checkout. Please try again.');
} }
}; };

View file

@ -58,7 +58,7 @@ export default function TopUpModal({ onClose, required, remaining, context = 'wa
body: JSON.stringify({ price_id: entry.price_id }), body: JSON.stringify({ price_id: entry.price_id }),
}); });
window.location.href = url; 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', { const fmt = (a, c) => new Intl.NumberFormat('en-US', {

View file

@ -37,12 +37,30 @@ export async function apiFetch(path, options = {}) {
return res; 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. // Convenience JSON helper.
export async function apiJson(path, options = {}) { export async function apiJson(path, options = {}) {
const res = await apiFetch(path, options); const res = await apiFetch(path, options);
if (!res.ok) { if (!res.ok) {
const text = await res.text().catch(() => ''); 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(); return res.json();
} }

View file

@ -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