clipwright/tests/test_billing_states.py
juancarlos.cavero 5b5d3d2306 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.
2026-07-25 15:14:15 +02:00

82 lines
3.4 KiB
Python

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