Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(platform): plans bought during a canceled trial change the trial's own subscription (#15382)

Nicholas Tindle170e5ce18798
diff --git a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py
index a5ac0b1a15..1ba2bb1e1b 100644
--- a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py
+++ b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py
@@ -48,6 +48,7 @@ from backend.data.credit import (
)
from backend.data.notifications import PassWorkEvent, PassWorkKind
from backend.data.redis_client import get_redis_async
+from backend.data.stripe_authentication import requires_authentication
from backend.data.stripe_client import stripe_call
from backend.data.subscription_checkout import AnotherPlanLive
from backend.data.subscription_trial import TrialState
@@ -74,19 +75,6 @@ from backend.util.settings import Settings
logger = logging.getLogger(__name__)
settings = Settings()
-# The card is fine but the bank wants 3DS. Stripe documents
-# ``authentication_required`` (also a ``card_declined`` decline code) and
-# ``invoice_payment_intent_requires_action`` for an invoice payment that needs
-# action; ``subscription_payment_intent_requires_action`` is kept because it has
-# been reported for Subscription.modify under ``error_if_incomplete``.
-_SCA_CARD_ERROR_CODES = frozenset(
- {
- "authentication_required",
- "invoice_payment_intent_requires_action",
- "subscription_payment_intent_requires_action",
- }
-)
-
# No router-level auth: /credits/stripe_webhook is authenticated by Stripe's
# signature, not by a user, so each route keeps its own dependency.
router = APIRouter()
@@ -167,8 +155,10 @@ class SubscriptionStatusResponse(BaseModel):
default="",
description=(
"Populated only when POST /credits/subscription starts a Stripe Checkout"
- " Session (BASIC → paid upgrade). Empty string in all other branches —"
- " the client redirects to this URL when non-empty."
+ " Session (BASIC → paid upgrade), or when a trial ending early needs"
+ " the customer's bank to confirm its payment, on Stripe's invoice page."
+ " Empty string in all other branches — the client sends the customer"
+ " to this URL when non-empty."
),
)
@@ -509,19 +499,17 @@ async def update_subscription_tier(
# Modify in place if there's a sub; else fall through to Checkout below.
try:
- modified = await _change_plan_in_place(
- user_id, tier, request.billing_cycle, pending_trial
- )
- if modified:
- status = await get_subscription_status(user_id)
- if converts_trial and status.tier != tier.value:
- # Stripe charged the card but the reconcile did not see a
- # conversion; the person needs the paid plan they bought.
- logger.error(
- f"Trial conversion for user {user_id} left tier"
- f" {status.tier}, not {tier.value}"
- )
- return status
+ if pending_trial is not None:
+ return await _convert_trial(
+ user_id,
+ pending_trial,
+ tier,
+ None if converts_trial else target_price_id,
+ )
+ if await modify_stripe_subscription_for_tier(
+ user_id, tier, request.billing_cycle
+ ):
+ return await get_subscription_status(user_id)
except TrialConversionRefused as e:
raise HTTPException(status_code=409, detail=str(e))
except ValueError as e:
@@ -531,7 +519,7 @@ async def update_subscription_tier(
# modify was rolled back, so 402 lets the UI prompt for a new card or
# surface SCA. SCA codes mean the card is fine but the bank wants 3DS —
# different message so the user doesn't try a new card.
- if _requires_authentication(e):
+ if requires_authentication(e):
logger.warning(
"SCA required on subscription upgrade for user %s: %s", user_id, e
)
@@ -700,44 +688,30 @@ async def update_subscription_tier(
return status
-async def _change_plan_in_place(
+async def _convert_trial(
user_id: str,
+ trial: TrialState,
tier: SubscriptionTier,
- billing_cycle: Literal["monthly", "yearly"],
- pending_trial: TrialState | None,
-) -> bool:
- """Change the plan without Checkout; False means Checkout is needed.
-
- A cancel-pending trial choosing the plan it accepted converts in place.
- Any other plan is a new subscription through Checkout, and the
- stale-subscription cleanup ends the trial once that plan is active.
+ price_id: str | None,
+) -> SubscriptionStatusResponse:
+ """Start the chosen plan on the cancel-pending trial's own subscription.
+
+ Stripe limits a customer to one subscription, so Checkout would refuse a
+ plan beside the trial. A bank that wants to confirm the payment gets
+ Stripe's invoice page as ``url``; nothing changes until it is paid.
"""
- if pending_trial is None:
- return await modify_stripe_subscription_for_tier(user_id, tier, billing_cycle)
- if not is_trial_plan(pending_trial, tier, billing_cycle):
- return False
- try:
- converted = await convert_cancel_pending_trial(pending_trial)
- except stripe.CardError as e:
- if not _requires_authentication(e):
- raise
- # Only an on-session Checkout can complete 3DS. The failed charge left
- # the trial untouched, and the stale-subscription cleanup ends it once
- # the Checkout plan is active.
- logger.warning(
- f"SCA required on trial conversion for user {user_id}; using Checkout: {e}"
+ payment_page = await convert_cancel_pending_trial(trial, tier, price_id)
+ status = await get_subscription_status(user_id)
+ if payment_page:
+ status.url = payment_page
+ elif status.tier != tier.value:
+ # Stripe charged the card but the reconcile did not see a
+ # conversion; the person needs the paid plan they bought.
+ logger.error(
+ f"Trial conversion for user {user_id} left tier {status.tier},"
+ f" not {tier.value}"
)
- return False
- if not converted:
- logger.info(f"Trial conversion for user {user_id} needs a card; using Checkout")
- return converted
-
-
-def _requires_authentication(error: stripe.CardError) -> bool:
- decline_code = error.error.decline_code if error.error else None
- return (
- error.code in _SCA_CARD_ERROR_CODES or decline_code == "authentication_required"
- )
+ return status
def _stripe_event_dedup_key(event_id: str) -> str:
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_trial_guards_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_trial_guards_test.py
index 5e281dfa9a..86187ece29 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_routes_trial_guards_test.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_trial_guards_test.py
@@ -1,8 +1,8 @@
-"""Choosing a plan while a trial is cancel-pending converts it in place only
-while Stripe still shows that trial alone and cancel-pending, and only for the
-same plan: otherwise the request is refused or goes to a new checkout."""
+"""Choosing a plan while a trial is cancel-pending converts the trial's own
+subscription, whatever the plan, and only while Stripe still shows that trial
+alone and cancel-pending. Stripe limits a customer to one subscription, so no
+plan is ever bought through Checkout beside the trial."""
-from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, MagicMock
import fastapi.testclient
@@ -22,8 +22,7 @@ from backend.api.features.subscription_routes_trial_test import (
_post_plan,
_subscription_list,
)
-from backend.data import credit, subscription_checkout
-from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_conversion import PENDING_UPDATE_API_VERSION
pytest_plugins = ("backend.data.subscription_trial_fixtures",)
@@ -37,7 +36,11 @@ cancel_pending_trial = trial_test.cancel_pending_trial
trial_conversion = trial_test.trial_conversion
ANOTHER_PLAN_LIVE_DETAIL = "Another plan is already active. Manage it in billing."
-CHECKOUT_URL = "https://checkout.stripe.com/pay/cs_test_max"
+CARD_NEEDED_DETAIL = (
+ "Your saved card can't be charged. Update it under Payment method,"
+ " then try again."
+)
+INVOICE_URL = "https://invoice.stripe.com/i/acct_1/test_pay"
def test_update_subscription_tier_cancel_pending_trial_card_declined_returns_402(
@@ -66,30 +69,51 @@ def test_update_subscription_tier_cancel_pending_trial_card_declined_returns_402
("card_declined", "authentication_required"),
],
)
-def test_update_subscription_tier_cancel_pending_trial_sca_falls_back_to_checkout(
+def test_update_subscription_tier_cancel_pending_trial_sca_waits_on_stripes_invoice_page(
client: fastapi.testclient.TestClient,
trial_conversion: MagicMock,
code: str,
decline_code: str | None,
) -> None:
- """Only an on-session Checkout can complete 3DS. The failed charge left the
- trial untouched, and the stale-plan cleanup ends it once the plan is paid."""
- trial_conversion.modify.side_effect = stripe.CardError(
- "Authentication required.",
- param="card",
- code=code,
- json_body={"error": {"code": code, "decline_code": decline_code}},
+ """Checkout would refuse a second subscription, so the same change is held
+ as a pending update: nothing changes until the customer pays its invoice,
+ on the page returned as ``url``."""
+ held = stripe.Subscription.construct_from(
+ {
+ **trial_conversion.live,
+ "pending_update": {"trial_end": 1, "expires_at": 2},
+ "latest_invoice": {
+ "id": "in_held",
+ "status": "open",
+ "created": 1,
+ "hosted_invoice_url": INVOICE_URL,
+ },
+ },
+ "test-key",
)
+ trial_conversion.modify.side_effect = [
+ stripe.CardError(
+ "Authentication required.",
+ param="card",
+ code=code,
+ json_body={"error": {"code": code, "decline_code": decline_code}},
+ ),
+ held,
+ ]
response = _post_plan(client, "PRO")
assert response.status_code == 200
- assert response.json()["url"] == CHECKOUT_URL
+ assert response.json()["url"] == INVOICE_URL
+ assert trial_conversion.modify.await_args_list[-1].kwargs == {
+ "cancel_at_period_end": False,
+ "trial_end": "now",
+ "payment_behavior": "pending_if_incomplete",
+ "expand": ["latest_invoice"],
+ "stripe_version": PENDING_UPDATE_API_VERSION,
+ }
trial_conversion.sync.assert_not_awaited()
- trial_conversion.checkout.assert_awaited_once()
- requested = trial_conversion.checkout.call_args.kwargs
- assert requested["tier"] == SubscriptionTier.PRO
- assert requested["billing_cycle"] == "monthly"
+ trial_conversion.checkout.assert_not_awaited()
@pytest.mark.parametrize(
@@ -124,18 +148,20 @@ def test_update_subscription_tier_cancel_pending_trial_changed_in_stripe_returns
trial_conversion.checkout.assert_not_awaited()
[email protected]("tier", ["PRO", "MAX"])
def test_update_subscription_tier_cancel_pending_trial_with_another_live_plan_returns_409(
client: fastapi.testclient.TestClient,
trial_conversion: MagicMock,
+ tier: str,
) -> None:
- """A Max Checkout completed before its webhook ended the trial: converting
- the trial as well would bill the customer for two plans."""
+ """A plan bought before this change, whose webhook has not ended the trial
+ yet: converting the trial as well would bill the customer for two plans."""
trial_conversion.others.side_effect = None
trial_conversion.others.return_value = _subscription_list(
trial_conversion.live, {"id": "sub_max", "status": "active"}
)
- response = _post_plan(client, "PRO")
+ response = _post_plan(client, tier)
assert response.status_code == 409
assert response.json()["detail"] == ANOTHER_PLAN_LIVE_DETAIL
@@ -177,34 +203,45 @@ def test_update_subscription_tier_cancel_pending_trial_repriced_plan_converts_in
trial_conversion.checkout.assert_not_awaited()
[email protected]("tier,billing_cycle", [("MAX", "monthly"), ("PRO", "yearly")])
-def test_update_subscription_tier_cancel_pending_trial_other_plan_uses_checkout(
+ "tier,billing_cycle,price",
+ [("MAX", "monthly", "price_max"), ("PRO", "yearly", "price_pro_yearly")],
+)
+def test_update_subscription_tier_cancel_pending_trial_other_plan_converts_its_subscription(
client: fastapi.testclient.TestClient,
trial_conversion: MagicMock,
tier: str,
billing_cycle: str,
+ price: str,
) -> None:
- """Another tier or another cycle is a new subscription; the
- stale-subscription cleanup ends the trial once it is paid for."""
+ """Another tier or cycle moves the trial's own subscription onto that
+ plan's price, with the plan recorded for the reconcile to grant."""
response = _post_plan(client, tier, billing_cycle)
assert response.status_code == 200
- assert response.json()["url"] == CHECKOUT_URL
- assert trial_conversion.calls == []
- trial_conversion.modify.assert_not_awaited()
+ assert response.json()["url"] == ""
+ trial_conversion.modify.assert_awaited_once_with(
+ "sub_1",
+ cancel_at_period_end=False,
+ trial_end="now",
+ items=[{"id": "si_1", "price": price}],
+ metadata={
+ "trial_conversion_price_id": price,
+ "trial_conversion_tier": tier,
+ },
+ payment_behavior="error_if_incomplete",
+ )
+ trial_conversion.sync.assert_awaited_once_with(dict(trial_conversion.converted))
trial_conversion.modify_for_tier.assert_not_awaited()
- trial_conversion.checkout.assert_awaited_once()
- assert trial_conversion.checkout.call_args.kwargs["tier"] == SubscriptionTier(tier)
- assert trial_conversion.checkout.call_args.kwargs["billing_cycle"] == billing_cycle
+ trial_conversion.checkout.assert_not_awaited()
[email protected]("tier,converts", [("PRO", True), ("MAX", False)])
[email protected]("tier", ["PRO", "MAX"])
def test_update_subscription_tier_cancel_pending_trial_without_access_can_buy_a_plan(
client: fastapi.testclient.TestClient,
mocker: pytest_mock.MockFixture,
trial_conversion: MagicMock,
tier: str,
- converts: bool,
) -> None:
"""A cancel-pending trial whose card stopped verifying is on NO_TIER. It
still takes the trial path; the trial subscription would otherwise make
@@ -218,24 +255,25 @@ def test_update_subscription_tier_cancel_pending_trial_without_access_can_buy_a_
response = _post_plan(client, tier)
assert response.status_code == 200
- assert trial_conversion.modify.await_count == int(converts)
- assert trial_conversion.checkout.await_count == int(not converts)
+ trial_conversion.modify.assert_awaited_once()
trial_conversion.modify_for_tier.assert_not_awaited()
+ trial_conversion.checkout.assert_not_awaited()
-def test_update_subscription_tier_cancel_pending_trial_card_it_cannot_charge_uses_checkout(
+def test_update_subscription_tier_cancel_pending_trial_card_it_cannot_charge_returns_409(
client: fastapi.testclient.TestClient,
trial_conversion: MagicMock,
) -> None:
- """Only Checkout can take a new card; the trial is left as it was."""
+ """The customer fixes the card in the billing portal and tries again;
+ the trial is left as it was."""
trial_conversion.card.return_value = False
- response = _post_plan(client, "PRO")
+ response = _post_plan(client, "MAX")
- assert response.status_code == 200
- assert response.json()["url"] == CHECKOUT_URL
+ assert response.status_code == 409
+ assert response.json()["detail"] == CARD_NEEDED_DETAIL
trial_conversion.modify.assert_not_awaited()
- trial_conversion.checkout.assert_awaited_once()
+ trial_conversion.checkout.assert_not_awaited()
def test_update_subscription_tier_cancel_pending_trial_converts_without_a_current_price(
@@ -255,50 +293,3 @@ def test_update_subscription_tier_cancel_pending_trial_converts_without_a_curren
assert response.status_code == 200
trial_conversion.modify.assert_awaited_once()
-
-
-@asynccontextmanager
-async def _unlocked(user_id: str):
- yield
-
-
-def test_update_subscription_tier_cancel_pending_trial_checkout_with_live_plan_returns_409(
- client: fastapi.testclient.TestClient,
- mocker: pytest_mock.MockFixture,
- trial_conversion: MagicMock,
- cancel_pending_trial: TrialState,
-) -> None:
- """Max was paid for, but its webhook has not ended the trial yet: another
- Checkout would bill for a second plan."""
- trial_conversion.others.side_effect = None
- trial_conversion.others.return_value = _subscription_list(
- {"id": "sub_max", "status": "active", "metadata": {}}, trial_conversion.live
- )
- mocker.patch(
- "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",
- credit.create_subscription_checkout,
- )
- mocker.patch.object(credit, "subscription_checkout_lock", _unlocked)
- mocker.patch.object(
- credit, "get_subscription_price_id", AsyncMock(return_value="price_max")
- )
- mocker.patch.object(
- credit, "get_stripe_customer_id", AsyncMock(return_value="cus_1")
- )
- mocker.patch.object(credit, "_expire_open_subscription_sessions", AsyncMock())
- mocker.patch.object(
- subscription_checkout,
- "get_subscription_trial",
- AsyncMock(return_value=cancel_pending_trial),
- )
- create = mocker.patch.object(stripe.checkout.Session, "create_async", AsyncMock())
-
- response = _post_plan(client, "MAX")
-
- assert response.status_code == 409
- assert response.json()["detail"] == ANOTHER_PLAN_LIVE_DETAIL
- trial_conversion.others.assert_awaited_once_with(
- customer="cus_1", status="all", limit=100
- )
- create.assert_not_awaited()
- trial_conversion.modify.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_trial_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_trial_test.py
index ae21e1b7d4..61d6234c58 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_routes_trial_test.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_trial_test.py
@@ -76,6 +76,16 @@ def trial_conversion(
"user_id": TEST_USER_ID,
"trial_enrollment_id": cancel_pending_trial.id,
},
+ "items": {
+ "data": [
+ {
+ "id": "si_1",
+ "price": {"id": cancel_pending_trial.offer.price_id},
+ "quantity": 1,
+ }
+ ],
+ "has_more": False,
+ },
}
converted = stripe.Subscription.construct_from(
{**live, "status": "active", "cancel_at_period_end": False}, "test-key"
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 2a7b1812e9..12b4843ac5 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -3199,8 +3199,7 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:
if invoice.get("billing_reason") == "subscription_create":
# A new plan's first payment failed inside Checkout, which lets the
- # customer retry; no plan lapsed. Cancelling here would also end the
- # trial a cancel-pending customer was buying the plan beside.
+ # customer retry; no plan lapsed.
logger.info(
"handle_subscription_payment_failure: first payment of new sub %s"
" failed for user %s; leaving it to Checkout",
@@ -3218,6 +3217,27 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:
)
return
+ if (
+ sub_id
+ and invoice_id
+ # A pending update waits on the invoice its own change made, never on
+ # a renewal, so the common failure skips the Stripe lookup.
+ and invoice.get("billing_reason") != "subscription_cycle"
+ and await _nothing_left_to_cover(invoice_id)
+ ):
+ # Stripe applies a pending update only once its invoice is paid, and
+ # voids the invoice when the update lapses: nothing has changed. A
+ # trial converting early waits like this for the bank to confirm.
+ logger.info(
+ "handle_subscription_payment_failure: invoice %s on sub %s for user"
+ " %s waits on a pending update or is already settled; nothing to"
+ " cover",
+ invoice_id,
+ sub_id,
+ user.id,
+ )
+ return
+
credit_model = UserCredit()
try:
await credit_model._add_transaction(
@@ -3293,6 +3313,21 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:
await set_subscription_tier(user.id, SubscriptionTier.NO_TIER)
+async def _nothing_left_to_cover(invoice_id: str) -> bool:
+ """Whether a pending update still waits on this invoice, or Stripe has
+ settled it since: paid once the bank confirmed, or voided when the update
+ lapsed. The failure event can be delivered after either."""
+ invoice = await stripe_call(
+ stripe.Invoice.retrieve_async, invoice_id, expand=["subscription"]
+ )
+ if invoice.get("status") in ("paid", "void"):
+ return True
+ subscription = invoice.get("subscription") or {}
+ return bool(subscription.get("pending_update")) and (
+ subscription.get("latest_invoice") == invoice_id
+ )
+
+
async def handle_subscription_payment_success(invoice: dict) -> None:
"""Optionally grant AutoGPT credits equal to the paid Stripe invoice amount.
diff --git a/autogpt_platform/backend/backend/data/credit_pending_update_test.py b/autogpt_platform/backend/backend/data/credit_pending_update_test.py
new file mode 100644
index 0000000000..4236765c80
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/credit_pending_update_test.py
@@ -0,0 +1,113 @@
+"""A failed payment on a change Stripe holds until it's paid changed nothing,
+so it must not end the plans a lapsed payment otherwise ends. A trial that
+converts early waits like this for the customer's bank to confirm. The failure
+event can also arrive after the bank confirmed or the hold lapsed."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+import stripe
+from prisma.enums import SubscriptionTier
+from prisma.models import User
+
+from backend.data import credit
+
+
+def _failed_invoice(billing_reason: str) -> dict:
+ return {
+ "id": "in_held",
+ "customer": "cus_1",
+ "subscription": "sub_trial",
+ "amount_due": 32000,
+ "billing_reason": billing_reason,
+ }
+
+
+def lapse():
+ user = MagicMock(spec=User)
+ user.id = "user-1"
+ user.subscriptionTier = SubscriptionTier.TRIAL
+ with (
+ patch(
+ "backend.data.credit.User.prisma",
+ return_value=MagicMock(find_first=AsyncMock(return_value=user)),
+ ),
+ patch.object(
+ credit, "_nothing_left_to_cover", AsyncMock(return_value=True)
+ ) as settled,
+ patch.object(
+ credit.UserCredit, "_add_transaction", new_callable=AsyncMock
+ ) as deduct,
+ patch.object(
+ credit, "_cancel_customer_subscriptions", new_callable=AsyncMock
+ ) as cancel,
+ patch.object(credit, "set_subscription_tier", new_callable=AsyncMock) as tier,
+ patch.object(stripe.Invoice, "pay_async", new_callable=AsyncMock),
+ ):
+ yield MagicMock(settled=settled, deduct=deduct, cancel=cancel, tier=tier)
+
+
+async def test_a_failed_payment_on_a_held_change_cancels_nothing(lapse):
+ await credit.handle_subscription_payment_failure(
+ _failed_invoice("subscription_update")
+ )
+
+ lapse.settled.assert_awaited_once_with("in_held")
+ lapse.deduct.assert_not_awaited()
+ lapse.cancel.assert_not_awaited()
+ lapse.tier.assert_not_awaited()
+
+
+async def test_a_failed_renewal_is_never_looked_up_as_a_held_change(lapse):
+ """A pending update waits on the invoice its own change made, so a renewal
+ goes straight to the balance without a Stripe lookup."""
+ await credit.handle_subscription_payment_failure(
+ _failed_invoice("subscription_cycle")
+ )
+
+ lapse.settled.assert_not_awaited()
+ lapse.deduct.assert_awaited_once()
+
+
+ "status,subscription,nothing_left",
+ [
+ (
+ "open",
+ {"pending_update": {"expires_at": 1}, "latest_invoice": "in_held"},
+ True,
+ ),
+ # A later invoice on the same subscription is not the held one.
+ (
+ "open",
+ {"pending_update": {"expires_at": 1}, "latest_invoice": "in_next"},
+ False,
+ ),
+ ("open", {"pending_update": None, "latest_invoice": "in_held"}, False),
+ # Settled before this event was handled: paid once the bank confirmed,
+ # or voided when the hold lapsed or a later change replaced it.
+ ("paid", {"pending_update": None, "latest_invoice": "in_held"}, True),
+ ("void", {"pending_update": None, "latest_invoice": "in_next"}, True),
+ ],
+)
+async def test_only_a_held_or_settled_invoice_leaves_nothing_to_cover(
+ status, subscription, nothing_left
+):
+ retrieve = AsyncMock(
+ return_value=stripe.Invoice.construct_from(
+ {
+ "id": "in_held",
+ "status": status,
+ "subscription": {"id": "sub_trial", **subscription},
+ },
+ "test-key",
+ )
+ )
+ with patch.object(stripe.Invoice, "retrieve_async", retrieve):
+ assert await credit._nothing_left_to_cover("in_held") is nothing_left
+
+ retrieve.assert_awaited_once_with("in_held", expand=["subscription"])
diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.py
index 1a5386c862..2a14f688d5 100644
--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py
+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py
@@ -60,6 +60,17 @@ def _clear_active_subscription_cache():
yield
[email protected](autouse=True)
+def _no_pending_update():
+ """The payment failures here are plans that lapsed, not a change Stripe
+ holds until it's paid (see credit_pending_update_test.py)."""
+ with patch(
+ "backend.data.credit._nothing_left_to_cover",
+ AsyncMock(return_value=False),
+ ):
+ yield
+
+
# What the shared PostHog client adds to every event (see posthog_client.capture).
BASE_PROPERTIES = {"environment": "test", "source": "platform"}
diff --git a/autogpt_platform/backend/backend/data/stripe_authentication.py b/autogpt_platform/backend/backend/data/stripe_authentication.py
new file mode 100644
index 0000000000..3e9fdc9591
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/stripe_authentication.py
@@ -0,0 +1,23 @@
+"""Whether a refused Stripe charge only needs the customer's bank to confirm it."""
+
+import stripe
+
+# The card is fine but the bank wants 3DS. Stripe documents
+# ``authentication_required`` (also a ``card_declined`` decline code) and
+# ``invoice_payment_intent_requires_action`` for an invoice payment that needs
+# action; ``subscription_payment_intent_requires_action`` is kept because it has
+# been reported for Subscription.modify under ``error_if_incomplete``.
+_SCA_CARD_ERROR_CODES = frozenset(
+ {
+ "authentication_required",
+ "invoice_payment_intent_requires_action",
+ "subscription_payment_intent_requires_action",
+ }
+)
+
+
+def requires_authentication(error: stripe.CardError) -> bool:
+ decline_code = error.error.decline_code if error.error else None
+ return (
+ error.code in _SCA_CARD_ERROR_CODES or decline_code == "authentication_required"
+ )
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_chosen_plan_test.py b/autogpt_platform/backend/backend/data/subscription_trial_chosen_plan_test.py
new file mode 100644
index 0000000000..92df7b2aef
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/subscription_trial_chosen_plan_test.py
@@ -0,0 +1,110 @@
+"""A trial ended early on a plan the customer chose in place of the accepted
+one: the reconcile grants that plan once it is paid for, and nothing else."""
+
+from datetime import UTC, datetime
+
+import pytest
+from prisma.enums import SubscriptionTier
+
+from backend.data import subscription_trial_stripe as fulfillment
+
+pytest_plugins = ("backend.data.subscription_trial_fixtures",)
+
+CHOSEN = {
+ "trial_conversion_price_id": "price_max",
+ "trial_conversion_tier": "MAX",
+}
+
+
+def switched(subscription: dict) -> dict:
+ """The trial's subscription after Max was paid for in its place."""
+ end = int(datetime.now(UTC).timestamp()) - 60
+ subscription.update(
+ status="active",
+ trial_end=end,
+ metadata={**subscription["metadata"], **CHOSEN},
+ items={
+ "data": [{"id": "si_1", "price": {"id": "price_max"}, "quantity": 1}],
+ "has_more": False,
+ },
+ latest_invoice={
+ "id": "in_max",
+ "status": "paid",
+ "created": end,
+ "billing_reason": "subscription_update",
+ },
+ )
+ return subscription
+
+
+async def test_a_paid_switch_to_the_chosen_plan_converts_the_trial_onto_it(
+ trial, switched, boundaries
+):
+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+
+ assert result is not None and result[1] == SubscriptionTier.MAX
+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]
+ assert saved["convertedAt"] is not None
+ assert saved["stripeConversionInvoiceId"] == "in_max"
+ granted = boundaries.user.update_many.await_args.kwargs["data"]
+ assert granted == {"subscriptionTier": SubscriptionTier.MAX}
+
+
+ "change",
+ [
+ # Still trialing: the switch has not been paid for.
+ {"status": "trialing"},
+ # Items that no longer carry the chosen price.
+ {
+ "items": {
+ "data": [{"id": "si_1", "price": {"id": "price_other"}, "quantity": 1}],
+ "has_more": False,
+ }
+ },
+ {
+ "items": {
+ "data": [{"id": "si_1", "price": {"id": "price_max"}, "quantity": 2}],
+ "has_more": False,
+ }
+ },
+ ],
+)
+async def test_the_chosen_price_is_granted_only_as_paid_for(
+ trial, switched, boundaries, change
+):
+ switched.update(change)
+
+ with pytest.raises(ValueError, match="accepted"):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+
+ boundaries.user.update_many.assert_not_awaited()
+
+
[email protected]("tier", ["TRIAL", "NO_TIER", "ENTERPRISE", "max", None])
+async def test_a_chosen_plan_names_a_self_serve_tier(trial, switched, boundaries, tier):
+ metadata = {**switched["metadata"], "trial_conversion_tier": tier}
+ switched["metadata"] = {key: value for key, value in metadata.items() if value}
+
+ with pytest.raises(ValueError, match="accepted"):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
+
+ boundaries.user.update_many.assert_not_awaited()
+
+
+async def test_a_switch_that_lost_its_record_of_the_choice_is_refused(
+ trial, switched, boundaries
+):
+ switched["metadata"] = {
+ key: value
+ for key, value in switched["metadata"].items()
+ if key != "trial_conversion_price_id"
+ }
+
+ with pytest.raises(ValueError, match="accepted"):
+ await fulfillment._reconcile_locked(trial, "sub_1", boundaries)
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_conversion.py b/autogpt_platform/backend/backend/data/subscription_trial_conversion.py
index 013405954c..0c13d29255 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_conversion.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_conversion.py
@@ -1,15 +1,21 @@
-"""Start the paid plan a cancel-pending trial was accepted for, today."""
+"""Start a paid plan on a cancel-pending trial's own subscription, today.
+
+Stripe limits a customer to one subscription, so the plan can't be bought
+beside the trial: the trial's subscription is the one that changes.
+"""
import logging
from datetime import UTC, datetime
import stripe
from prisma.enums import SubscriptionTier
+from pydantic import BaseModel
from backend.data.credit import (
invalidate_active_subscription_cache,
sync_subscription_from_stripe,
)
+from backend.data.stripe_authentication import requires_authentication
from backend.data.stripe_client import stripe_call
from backend.data.subscription_checkout import (
ANOTHER_PLAN_LIVE,
@@ -19,7 +25,12 @@ from backend.data.subscription_checkout import (
subscription_checkout_lock,
)
from backend.data.subscription_trial import TrialState, get_subscription_trial
-from backend.data.subscription_trial_payment import subscription_card_can_be_charged
+from backend.data.subscription_trial_payment import (
+ CONVERSION_PRICE_KEY,
+ CONVERSION_TIER_KEY,
+ Invoice,
+ subscription_card_can_be_charged,
+)
logger = logging.getLogger(__name__)
@@ -28,12 +39,27 @@ TRIAL_RUNNING = (
"Your accepted plan starts after your trial. Manage the trial in billing."
)
TRIAL_BUSY = "Your trial is already being updated. Please retry."
+CARD_NEEDED = (
+ "Your saved card can't be charged. Update it under Payment method,"
+ " then try again."
+)
+# A pending update takes metadata from 2026-05-27.dahlia and
+# cancel_at_period_end from 2026-09-30.endive. The SDK's own 2025-02-24.acacia
+# rejects both with pending_if_incomplete.
+PENDING_UPDATE_API_VERSION = "2026-09-30.endive"
class TrialConversionRefused(Exception):
"""The live trial is no longer one this request may convert."""
+class _HeldConversion(BaseModel):
+ """Stripe's answer to a conversion held for the bank to confirm."""
+
+ pending_update: dict[str, object] | None = None
+ latest_invoice: Invoice | None = None
+
+
async def get_cancel_pending_trial(user_id: str) -> TrialState | None:
"""The user's trial when it is running but scheduled to end unconverted."""
trial = await get_subscription_trial(user_id)
@@ -51,45 +77,118 @@ def is_trial_plan(
return tier.value == offer.tier and billing_cycle == offer.billing_cycle
-async def convert_cancel_pending_trial(trial: TrialState) -> bool:
- """End the trial now and bill the first period of its accepted plan.
+async def convert_cancel_pending_trial(
+ trial: TrialState, tier: SubscriptionTier, price_id: str | None = None
+) -> str | None:
+ """End the trial now and bill the first period of a paid plan.
- Returns False, changing nothing, when the saved card can't be charged:
- only Checkout can take a new card. Stripe would otherwise end a card-less
- trial under its missing-payment-method setting instead of billing it.
+ ``price_id`` names a plan other than the accepted one; None bills the
+ accepted price. Returns the Stripe page where the customer confirms the
+ payment with their bank, or None once the plan has started.
- The items stay as accepted: the reconcile refuses an unconverted trial
- whose price changed. ``error_if_incomplete`` leaves the trial
- cancel-pending when the charge fails.
+ ``error_if_incomplete`` leaves the trial cancel-pending when the charge
+ fails. A bank that wants to confirm the charge gets a pending update
+ instead, which changes nothing until it is paid.
"""
try:
async with subscription_checkout_lock(trial.user_id):
- return await _convert_locked(trial)
+ return await _convert_locked(trial, tier, price_id)
except SubscriptionCheckoutUnavailable as exc:
raise TrialConversionRefused(TRIAL_BUSY) from exc
-async def _convert_locked(trial: TrialState) -> bool:
+async def _convert_locked(
+ trial: TrialState, tier: SubscriptionTier, price_id: str | None
+) -> str | None:
subscription = await _live_cancel_pending_subscription(trial)
if subscription is None:
- return True
+ return None
+ # Stripe ends a trial it has no card to charge for under its
+ # missing-payment-method setting instead of billing it.
if not await subscription_card_can_be_charged(subscription.id, datetime.now(UTC)):
- return False
+ raise TrialConversionRefused(CARD_NEEDED)
await expire_other_subscription_checkouts(trial.customer_id)
# A plan bought through Checkout ends the trial only once its webhook
# is handled; converting before then would bill for both plans.
if await other_plan_is_live(trial.customer_id, subscription.id):
raise TrialConversionRefused(ANOTHER_PLAN_LIVE)
- # No proration_behavior: ending a trial has nothing to prorate, and
- # "none" would skip the first invoice entirely under Stripe's flexible
- # billing mode.
- converted = await stripe_call(
- stripe.Subscription.modify_async,
- subscription.id,
- cancel_at_period_end=False,
- trial_end="now",
- payment_behavior="error_if_incomplete",
- )
+ changes = _plan_changes(subscription, tier, price_id)
+ charge: stripe.Subscription.ModifyParams = {
+ **changes,
+ "payment_behavior": "error_if_incomplete",
+ }
+ try:
+ # No proration_behavior: ending a trial has nothing to prorate, and
+ # "none" would skip the first invoice entirely under Stripe's flexible
+ # billing mode.
+ converted = await stripe_call(
+ stripe.Subscription.modify_async, subscription.id, **charge
+ )
+ except stripe.CardError as exc:
+ if not requires_authentication(exc):
+ raise
+ return await _confirm_with_bank(trial, subscription.id, changes)
+ await _save_conversion(trial, converted)
+ return None
+
+
+def _plan_changes(
+ subscription: stripe.Subscription, tier: SubscriptionTier, price_id: str | None
+) -> stripe.Subscription.ModifyParams:
+ changes: stripe.Subscription.ModifyParams = {
+ "cancel_at_period_end": False,
+ "trial_end": "now",
+ }
+ if price_id is None:
+ return changes
+ items = subscription["items"]
+ if items.get("has_more") or len(items.get("data") or []) != 1:
+ raise ValueError("A trial subscription carries exactly one plan")
+ # The reconcile grants a price other than the accepted one only beside the
+ # tier chosen for it here.
+ changes["items"] = [{"id": items["data"][0]["id"], "price": price_id}]
+ changes["metadata"] = {
+ CONVERSION_PRICE_KEY: price_id,
+ CONVERSION_TIER_KEY: tier.value,
+ }
+ return changes
+
+
+async def _confirm_with_bank(
+ trial: TrialState,
+ subscription_id: str,
+ changes: stripe.Subscription.ModifyParams,
+) -> str | None:
+ """Hold the same change for the customer to pay on Stripe's invoice page.
+
+ Stripe applies a pending update only once its invoice is paid, so the trial
+ stays cancel-pending meanwhile; an unpaid one lapses by trial_end at the
+ latest, with its invoice voided. Only this call uses the newer API version,
+ and only its pending update and invoice page are read from the answer.
+ """
+ hold: stripe.Subscription.ModifyParams = {
+ **changes,
+ "payment_behavior": "pending_if_incomplete",
+ "expand": ["latest_invoice"],
+ "stripe_version": PENDING_UPDATE_API_VERSION,
+ }
+ held = await stripe_call(stripe.Subscription.modify_async, subscription_id, **hold)
+ answer = _HeldConversion.model_validate(held)
+ if answer.pending_update is None:
+ # Paid at once: read the plan back in the version the sync parses.
+ converted = await stripe_call(
+ stripe.Subscription.retrieve_async, subscription_id
+ )
+ await _save_conversion(trial, converted)
+ return None
+ page = answer.latest_invoice.hosted_invoice_url if answer.latest_invoice else None
+ if not page:
+ raise ValueError("Stripe returned no page to confirm the payment on")
+ logger.info(f"Trial {trial.id} conversion waits for the bank to confirm it")
+ return page
+
+
+async def _save_conversion(trial: TrialState, converted: stripe.Subscription) -> None:
invalidate_active_subscription_cache(trial.customer_id)
if converted.get("status") != "active":
await sync_subscription_from_stripe(dict(converted))
@@ -102,7 +201,6 @@ async def _convert_locked(trial: TrialState) -> bool:
logger.exception(
f"Trial {trial.id} converted in Stripe but the follow-up sync failed"
)
- return True
def _is_cancel_pending(trial: TrialState) -> bool:
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_conversion_test.py b/autogpt_platform/backend/backend/data/subscription_trial_conversion_test.py
index 97408581c3..c6b9e2e6cc 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_conversion_test.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_conversion_test.py
@@ -1,6 +1,6 @@
from contextlib import asynccontextmanager
from datetime import UTC, datetime, timedelta
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
import stripe
@@ -12,6 +12,8 @@ from backend.data.subscription_trial import TrialState
pytest_plugins = ("backend.data.subscription_trial_fixtures",)
+PRO = SubscriptionTier.PRO
+
@pytest.fixture
def pending_trial(trial: TrialState) -> TrialState:
@@ -101,7 +103,7 @@ def boundaries(live: dict):
async def test_converts_cancel_pending_trial_in_place_under_checkout_lock(
pending_trial, boundaries
):
- assert await conversion.convert_cancel_pending_trial(pending_trial)
+ assert await conversion.convert_cancel_pending_trial(pending_trial, PRO) is None
assert boundaries.calls == [
"lock:user-1",
@@ -147,7 +149,7 @@ async def test_refuses_a_subscription_the_trial_does_not_own(
)
with pytest.raises(conversion.TrialConversionRefused) as refused:
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
assert str(refused.value) == "This trial has ended. Manage the plan in billing."
boundaries.expire.assert_not_awaited()
@@ -173,7 +175,7 @@ async def test_refuses_a_trial_that_is_no_longer_running(
boundaries.retrieve.return_value = ended
with pytest.raises(conversion.TrialConversionRefused, match="has ended"):
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
boundaries.sync.assert_awaited_once_with(dict(ended))
boundaries.expire.assert_not_awaited()
@@ -191,7 +193,7 @@ async def test_a_trial_stripe_already_converted_is_saved_and_succeeds(
boundaries.retrieve.side_effect = None
boundaries.retrieve.return_value = converted
- assert await conversion.convert_cancel_pending_trial(pending_trial)
+ assert await conversion.convert_cancel_pending_trial(pending_trial, PRO) is None
boundaries.sync.assert_awaited_once_with(dict(converted))
boundaries.modify.assert_not_awaited()
@@ -207,7 +209,7 @@ async def test_canceled_trial_is_reconciled_and_refused(
boundaries.retrieve.return_value = canceled
with pytest.raises(conversion.TrialConversionRefused, match="has ended"):
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
boundaries.sync.assert_awaited_once_with(dict(canceled))
boundaries.expire.assert_not_awaited()
@@ -225,7 +227,7 @@ async def test_resumed_trial_is_refused_like_any_running_trial(
)
with pytest.raises(conversion.TrialConversionRefused) as refused:
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
assert str(refused.value) == (
"Your accepted plan starts after your trial. Manage the trial in billing."
@@ -236,20 +238,176 @@ async def test_resumed_trial_is_refused_like_any_running_trial(
@pytest.mark.asyncio
-async def test_a_card_stripe_cannot_charge_sends_the_conversion_to_checkout(
+async def test_a_card_stripe_cannot_charge_is_refused_until_it_is_updated(
pending_trial, boundaries
):
- """Only Checkout can take a new card, and ending a card-less trial would
- let Stripe cancel it instead of billing it."""
+ """Ending a card-less trial would let Stripe cancel it instead of billing
+ it, and Checkout can't take a new card beside the trial's subscription."""
boundaries.card.return_value = False
- assert not await conversion.convert_cancel_pending_trial(pending_trial)
+ with pytest.raises(conversion.TrialConversionRefused) as refused:
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
+ assert str(refused.value) == conversion.CARD_NEEDED
boundaries.expire.assert_not_awaited()
boundaries.modify.assert_not_awaited()
boundaries.sync.assert_not_awaited()
+async def test_another_plan_moves_the_trials_own_subscription_onto_its_price(
+ pending_trial, boundaries
+):
+ """Stripe limits a customer to one subscription, so Max is bought by
+ changing the trial's, with the choice recorded for the reconcile."""
+ page = await conversion.convert_cancel_pending_trial(
+ pending_trial, SubscriptionTier.MAX, "price_max"
+ )
+
+ assert page is None
+ boundaries.modify.assert_awaited_once_with(
+ "sub_1",
+ cancel_at_period_end=False,
+ trial_end="now",
+ items=[{"id": "si_1", "price": "price_max"}],
+ metadata={
+ "trial_conversion_price_id": "price_max",
+ "trial_conversion_tier": "MAX",
+ },
+ payment_behavior="error_if_incomplete",
+ )
+ boundaries.sync.assert_awaited_once_with(dict(boundaries.converted))
+
+
+async def test_another_plan_needs_a_subscription_with_one_plan(
+ pending_trial, live, boundaries
+):
+ live["items"] = {
+ "data": [
+ {"id": "si_1", "price": {"id": "price_pro"}, "quantity": 1},
+ {"id": "si_2", "price": {"id": "price_seat"}, "quantity": 1},
+ ],
+ "has_more": False,
+ }
+ boundaries.retrieve.side_effect = None
+ boundaries.retrieve.return_value = stripe.Subscription.construct_from(
+ live, "test-key"
+ )
+
+ with pytest.raises(ValueError, match="one plan"):
+ await conversion.convert_cancel_pending_trial(
+ pending_trial, SubscriptionTier.MAX, "price_max"
+ )
+
+ boundaries.modify.assert_not_awaited()
+
+
+def _bank_wants_to_confirm() -> stripe.CardError:
+ return stripe.CardError(
+ "Authentication required.",
+ param="card",
+ code="authentication_required",
+ json_body={"error": {"code": "authentication_required"}},
+ )
+
+
+def _held(live: dict, **changes) -> stripe.Subscription:
+ return stripe.Subscription.construct_from(
+ {
+ **live,
+ "pending_update": {"trial_end": 1, "expires_at": 2},
+ "latest_invoice": {
+ "id": "in_held",
+ "status": "open",
+ "created": 1,
+ "hosted_invoice_url": "https://invoice.stripe.com/i/test_pay",
+ },
+ **changes,
+ },
+ "test-key",
+ )
+
+
+ "tier,price_id,plan",
+ [
+ (PRO, None, {}),
+ (
+ SubscriptionTier.MAX,
+ "price_max",
+ {
+ "items": [{"id": "si_1", "price": "price_max"}],
+ "metadata": {
+ "trial_conversion_price_id": "price_max",
+ "trial_conversion_tier": "MAX",
+ },
+ },
+ ),
+ ],
+)
+async def test_a_bank_that_wants_to_confirm_gets_stripes_invoice_page(
+ pending_trial, live, boundaries, tier, price_id, plan
+):
+ """The same change is held until its invoice is paid; meanwhile the trial
+ stays cancel-pending, so nothing is saved. The hold names an API version
+ that takes metadata and cancel_at_period_end in a pending update."""
+ boundaries.modify.side_effect = [_bank_wants_to_confirm(), _held(live)]
+
+ page = await conversion.convert_cancel_pending_trial(pending_trial, tier, price_id)
+
+ assert page == "https://invoice.stripe.com/i/test_pay"
+ first, hold = boundaries.modify.await_args_list
+ assert "stripe_version" not in first.kwargs
+ assert hold.kwargs == {
+ "cancel_at_period_end": False,
+ "trial_end": "now",
+ **plan,
+ "payment_behavior": "pending_if_incomplete",
+ "expand": ["latest_invoice"],
+ "stripe_version": "2026-09-30.endive",
+ }
+ boundaries.sync.assert_not_awaited()
+
+
+async def test_a_held_change_that_was_paid_at_once_is_read_back_and_saved(
+ pending_trial, live, boundaries
+):
+ """The hold's answer is in the newer API version's shape, so the plan is
+ read back in the SDK's own version before it is saved."""
+ boundaries.modify.side_effect = [
+ _bank_wants_to_confirm(),
+ _held(live, status="active", pending_update=None),
+ ]
+ active = stripe.Subscription.construct_from(
+ {**live, "status": "active", "cancel_at_period_end": False}, "test-key"
+ )
+ boundaries.retrieve.side_effect = [
+ stripe.Subscription.construct_from(live, "test-key"),
+ active,
+ ]
+
+ assert await conversion.convert_cancel_pending_trial(pending_trial, PRO) is None
+
+ assert boundaries.retrieve.await_args_list[-1] == call(live["id"])
+ boundaries.sync.assert_awaited_once_with(dict(active))
+
+
+async def test_a_held_change_without_a_page_to_pay_on_is_an_error(
+ pending_trial, live, boundaries
+):
+ held = _held(live, latest_invoice={"id": "in_held", "created": 1})
+ boundaries.modify.side_effect = [_bank_wants_to_confirm(), held]
+
+ with pytest.raises(ValueError, match="no page"):
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
+
+ boundaries.sync.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_a_conversion_stripe_did_not_activate_is_saved_and_refused(
pending_trial, live, boundaries
@@ -261,7 +419,7 @@ async def test_a_conversion_stripe_did_not_activate_is_saved_and_refused(
boundaries.modify.return_value = canceled
with pytest.raises(conversion.TrialConversionRefused, match="has ended"):
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
boundaries.sync.assert_awaited_once_with(dict(canceled))
@@ -274,7 +432,7 @@ async def test_a_failed_sync_after_the_charge_still_reports_the_conversion(
it, so the paying customer is not told the change failed."""
boundaries.sync.side_effect = stripe.APIConnectionError("Stripe is unreachable")
- assert await conversion.convert_cancel_pending_trial(pending_trial)
+ assert await conversion.convert_cancel_pending_trial(pending_trial, PRO) is None
boundaries.modify.assert_awaited_once()
@@ -288,7 +446,7 @@ async def test_a_busy_checkout_lock_is_a_retryable_conflict(pending_trial, bound
with patch.object(conversion, "subscription_checkout_lock", busy):
with pytest.raises(conversion.TrialConversionRefused) as refused:
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
assert str(refused.value) == "Your trial is already being updated. Please retry."
boundaries.retrieve.assert_not_awaited()
@@ -308,7 +466,7 @@ async def test_refuses_while_another_plan_is_live(
)
with pytest.raises(conversion.TrialConversionRefused) as refused:
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
assert str(refused.value) == (
"Another plan is already active. Manage it in billing."
@@ -327,7 +485,7 @@ async def test_ended_plans_do_not_block_the_conversion(pending_trial, live, boun
{"id": "sub_abandoned", "status": "incomplete_expired"},
)
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
boundaries.modify.assert_awaited_once()
boundaries.sync.assert_awaited_once_with(dict(boundaries.converted))
@@ -354,7 +512,7 @@ async def test_conversion_refreshes_the_cached_subscription_lookup(
AsyncMock(side_effect=[trialing, boundaries.converted]),
):
assert await subscription_lookup("cus_1") is trialing
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
assert await subscription_lookup("cus_1") is boundaries.converted
@@ -365,7 +523,7 @@ async def test_card_decline_leaves_the_trial_cancel_pending(pending_trial, bound
)
with pytest.raises(stripe.CardError):
- await conversion.convert_cancel_pending_trial(pending_trial)
+ await conversion.convert_cancel_pending_trial(pending_trial, PRO)
boundaries.sync.assert_not_awaited()
assert boundaries.calls[-1] == "unlock"
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_fixtures.py b/autogpt_platform/backend/backend/data/subscription_trial_fixtures.py
index 5356815755..87c0b6cfd1 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_fixtures.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_fixtures.py
@@ -70,7 +70,9 @@ def subscription(trial):
},
"pending_setup_intent": None,
"items": {
- "data": [{"price": {"id": trial.offer.price_id}, "quantity": 1}],
+ "data": [
+ {"id": "si_1", "price": {"id": trial.offer.price_id}, "quantity": 1}
+ ],
"has_more": False,
},
}
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_payment.py b/autogpt_platform/backend/backend/data/subscription_trial_payment.py
index 6ee644c812..2a28e37d62 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_payment.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_payment.py
@@ -3,11 +3,25 @@
from datetime import datetime
import stripe
+from prisma.enums import SubscriptionTier
from pydantic import BaseModel, Field
from backend.data.stripe_client import stripe_call
from backend.data.subscription_trial_config import AcceptedTrialOffer
+# A trial that ends on a plan other than the accepted one is moved onto that
+# plan's price with these beside it; the reconcile grants no other price.
+CONVERSION_PRICE_KEY = "trial_conversion_price_id"
+CONVERSION_TIER_KEY = "trial_conversion_tier"
+_CHOSEN_TIERS = frozenset(
+ {
+ SubscriptionTier.BASIC,
+ SubscriptionTier.PRO,
+ SubscriptionTier.MAX,
+ SubscriptionTier.BUSINESS,
+ }
+)
+
class Card(BaseModel):
exp_month: int
@@ -68,10 +82,18 @@ class Invoice(BaseModel):
status: str | None = None
created: int
billing_reason: str | None = None
+ hosted_invoice_url: str | None = None
+
+
+class Recurring(BaseModel):
+ interval: str
class SubscriptionPrice(BaseModel):
id: str
+ unit_amount: int | None = None
+ currency: str | None = None
+ recurring: Recurring | None = None
class SubscriptionItem(BaseModel):
@@ -88,11 +110,42 @@ class CancellationDetails(BaseModel):
comment: str | None = None
-class SubscriptionSnapshot(BaseModel):
+class ChosenPlan(BaseModel):
+ tier: SubscriptionTier
+ price: SubscriptionPrice
+
+
+class SubscriptionPlanTerms(BaseModel):
+ """The plan a trial subscription carries."""
+
+ metadata: dict[str, str] = Field(default_factory=dict)
+ items: SubscriptionItems | None = None
+
+ def has_accepted_price(self, offer: AcceptedTrialOffer) -> bool:
+ price = self._sole_price()
+ return price is not None and price.id == offer.price_id
+
+ def chosen_plan(self) -> ChosenPlan | None:
+ """The plan the customer ended the trial on in place of the accepted
+ one, while the subscription carries exactly that plan's price."""
+ price = self._sole_price()
+ if price is None or price.id != self.metadata.get(CONVERSION_PRICE_KEY):
+ return None
+ tier = self.metadata.get(CONVERSION_TIER_KEY)
+ chosen = next((t for t in _CHOSEN_TIERS if t.value == tier), None)
+ return ChosenPlan(tier=chosen, price=price) if chosen else None
+
+ def _sole_price(self) -> SubscriptionPrice | None:
+ if not self.items or self.items.has_more or len(self.items.data) != 1:
+ return None
+ item = self.items.data[0]
+ return item.price if item.quantity == 1 else None
+
+
+class SubscriptionSnapshot(SubscriptionPlanTerms):
id: str
customer: str
status: str
- metadata: dict[str, str] = Field(default_factory=dict)
trial_start: int | None = None
trial_end: int | None = None
ended_at: int | None = None
@@ -103,16 +156,6 @@ class SubscriptionSnapshot(BaseModel):
customer_default_payment_method: PaymentMethod | None = None
pending_setup_intent: str | dict | None = None
latest_invoice: Invoice | None = None
- items: SubscriptionItems | None = None
-
- def has_accepted_price(self, offer: AcceptedTrialOffer) -> bool:
- return bool(
- self.items
- and not self.items.has_more
- and len(self.items.data) == 1
- and self.items.data[0].price.id == offer.price_id
- and self.items.data[0].quantity == 1
- )
def has_verified_card(self, now: datetime) -> bool:
method = self.effective_payment_method()
diff --git a/autogpt_platform/backend/backend/data/subscription_trial_stripe.py b/autogpt_platform/backend/backend/data/subscription_trial_stripe.py
index 70f7101aae..60d663f5a8 100644
--- a/autogpt_platform/backend/backend/data/subscription_trial_stripe.py
+++ b/autogpt_platform/backend/backend/data/subscription_trial_stripe.py
@@ -107,10 +107,13 @@ async def _reconcile_locked(
snapshot = SubscriptionSnapshot.model_validate(raw)
if snapshot.id != subscription_id or snapshot.status != "canceled":
raise ValueError("Stripe did not confirm trial cancellation")
+ # The one other price a trial may end on is the plan the customer chose
+ # to start in its place, once that switch has gone through.
if (
trial.converted_at is None
and snapshot.status in ("active", "trialing")
and not snapshot.has_accepted_price(trial.offer)
+ and not (snapshot.status == "active" and snapshot.chosen_plan())
):
raise ValueError(
"Stripe items do not match the accepted trial price and quantity"
@@ -231,7 +234,8 @@ def trial_subscription_tier(
and invoice.created >= end
and invoice.billing_reason != "subscription_create"
):
- return SubscriptionTier(trial.offer.tier)
+ chosen = subscription.chosen_plan()
+ return chosen.tier if chosen else SubscriptionTier(trial.offer.tier)
return SubscriptionTier.NO_TIER
@@ -254,7 +258,11 @@ async def _save_snapshot(
consumed_at = consumed_at or now
converted_at = trial.converted_at
conversion_invoice_id = trial.conversion_invoice_id
- if converted_at is None and tier.value == trial.offer.tier:
+ # Only a paid conversion reads as a paid tier here.
+ if converted_at is None and tier not in (
+ SubscriptionTier.TRIAL,
+ SubscriptionTier.NO_TIER,
+ ):
if snapshot.latest_invoice is None:
raise ValueError("Trial conversion requires a paid invoice")
converted_at = now
diff --git a/autogpt_platform/backend/backend/notifications/trial.py b/autogpt_platform/backend/backend/notifications/trial.py
index 8dda419973..2d02994772 100644
--- a/autogpt_platform/backend/backend/notifications/trial.py
+++ b/autogpt_platform/backend/backend/notifications/trial.py
@@ -29,6 +29,7 @@ from backend.notifications.trial_audience import (
leave_trial_group,
queue_trial_audience_change,
)
+from backend.notifications.trial_plan import notice_plan
from backend.util.posthog_events import PostHogEvent
logger = logging.getLogger(__name__)
@@ -86,7 +87,7 @@ async def notify_trial(subscription: dict, kind: TrialNoticeKind) -> bool:
if kind == "ended" and await _another_plan_is_live(trial, current):
await leave_trial_group(user)
return True
- data = trial_notice_data(trial, kind, user.name or "there")
+ data = trial_notice_data(trial, kind, user.name or "there", current)
claim = trial_notice_key(trial, kind)
data.notice_key = claim
if not await claim_once(claim):
@@ -105,14 +106,15 @@ async def notify_trial(subscription: dict, kind: TrialNoticeKind) -> bool:
raise
if kind == "converted":
await join_paying_audience(user)
+ plan = notice_plan(trial, kind, current)
_track_billing_event(
TRIAL_NOTICE_EVENTS[kind],
user_id,
{
"trial_id": trial.id,
"trial_offer_version": trial.offer.version,
- "subscription_tier": trial.offer.tier,
- "billing_cycle": trial.offer.billing_cycle,
+ "subscription_tier": plan.tier,
+ "billing_cycle": plan.cycle,
"trial_duration_days": trial.offer.duration_days,
},
)
@@ -175,7 +177,7 @@ async def trial_notice_disposition(
return "obsolete"
if data.notice_key != trial_notice_key(trial, data.kind):
return "obsolete"
- expected = trial_notice_data(trial, data.kind, data.user_name)
+ expected = trial_notice_data(trial, data.kind, data.user_name, current)
if data.model_copy(update={"notice_key": None}) != expected:
return "obsolete"
if trial.status != current.get("status") or trial.cancel_at_period_end != bool(
@@ -234,25 +236,29 @@ def trial_notice_key(trial: TrialState, kind: TrialNoticeKind) -> str:
def trial_notice_data(
- trial: TrialState, kind: TrialNoticeKind, name: str
+ trial: TrialState,
+ kind: TrialNoticeKind,
+ name: str,
+ current: dict | None = None,
) -> TrialUpdateData:
if trial.ends_at is None:
raise ValueError("Cannot send a trial notice without the accepted end date")
- offer = trial.offer
- cycle_noun = "month" if offer.billing_cycle == "monthly" else "year"
+ plan = notice_plan(trial, kind, current)
+ title = plan.tier.title()
+ cycle_noun = "month" if plan.cycle == "monthly" else "year"
return TrialUpdateData(
user_name=name,
kind=kind,
plan=SubscriptionPlan(
- name=offer.tier.title(),
- cycle=offer.billing_cycle,
+ name=title,
+ cycle=plan.cycle,
cycle_noun=cycle_noun,
- label=f"{offer.tier.title()} — {offer.billing_cycle}",
- price_display=f"{format_amount(offer.unit_amount, offer.currency)} {offer.currency.upper()} / {cycle_noun}",
+ label=f"{title} — {plan.cycle}",
+ price_display=f"{format_amount(plan.unit_amount, plan.currency)} {plan.currency.upper()} / {cycle_noun}",
),
ends_label=trial.ends_at.astimezone(UTC).strftime("%d %b %Y at %H:%M UTC"),
- onboarding_credit_amount=offer.onboarding_credit_amount,
- offer_version=offer.version,
+ onboarding_credit_amount=trial.offer.onboarding_credit_amount,
+ offer_version=trial.offer.version,
)
diff --git a/autogpt_platform/backend/backend/notifications/trial_plan.py b/autogpt_platform/backend/backend/notifications/trial_plan.py
new file mode 100644
index 0000000000..1820b97da3
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/trial_plan.py
@@ -0,0 +1,40 @@
+"""The plan a trial notice is about."""
+
+from typing import Literal
+
+from pydantic import BaseModel
+
+from backend.data.subscription_trial import TrialState
+from backend.data.subscription_trial_payment import SubscriptionPlanTerms
+
+
+class NoticePlan(BaseModel):
+ tier: str
+ cycle: Literal["monthly", "yearly"]
+ unit_amount: int | None
+ currency: str
+
+
+def notice_plan(trial: TrialState, kind: str, current: dict | None) -> NoticePlan:
+ """The accepted plan, or for a conversion the plan the customer chose to
+ end the trial on in its place."""
+ offer = trial.offer
+ chosen = (
+ SubscriptionPlanTerms.model_validate(current).chosen_plan()
+ if kind == "converted" and current
+ else None
+ )
+ if chosen is None:
+ return NoticePlan(
+ tier=offer.tier,
+ cycle=offer.billing_cycle,
+ unit_amount=offer.unit_amount,
+ currency=offer.currency,
+ )
+ recurring = chosen.price.recurring
+ return NoticePlan(
+ tier=chosen.tier.value,
+ cycle="yearly" if recurring and recurring.interval == "year" else "monthly",
+ unit_amount=chosen.price.unit_amount,
+ currency=chosen.price.currency or offer.currency,
+ )
diff --git a/autogpt_platform/backend/backend/notifications/trial_plan_test.py b/autogpt_platform/backend/backend/notifications/trial_plan_test.py
new file mode 100644
index 0000000000..a94ff30a67
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/trial_plan_test.py
@@ -0,0 +1,128 @@
+"""A trial converted onto a plan the customer chose in place of the accepted
+one is announced as that plan, at its price; every other notice keeps the
+accepted terms."""
+
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.data.notifications import NotificationResult
+from backend.data.subscription_trial import TrialState
+from backend.notifications import trial as notices
+from backend.notifications.trial_plan import notice_plan
+
+pytest_plugins = ("backend.data.subscription_trial_fixtures",)
+
+
+def converted(trial: TrialState) -> TrialState:
+ now = datetime.now(UTC)
+ return trial.model_copy(
+ update={
+ "subscription_id": "sub_1",
+ "status": "active",
+ "ends_at": now - timedelta(minutes=1),
+ "consumed_at": now - timedelta(days=2),
+ "converted_at": now,
+ "conversion_invoice_id": "in_max",
+ }
+ )
+
+
+def _switched(interval: str = "month") -> dict:
+ return {
+ "id": "sub_1",
+ "customer": "cus_1",
+ "status": "active",
+ "metadata": {
+ "user_id": "user-1",
+ "trial_enrollment_id": "trial-1",
+ "trial_checkout_attempt": "0",
+ "trial_conversion_price_id": "price_max",
+ "trial_conversion_tier": "MAX",
+ },
+ "items": {
+ "data": [
+ {
+ "id": "si_1",
+ "quantity": 1,
+ "price": {
+ "id": "price_max",
+ "unit_amount": 32000,
+ "currency": "usd",
+ "recurring": {"interval": interval},
+ },
+ }
+ ],
+ "has_more": False,
+ },
+ }
+
+
+def test_a_conversion_onto_the_chosen_plan_is_announced_as_that_plan(converted):
+ data = notices.trial_notice_data(converted, "converted", "Sam", _switched())
+
+ assert data.plan.name == "Max"
+ assert data.plan.label == "Max — monthly"
+ assert data.plan.price_display == "$320.00 USD / month"
+
+
+def test_a_yearly_choice_is_announced_as_yearly(converted):
+ plan = notice_plan(converted, "converted", _switched("year"))
+
+ assert (plan.tier, plan.cycle) == ("MAX", "yearly")
+
+
[email protected]("kind", ["started", "canceled", "ended", "payment_failed"])
+def test_other_notices_keep_the_accepted_terms(converted, kind):
+ data = notices.trial_notice_data(converted, kind, "Sam", _switched())
+
+ assert data.plan.name == "Pro"
+ assert data.plan.price_display == "$50.00 USD / month"
+
+
+def test_a_conversion_on_the_accepted_price_keeps_its_terms(converted, subscription):
+ data = notices.trial_notice_data(converted, "converted", "Sam", subscription)
+
+ assert data.plan.name == "Pro"
+
+
+async def test_the_conversion_event_reports_the_chosen_plan(converted):
+ current = _switched()
+ with (
+ patch.object(notices, "stripe_call", AsyncMock(return_value=current)),
+ patch.object(
+ notices,
+ "credit_db",
+ return_value=MagicMock(
+ get_subscription_trial=AsyncMock(return_value=converted)
+ ),
+ ),
+ patch.object(
+ notices,
+ "user_db",
+ return_value=MagicMock(
+ get_user_by_id=AsyncMock(
+ return_value=SimpleNamespace(id="user-1", name="Sam")
+ )
+ ),
+ ),
+ patch.object(notices, "claim_once", AsyncMock(return_value=True)),
+ patch.object(notices, "queue_trial_audience_change", AsyncMock()),
+ patch.object(notices, "join_paying_audience", AsyncMock()),
+ patch.object(
+ notices,
+ "queue_notification_async",
+ AsyncMock(return_value=NotificationResult(success=True)),
+ ) as queue,
+ patch.object(notices, "_track_billing_event") as track,
+ ):
+ assert await notices.notify_trial(current, "converted")
+
+ assert queue.await_args.args[0].data.plan.name == "Max"
+ properties = track.call_args.args[2]
+ assert properties["subscription_tier"] == "MAX"
+ assert properties["billing_cycle"] == "monthly"
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-upgrade.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-upgrade.test.tsx
index e355b59097..50218a7e86 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-upgrade.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-upgrade.test.tsx
@@ -1,14 +1,11 @@
import { server } from "@/mocks/mock-server";
-import {
- installGtagShim,
- removeGtagShim,
-} from "@/tests/integrations/gtag-shim";
import {
act,
fireEvent,
render,
screen,
waitFor,
+ within,
} from "@/tests/integrations/test-utils";
import {
deferredTrialResponse,
@@ -51,10 +48,13 @@ vi.mock(
}),
);
-const checkoutURL = "https://checkout.stripe.com/c/pay/cs_max";
+const paymentPage = "https://invoice.stripe.com/i/acct_1/test_pay";
-function stubNavigation() {
- return vi.spyOn(window.location, "assign").mockImplementation(() => {});
+async function openUpgrade() {
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Upgrade to Max" }),
+ );
+ return screen.findByRole("dialog", { name: "Start Max today?" });
}
beforeEach(() => setTrialUser());
@@ -63,29 +63,36 @@ afterEach(() => {
toast.mockReset();
analytics.trackPaywallViewed.mockReset();
analytics.trackPlanSelected.mockReset();
- removeGtagShim();
- vi.unstubAllEnvs();
vi.restoreAllMocks();
});
describe("upgrading past the trial's plan", () => {
it.each([
- ["monthly", trialOffer],
- ["yearly", yearlyOffer],
+ ["monthly", trialOffer, "$320 / month"],
+ ["yearly", yearlyOffer, "$3,264 / year"],
] as const)(
- "opens Stripe Checkout for the next tier on the %s cycle",
- async (cycle, offer) => {
- const assign = stubNavigation();
+ "charges the saved card for the next tier on the %s cycle once confirmed",
+ async (cycle, offer, price) => {
+ const assign = vi.spyOn(window.location, "assign");
mockBilling(trialResponse({ ...cancelPending, offer }));
const body = mockPlanRequest(() =>
- HttpResponse.json({ ...trialSubscription, url: checkoutURL }),
+ HttpResponse.json({ ...trialSubscription, tier: "MAX", url: "" }),
);
render(<SettingsBillingPage />);
+
+ const dialog = await openUpgrade();
+ expect(dialog.textContent).toContain(price);
+ expect(body).not.toHaveBeenCalled();
fireEvent.click(
- await screen.findByRole("button", { name: "Upgrade to Max" }),
+ within(dialog).getByRole("button", { name: "Subscribe to Max" }),
);
- await waitFor(() => expect(assign).toHaveBeenCalledWith(checkoutURL));
+ await waitFor(() =>
+ expect(toast).toHaveBeenCalledWith({
+ title: "You're on Max",
+ description: "Your trial has ended and your plan starts today.",
+ }),
+ );
expect(body).toHaveBeenCalledWith({
tier: "MAX",
billing_cycle: cycle,
@@ -97,89 +104,86 @@ describe("upgrading past the trial's plan", () => {
billing_cycle: cycle,
surface: "billing",
});
- expect(screen.queryByRole("dialog")).toBeNull();
- expect(toast).not.toHaveBeenCalled();
+ expect(assign).not.toHaveBeenCalled();
},
);
- it("reports begin_checkout at the next tier's price before leaving", async () => {
- vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
- vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");
- const gtagCalls = installGtagShim();
- const assign = stubNavigation();
+ it("keeps the trial without a request when the person backs out", async () => {
mockBilling();
- mockPlanRequest(() =>
- HttpResponse.json({ ...trialSubscription, url: checkoutURL }),
+ const body = mockPlanRequest(() =>
+ HttpResponse.json({ ...trialSubscription, url: "" }),
);
render(<SettingsBillingPage />);
- const upgrade = await screen.findByRole("button", {
- name: "Upgrade to Max",
- });
- fireEvent.click(upgrade);
- await waitFor(() =>
- expect(gtagCalls).toContainEqual([
- "event",
- "conversion",
- {
- send_to: "AW-123/BC",
- value: 320,
- currency: "USD",
- event_callback: expect.any(Function),
- },
- ]),
+ const dialog = await openUpgrade();
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Keep my trial" }),
);
- expect(upgrade.hasAttribute("disabled")).toBe(true);
- await waitFor(() => expect(assign).toHaveBeenCalledWith(checkoutURL));
+
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(body).not.toHaveBeenCalled();
});
- it("frees the choices after handing off, so a page restored from history works", async () => {
- const assign = stubNavigation();
- mockBilling();
+ it("sends the customer to Stripe's page when their bank wants to confirm", async () => {
+ const assign = vi.spyOn(window.location, "assign");
+ const { hits } = mockBilling();
mockPlanRequest(() =>
- HttpResponse.json({ ...trialSubscription, url: checkoutURL }),
+ HttpResponse.json({ ...trialSubscription, url: paymentPage }),
);
render(<SettingsBillingPage />);
fireEvent.click(
- await screen.findByRole("button", { name: "Upgrade to Max" }),
+ within(await openUpgrade()).getByRole("button", {
+ name: "Subscribe to Max",
+ }),
);
- await waitFor(() => expect(assign).toHaveBeenCalledOnce());
+ const bank = await screen.findByRole("dialog", {
+ name: "Confirm with your bank",
+ });
+ expect(bank.textContent).toContain("$320 / month payment for Max");
+ const pay = within(bank).getByRole("link", { name: "Pay on Stripe" });
+ expect(pay.getAttribute("href")).toBe(paymentPage);
+ expect(pay.getAttribute("target")).toBe("_blank");
+ expect(toast).not.toHaveBeenCalled();
+ expect(assign).not.toHaveBeenCalled();
+
+ // Closing re-reads the trial: the customer may have paid in the other tab.
+ const trialReads = hits.trial;
+ fireEvent.click(within(bank).getByRole("button", { name: "Done" }));
await waitFor(() =>
expect(
- screen
- .getByRole("button", { name: "Upgrade to Max" })
- .hasAttribute("disabled"),
- ).toBe(false),
+ screen.queryByRole("dialog", { name: "Confirm with your bank" }),
+ ).toBeNull(),
);
- expect(
- screen
- .getByRole("button", { name: "Subscribe to Pro" })
- .hasAttribute("disabled"),
- ).toBe(false);
+ await waitFor(() => expect(hits.trial).toBeGreaterThan(trialReads));
});
- it("shows why Checkout could not start", async () => {
- const assign = stubNavigation();
+ it("shows why Max could not start and frees the choices", async () => {
mockBilling();
mockPlanRequest(() =>
HttpResponse.json(
- { detail: "Stripe is unavailable. Please retry." },
- { status: 502 },
+ {
+ detail:
+ "Your saved card can't be charged. Update it under Payment method, then try again.",
+ },
+ { status: 409 },
),
);
render(<SettingsBillingPage />);
fireEvent.click(
- await screen.findByRole("button", { name: "Upgrade to Max" }),
+ within(await openUpgrade()).getByRole("button", {
+ name: "Subscribe to Max",
+ }),
);
+
await waitFor(() =>
expect(toast).toHaveBeenCalledWith({
title: "Unable to start Max",
- description: "Stripe is unavailable. Please retry.",
+ description:
+ "Your saved card can't be charged. Update it under Payment method, then try again.",
variant: "destructive",
}),
);
- expect(assign).not.toHaveBeenCalled();
await waitFor(() =>
expect(
screen
@@ -189,35 +193,35 @@ describe("upgrading past the trial's plan", () => {
);
});
- it("does not send user B to the Checkout user A started", async () => {
- const assign = stubNavigation();
+ it("does not show user B the payment page user A was sent to", async () => {
setTrialUser("user-a");
mockBilling();
mockPricePerUser();
- const checkout = deferredTrialResponse<void>();
+ const charge = deferredTrialResponse<void>();
const sent = vi.fn();
server.use(
http.post("*/api/credits/subscription", async () => {
sent();
- await checkout.promise;
- return HttpResponse.json({
- ...trialSubscription,
- url: "https://checkout.stripe.com/c/pay/cs_user_a",
- });
+ await charge.promise;
+ return HttpResponse.json({ ...trialSubscription, url: paymentPage });
}),
);
render(<SettingsBillingPage />);
fireEvent.click(
- await screen.findByRole("button", { name: "Upgrade to Max" }),
+ within(await openUpgrade()).getByRole("button", {
+ name: "Subscribe to Max",
+ }),
);
await waitFor(() => expect(sent).toHaveBeenCalledOnce());
act(() => setTrialUser("user-b"));
await screen.findByText("$30");
- checkout.resolve();
+ charge.resolve();
await act(() => new Promise((settle) => setTimeout(settle, 50)));
- expect(assign).not.toHaveBeenCalled();
+ expect(
+ screen.queryByRole("dialog", { name: "Confirm with your bank" }),
+ ).toBeNull();
expect(toast).not.toHaveBeenCalled();
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/ConfirmWithBankDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/ConfirmWithBankDialog.tsx
new file mode 100644
index 0000000000..7426815af7
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/ConfirmWithBankDialog.tsx
@@ -0,0 +1,53 @@
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+
+import { formatChoicePrice } from "./helpers";
+import type { PaymentPage } from "./useTrialPlanRequest";
+
+interface Props {
+ page: PaymentPage | null;
+ onClose: () => void;
+}
+
+export function ConfirmWithBankDialog({ page, onClose }: Props) {
+ return (
+ <Dialog
+ title="Confirm with your bank"
+ styling={{ maxWidth: "28rem", minWidth: "auto" }}
+ controlled={{
+ isOpen: page !== null,
+ set: (open) => {
+ if (!open) onClose();
+ },
+ }}
+ >
+ <Dialog.Content>
+ {page ? (
+ <Text variant="body" unmask={false}>
+ Your bank wants to confirm the {formatChoicePrice(page.plan)}{" "}
+ payment for {page.plan.label}. Pay on Stripe&apos;s secure page and{" "}
+ {page.plan.label} starts right away. Until then your trial stays as
+ it is.
+ </Text>
+ ) : null}
+ <Dialog.Footer>
+ <Button variant="outline" onClick={onClose}>
+ Done
+ </Button>
+ {page ? (
+ <Button
+ as="NextLink"
+ variant="primary"
+ href={page.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Pay on Stripe
+ </Button>
+ ) : null}
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/TrialPlanChoices.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/TrialPlanChoices.tsx
index df949e57a5..1be0f9658d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/TrialPlanChoices.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/TrialPlanChoices.tsx
@@ -3,6 +3,8 @@
import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";
import { ConfirmTrialPlanDialog } from "./ConfirmTrialPlanDialog";
+import { ConfirmWithBankDialog } from "./ConfirmWithBankDialog";
+import { formatChoicePrice } from "./helpers";
import { PlanChoice } from "./PlanChoice";
import { useTrialPlanChoices } from "./useTrialPlanChoices";
@@ -15,17 +17,19 @@ export function TrialPlanChoices({ offer }: Props) {
isVisible,
ownPlan,
upgradePlan,
- ownPrice,
+ confirmPlan,
requestedTier,
- isConfirmOpen,
+ paymentPage,
onSelectOwnPlan,
- onConfirmOwnPlan,
- onCloseConfirm,
onSelectUpgradePlan,
+ onConfirmPlan,
+ onCloseConfirm,
+ onClosePaymentPage,
} = useTrialPlanChoices(offer);
if (!isVisible) return null;
const isBusy = requestedTier !== null;
+ const dialogPlan = confirmPlan ?? ownPlan;
return (
<section aria-label="Plan choices" className="flex flex-col gap-3">
@@ -50,13 +54,14 @@ export function TrialPlanChoices({ offer }: Props) {
) : null}
</ul>
<ConfirmTrialPlanDialog
- isOpen={isConfirmOpen}
- planLabel={ownPlan.label}
- price={ownPrice}
- isSaving={requestedTier === ownPlan.tier}
- onConfirm={onConfirmOwnPlan}
+ isOpen={confirmPlan !== null}
+ planLabel={dialogPlan.label}
+ price={formatChoicePrice(dialogPlan)}
+ isSaving={requestedTier === dialogPlan.tier}
+ onConfirm={onConfirmPlan}
onClose={onCloseConfirm}
/>
+ <ConfirmWithBankDialog page={paymentPage} onClose={onClosePaymentPage} />
</section>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/helpers.ts
index e4ecf2af47..badeb8b469 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/helpers.ts
@@ -22,7 +22,6 @@ export interface PlanChoiceDetails {
amount: string;
cadence: "month" | "year";
description: string;
- cents?: number;
}
export function getCancelPendingOffer(trial: TrialStatusResponse | undefined) {
@@ -63,10 +62,20 @@ export function getUpgradePlanChoice(
tier,
subscription.tier_multipliers,
),
- cents,
};
}
+export function formatChoicePrice(plan: PlanChoiceDetails) {
+ return `${plan.amount} / ${plan.cadence}`;
+}
+
+export function findPlanChoice(
+ plans: (PlanChoiceDetails | null)[],
+ tier: PlanChoiceDetails["tier"],
+) {
+ return plans.find((plan) => plan?.tier === tier) ?? null;
+}
+
// The plan only counts as started once the server reports it: a charge the
// reconcile hasn't recorded yet still reads as the trial.
export function describePlanResult(
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.ts
index 2ff5a70542..55faab843e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.ts
@@ -5,7 +5,6 @@ import { useEffect, useState } from "react";
import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";
import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";
import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";
-import { formatPlanPrice } from "@/components/organisms/TrialCard/helpers";
import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
import {
trackPaywallViewed,
@@ -13,6 +12,7 @@ import {
} from "@/services/analytics/monetization-analytics";
import {
+ findPlanChoice,
getOwnPlanChoice,
getUpgradePlanChoice,
type PlanChoiceDetails,
@@ -29,8 +29,12 @@ export function useTrialPlanChoices(offer: TrialOfferResponse) {
: undefined,
},
});
- const { requestedTier, requestPlan } = useTrialPlanRequest(offer);
- const [confirmFor, setConfirmFor] = useState<string | null>(null);
+ const request = useTrialPlanRequest(offer);
+ // Either plan charges the saved card today, so both ask first.
+ const [confirming, setConfirming] = useState<{
+ ownerID: string;
+ tier: PlanChoiceDetails["tier"];
+ } | null>(null);
// A trial status that lags behind a plan change must not offer the choices
// again, so they wait for the subscription itself to still be the trial.
@@ -39,41 +43,42 @@ export function useTrialPlanChoices(offer: TrialOfferResponse) {
const upgradePlan = subscription.data
? getUpgradePlanChoice(offer, subscription.data)
: null;
+ const confirmPlan =
+ confirming && confirming.ownerID === userID
+ ? findPlanChoice([ownPlan, upgradePlan], confirming.tier)
+ : null;
useEffect(() => {
if (isVisible) trackPaywallViewed("billing");
}, [isVisible]);
- function trackSelection(plan: PlanChoiceDetails) {
+ function selectPlan(plan: PlanChoiceDetails) {
trackPlanSelected({
subscription_tier: plan.tier,
billing_cycle: offer.billing_cycle,
surface: "billing",
});
+ if (userID) setConfirming({ ownerID: userID, tier: plan.tier });
}
- async function confirmOwnPlan() {
- const isLeaving = await requestPlan(ownPlan);
- if (!isLeaving) setConfirmFor(null);
+ async function confirmPlanChoice() {
+ if (confirmPlan) await request.requestPlan(confirmPlan);
+ setConfirming(null);
}
return {
isVisible,
ownPlan,
upgradePlan,
- ownPrice: formatPlanPrice(offer),
- requestedTier,
- isConfirmOpen: confirmFor !== null && confirmFor === userID,
- onSelectOwnPlan: () => {
- trackSelection(ownPlan);
- setConfirmFor(userID ?? null);
- },
- onConfirmOwnPlan: () => void confirmOwnPlan(),
- onCloseConfirm: () => setConfirmFor(null),
+ confirmPlan,
+ requestedTier: request.requestedTier,
+ paymentPage: request.paymentPage,
+ onSelectOwnPlan: () => selectPlan(ownPlan),
onSelectUpgradePlan: () => {
- if (!upgradePlan) return;
- trackSelection(upgradePlan);
- void requestPlan(upgradePlan);
+ if (upgradePlan) selectPlan(upgradePlan);
},
+ onConfirmPlan: () => void confirmPlanChoice(),
+ onCloseConfirm: () => setConfirming(null),
+ onClosePaymentPage: request.closePaymentPage,
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanRequest.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanRequest.ts
index 766dabd6ce..9fc74e9519 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanRequest.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanRequest.ts
@@ -13,11 +13,6 @@ import { getGetTrialsGetTrialStatusQueryKey } from "@/app/api/__generated__/endp
import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";
import { toast } from "@/components/molecules/Toast/use-toast";
import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
-import {
- centsToUSD,
- getSubscriptionValue,
- trackAdsConversionBeforeNavigation,
-} from "@/services/analytics/google-ads";
import { readTier } from "../helpers";
import {
@@ -26,6 +21,12 @@ import {
type PlanChoiceDetails,
} from "./helpers";
+export interface PaymentPage {
+ ownerID: string;
+ plan: PlanChoiceDetails;
+ url: string;
+}
+
export function useTrialPlanRequest(offer: TrialOfferResponse) {
const userID = useAuthStore((state) => state.user?.id);
const queryClient = useQueryClient();
@@ -33,15 +34,14 @@ export function useTrialPlanRequest(offer: TrialOfferResponse) {
const [requestedTier, setRequestedTier] = useState<
PlanChoiceDetails["tier"] | null
>(null);
+ const [paymentPage, setPaymentPage] = useState<PaymentPage | null>(null);
async function requestPlan(plan: PlanChoiceDetails) {
- if (!userID || requestedTier) return false;
+ if (!userID || requestedTier) return;
setRequestedTier(plan.tier);
try {
- return await submitPlan(plan, userID);
+ await submitPlan(plan, userID);
} finally {
- // Cleared after a Checkout hand-off too: a page restored from the
- // back-forward cache would otherwise keep both plans disabled.
setRequestedTier(null);
}
}
@@ -56,22 +56,23 @@ export function useTrialPlanRequest(offer: TrialOfferResponse) {
description: "Review your current plan below.",
});
await refreshBilling();
- return false;
+ return;
}
const response = await updateTier({
data: buildPlanRequest(plan, offer.billing_cycle),
});
- if (useAuthStore.getState().user?.id !== requestUserID) return false;
- const url = response.status === 200 ? response.data.url : undefined;
- if (url) {
- await leaveForCheckout(plan, url);
- return true;
+ if (useAuthStore.getState().user?.id !== requestUserID) return;
+ const data = response.status === 200 ? response.data : undefined;
+ // The bank wants to confirm the charge: nothing changes until the
+ // customer pays on Stripe's page.
+ if (data?.url) {
+ setPaymentPage({ ownerID: requestUserID, plan, url: data.url });
+ return;
}
- const tier = response.status === 200 ? response.data.tier : undefined;
- toast(describePlanResult(plan, tier));
+ toast(describePlanResult(plan, data?.tier));
await refreshBilling();
} catch (error) {
- if (useAuthStore.getState().user?.id !== requestUserID) return false;
+ if (useAuthStore.getState().user?.id !== requestUserID) return;
// A toast, not an inline alert: the refresh below usually unmounts these
// choices (the trial was resumed or ended elsewhere).
toast({
@@ -82,7 +83,6 @@ export function useTrialPlanRequest(offer: TrialOfferResponse) {
});
await refreshBilling();
}
- return false;
}
async function isStillOnTrial() {
@@ -103,17 +103,14 @@ export function useTrialPlanRequest(offer: TrialOfferResponse) {
);
}
- async function leaveForCheckout(plan: PlanChoiceDetails, url: string) {
- await trackAdsConversionBeforeNavigation("begin_checkout", {
- value:
- centsToUSD(plan.cents) ??
- getSubscriptionValue(plan.tier, offer.billing_cycle),
- });
- window.location.assign(url);
- }
-
return {
requestedTier,
requestPlan,
+ paymentPage: paymentPage?.ownerID === userID ? paymentPage : null,
+ closePaymentPage: () => {
+ setPaymentPage(null);
+ // The customer may have paid in the other tab.
+ void refreshBilling();
+ },
};
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index b2f690f754..6a5daf57b0 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -31034,7 +31034,7 @@
"url": {
"type": "string",
"title": "Url",
- "description": "Populated only when POST /credits/subscription starts a Stripe Checkout Session (BASIC → paid upgrade). Empty string in all other branches — the client redirects to this URL when non-empty.",
+ "description": "Populated only when POST /credits/subscription starts a Stripe Checkout Session (BASIC → paid upgrade), or when a trial ending early needs the customer's bank to confirm its payment, on Stripe's invoice page. Empty string in all other branches — the client sends the customer to this URL when non-empty.",
"default": ""
}
},