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.
feat(platform): canceling a trial keeps access until the trial ends (#15358)
John Ababseh0cddeafd8d3a
diff --git a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.pyindex 5fc5485df7..a5ac0b1a15 100644--- a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py+++ b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py@@ -49,10 +49,19 @@ from backend.data.credit import (from backend.data.notifications import PassWorkEvent, PassWorkKindfrom backend.data.redis_client import get_redis_asyncfrom backend.data.stripe_client import stripe_call+from backend.data.subscription_checkout import AnotherPlanLive+from backend.data.subscription_trial import TrialStatefrom backend.data.subscription_trial_billing import (TRIAL_BILLING_EVENTS,sync_trials_for_billing_event,)+from backend.data.subscription_trial_conversion import (+ TRIAL_RUNNING,+ TrialConversionRefused,+ convert_cancel_pending_trial,+ get_cancel_pending_trial,+ is_trial_plan,+)from backend.data.user import get_user_by_idfrom backend.notifications import lifecyclefrom backend.notifications.queue import queue_pass_work@@ -65,6 +74,19 @@ from backend.util.settings import Settingslogger = 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()@@ -381,11 +403,20 @@ async def update_subscription_tier(# admin-granted tiers (DB tier set, no Stripe sub) must fall through to the# Checkout flow so "start paying for my current tier" is not a no-op.current_tier = user.subscription_tier or SubscriptionTier.NO_TIER- if current_tier == SubscriptionTier.TRIAL and tier != SubscriptionTier.NO_TIER:- raise HTTPException(- 409,- "Your accepted plan starts after your trial. Manage the trial in billing.",- )+ pending_trial = None+ if tier != SubscriptionTier.NO_TIER and current_tier in (+ SubscriptionTier.TRIAL,+ SubscriptionTier.NO_TIER,+ ):+ # Only a trial scheduled to end may start a paid plan before trial_end.+ # One that lost its card (NO_TIER) takes the same path, or the trial+ # subscription would refuse every plan until trial_end.+ pending_trial = await get_cancel_pending_trial(user_id)+ if pending_trial is None and current_tier == SubscriptionTier.TRIAL:+ raise HTTPException(409, TRIAL_RUNNING)+ converts_trial = pending_trial is not None and is_trial_plan(+ pending_trial, tier, request.billing_cycle+ )current_cycle = await get_user_billing_cycle(user_id) or "monthly"has_active_stripe_subscription = (await get_active_subscription_period_end(user_id) is not None@@ -468,8 +499,9 @@ async def update_subscription_tier(detail=f"Subscription not available for tier {tier.value}",)- # Target has no LD price — not provisionable (matches the GET hiding).- if target_price_id is None:+ # Target has no LD price — not provisionable (matches the GET hiding). The+ # trial's own plan converts on the price it accepted, which needs none.+ if target_price_id is None and not converts_trial:raise HTTPException(status_code=422,detail=f"Subscription not available for tier {tier.value}",@@ -477,25 +509,29 @@ async def update_subscription_tier(# Modify in place if there's a sub; else fall through to Checkout below.try:- modified = await modify_stripe_subscription_for_tier(- user_id, tier, request.billing_cycle+ modified = await _change_plan_in_place(+ user_id, tier, request.billing_cycle, pending_trial)if modified:- return await get_subscription_status(user_id)+ 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+ except TrialConversionRefused as e:+ raise HTTPException(status_code=409, detail=str(e))except ValueError as e:raise HTTPException(status_code=422, detail=str(e))except stripe.CardError as e:# Auto-charge failed under payment_behavior=error_if_incomplete: the# 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. Stripe emits- # ``authentication_required`` for raw PaymentIntent confirms but- # ``subscription_payment_intent_requires_action`` for Subscription.modify- # under ``error_if_incomplete``; both must map to the SCA branch.- if e.code in {- "authentication_required",- "subscription_payment_intent_requires_action",- }:+ # different message so the user doesn't try a new card.+ if _requires_authentication(e):logger.warning("SCA required on subscription upgrade for user %s: %s", user_id, e)@@ -634,6 +670,8 @@ async def update_subscription_tier(datafast_visitor_id=x_datafast_visitor_id,datafast_session_id=x_datafast_session_id,)+ except AnotherPlanLive as e:+ raise HTTPException(status_code=409, detail=str(e))except ValueError as e:raise HTTPException(status_code=422, detail=str(e))except stripe.StripeError as e:@@ -662,6 +700,46 @@ async def update_subscription_tier(return status+async def _change_plan_in_place(+ user_id: str,+ 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.+ """+ 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}"+ )+ 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"+ )++def _stripe_event_dedup_key(event_id: str) -> str:return f"stripe_webhook_event:{event_id}"diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.pyindex 5398253566..ba53e555ec 100644--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py@@ -87,6 +87,17 @@ def _stub_pending_subscription_change(mocker: pytest_mock.MockFixture) -> None:)[email protected](autouse=True)+def _stub_cancel_pending_trial(mocker: pytest_mock.MockFixture) -> None:+ """No trial scheduled to end, so TRIAL and NO_TIER requests here don't+ read the trial from the DB. The trial guard tests cover that lookup."""+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.get_cancel_pending_trial",+ new_callable=AsyncMock,+ return_value=None,+ )++@pytest.fixture(autouse=True)def track_checkout_started(mocker: pytest_mock.MockFixture) -> AsyncMock:"""Keep analytics off the network and let tests assert the event."""@@ -1671,6 +1682,58 @@ def test_update_subscription_tier_pro_to_max_subscription_payment_intent_requireassert "card was declined" not in detail+ "code,decline_code",+ [+ ("invoice_payment_intent_requires_action", None),+ ("card_declined", "authentication_required"),+ ],+)+def test_update_subscription_tier_pro_to_max_documented_authentication_codes_return_402(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+ code: str,+ decline_code: str | None,+) -> None:+ """Stripe documents invoice_payment_intent_requires_action, and+ authentication_required as a card_declined decline code, for a payment the+ bank wants authenticated: both get the authentication copy, not a decline."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.PRO++ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ _patch_payment_flag(mocker)+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ side_effect=stripe.CardError(+ "This payment requires additional user action before it can be"+ " completed successfully.",+ param=None,+ code=code,+ json_body={"error": {"code": code, "decline_code": decline_code}},+ ),+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "MAX",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ },+ )++ assert response.status_code == 402+ detail = response.json()["detail"].lower()+ assert "authentication" in detail+ assert "card was declined" not in detail++def test_update_subscription_tier_pro_to_max_no_payment_method_returns_402(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,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.pynew file mode 100644index 0000000000..5e281dfa9a--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_trial_guards_test.py@@ -0,0 +1,304 @@+"""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."""++from contextlib import asynccontextmanager+from unittest.mock import AsyncMock, MagicMock++import fastapi.testclient+import pytest+import pytest_mock+import stripe+from prisma.enums import SubscriptionTier++from backend.api.features import subscription_routes_test as routes_test+from backend.api.features import subscription_routes_trial_test as trial_test+from backend.api.features.subscription_routes_test import (+ _DEFAULT_TIER_PRICES,+ _DEFAULT_TIER_PRICES_YEARLY,+)+from backend.api.features.subscription_routes_trial_test import (+ TRIAL_RUNNING_DETAIL,+ _post_plan,+ _subscription_list,+)+from backend.data import credit, subscription_checkout+from backend.data.subscription_trial import TrialState++pytest_plugins = ("backend.data.subscription_trial_fixtures",)++client = routes_test.client+_configure_frontend_origin = routes_test._configure_frontend_origin+_stub_lifecycle_emails = routes_test._stub_lifecycle_emails+_stub_pending_subscription_change = routes_test._stub_pending_subscription_change+track_checkout_started = routes_test.track_checkout_started+_stub_subscription_status_lookups = routes_test._stub_subscription_status_lookups+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"+++def test_update_subscription_tier_cancel_pending_trial_card_declined_returns_402(+ client: fastapi.testclient.TestClient,+ trial_conversion: MagicMock,+) -> None:+ trial_conversion.modify.side_effect = stripe.CardError(+ "Your card was declined.", param="card", code="card_declined"+ )++ response = _post_plan(client, "PRO")++ assert response.status_code == 402+ assert "card was declined" in response.json()["detail"].lower()+ trial_conversion.sync.assert_not_awaited()+ trial_conversion.modify_for_tier.assert_not_awaited()+ trial_conversion.checkout.assert_not_awaited()+++ "code,decline_code",+ [+ ("authentication_required", None),+ ("invoice_payment_intent_requires_action", None),+ ("subscription_payment_intent_requires_action", None),+ ("card_declined", "authentication_required"),+ ],+)+def test_update_subscription_tier_cancel_pending_trial_sca_falls_back_to_checkout(+ 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}},+ )++ response = _post_plan(client, "PRO")++ assert response.status_code == 200+ assert response.json()["url"] == CHECKOUT_URL+ 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"+++ "change,detail",+ [+ ({"cancel_at_period_end": False}, TRIAL_RUNNING_DETAIL),+ ({"status": "canceled"}, "This trial has ended. Manage the plan in billing."),+ (+ {"customer": "cus_other"},+ "This trial has ended. Manage the plan in billing.",+ ),+ ],+)+def test_update_subscription_tier_cancel_pending_trial_changed_in_stripe_returns_409(+ client: fastapi.testclient.TestClient,+ trial_conversion: MagicMock,+ change: dict,+ detail: str,+) -> None:+ trial_conversion.retrieve.side_effect = None+ trial_conversion.retrieve.return_value = stripe.Subscription.construct_from(+ {**trial_conversion.live, **change}, "test-key"+ )++ response = _post_plan(client, "PRO")++ assert response.status_code == 409+ assert response.json()["detail"] == detail+ trial_conversion.expire.assert_not_awaited()+ trial_conversion.modify.assert_not_awaited()+ trial_conversion.modify_for_tier.assert_not_awaited()+ trial_conversion.checkout.assert_not_awaited()+++def test_update_subscription_tier_cancel_pending_trial_with_another_live_plan_returns_409(+ client: fastapi.testclient.TestClient,+ trial_conversion: MagicMock,+) -> None:+ """A Max Checkout completed before its webhook ended the trial: 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")++ assert response.status_code == 409+ assert response.json()["detail"] == ANOTHER_PLAN_LIVE_DETAIL+ trial_conversion.modify.assert_not_awaited()+ trial_conversion.sync.assert_not_awaited()+ trial_conversion.modify_for_tier.assert_not_awaited()+ trial_conversion.checkout.assert_not_awaited()+++def test_update_subscription_tier_cancel_pending_trial_repriced_plan_converts_in_place(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+ trial_conversion: MagicMock,+) -> None:+ """The trial's own plan bills the price it accepted, as the plan card and+ the confirm dialog show, even after the plan was re-priced."""++ async def price_id(+ requested: SubscriptionTier, cycle: str = "monthly"+ ) -> str | None:+ if requested == SubscriptionTier.PRO and cycle == "monthly":+ return "price_pro_v2"+ prices = (+ _DEFAULT_TIER_PRICES_YEARLY if cycle == "yearly" else _DEFAULT_TIER_PRICES+ )+ return prices.get(requested)++ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",+ side_effect=price_id,+ )++ response = _post_plan(client, "PRO")++ assert response.status_code == 200+ assert response.json()["url"] == ""+ trial_conversion.modify.assert_awaited_once()+ trial_conversion.sync.assert_awaited_once_with(dict(trial_conversion.converted))+ 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(+ client: fastapi.testclient.TestClient,+ trial_conversion: MagicMock,+ tier: str,+ billing_cycle: str,+) -> None:+ """Another tier or another cycle is a new subscription; the+ stale-subscription cleanup ends the trial once it is paid for."""+ 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()+ 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++[email protected]("tier,converts", [("PRO", True), ("MAX", False)])+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+ every plan request fail until trial_end."""+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",+ new_callable=AsyncMock,+ return_value=MagicMock(subscription_tier=SubscriptionTier.NO_TIER),+ )++ 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_for_tier.assert_not_awaited()+++def test_update_subscription_tier_cancel_pending_trial_card_it_cannot_charge_uses_checkout(+ client: fastapi.testclient.TestClient,+ trial_conversion: MagicMock,+) -> None:+ """Only Checkout can take a new card; the trial is left as it was."""+ trial_conversion.card.return_value = False++ response = _post_plan(client, "PRO")++ assert response.status_code == 200+ assert response.json()["url"] == CHECKOUT_URL+ trial_conversion.modify.assert_not_awaited()+ trial_conversion.checkout.assert_awaited_once()+++def test_update_subscription_tier_cancel_pending_trial_converts_without_a_current_price(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+ trial_conversion: MagicMock,+) -> None:+ """The conversion bills the price the trial accepted, so it needs no+ current LaunchDarkly price for the plan."""+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.get_subscription_price_id",+ new_callable=AsyncMock,+ return_value=None,+ )++ response = _post_plan(client, "PRO")++ 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.pynew file mode 100644index 0000000000..ae21e1b7d4--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_trial_test.py@@ -0,0 +1,228 @@+"""Choosing a plan while a trial is cancel-pending: the same plan converts the+trial's own subscription in place instead of opening a second checkout."""++from contextlib import asynccontextmanager+from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, MagicMock, Mock++import fastapi.testclient+import pytest+import pytest_mock+import stripe+from prisma.enums import SubscriptionTier++from backend.api.features import subscription_routes_test as routes_test+from backend.api.features.subscription_routes_test import (+ TEST_FRONTEND_ORIGIN,+ TEST_USER_ID,+ _patch_payment_flag,+)+from backend.data import subscription_trial_conversion as conversion+from backend.data.subscription_trial import TrialState++pytest_plugins = ("backend.data.subscription_trial_fixtures",)++client = routes_test.client+_configure_frontend_origin = routes_test._configure_frontend_origin+_stub_lifecycle_emails = routes_test._stub_lifecycle_emails+_stub_pending_subscription_change = routes_test._stub_pending_subscription_change+track_checkout_started = routes_test.track_checkout_started+_stub_subscription_status_lookups = routes_test._stub_subscription_status_lookups+++TRIAL_RUNNING_DETAIL = (+ "Your accepted plan starts after your trial. Manage the trial in billing."+)+++def cancel_pending_trial(trial: TrialState) -> TrialState:+ now = datetime.now(UTC)+ return trial.model_copy(+ update={+ "user_id": TEST_USER_ID,+ "subscription_id": "sub_1",+ "status": "trialing",+ "card_verified_at": now - timedelta(days=2),+ "started_at": now - timedelta(days=2),+ "ends_at": now + timedelta(days=5),+ "consumed_at": now - timedelta(days=2),+ "cancel_at_period_end": True,+ }+ )+++def _subscription_list(*subscriptions: dict) -> stripe.ListObject:+ return stripe.ListObject.construct_from(+ {"data": list(subscriptions), "has_more": False}, "test-key"+ )+++def trial_conversion(+ mocker: pytest_mock.MockFixture, cancel_pending_trial: TrialState+) -> MagicMock:+ """A TRIAL-tier user whose trial is cancel-pending, with every Stripe and+ database boundary of the in-place conversion recorded in call order."""+ calls: list[str] = []+ assert cancel_pending_trial.ends_at is not None+ live = {+ "id": "sub_1",+ "customer": cancel_pending_trial.customer_id,+ "status": "trialing",+ "cancel_at_period_end": True,+ "trial_end": int(cancel_pending_trial.ends_at.timestamp()),+ "metadata": {+ "user_id": TEST_USER_ID,+ "trial_enrollment_id": cancel_pending_trial.id,+ },+ }+ converted = stripe.Subscription.construct_from(+ {**live, "status": "active", "cancel_at_period_end": False}, "test-key"+ )++ def recorded(name: str, result: object = None) -> AsyncMock:+ async def effect(*args, **kwargs):+ calls.append(name)+ return result++ return AsyncMock(side_effect=effect)++ @asynccontextmanager+ async def lock(user_id: str):+ calls.append(f"lock:{user_id}")+ try:+ yield+ finally:+ calls.append("unlock")++ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",+ new_callable=AsyncMock,+ return_value=Mock(subscription_tier=SubscriptionTier.TRIAL),+ )+ _patch_payment_flag(mocker)+ mocker.patch.object(+ conversion,+ "get_subscription_trial",+ AsyncMock(return_value=cancel_pending_trial),+ )+ mocker.patch.object(conversion, "subscription_checkout_lock", lock)+ card = mocker.patch.object(+ conversion, "subscription_card_can_be_charged", AsyncMock(return_value=True)+ )+ retrieve = recorded(+ "retrieve", stripe.Subscription.construct_from(live, "test-key")+ )+ mocker.patch.object(stripe.Subscription, "retrieve_async", retrieve)+ return MagicMock(+ calls=calls,+ live=live,+ retrieve=retrieve,+ card=card,+ converted=converted,+ others=mocker.patch.object(+ stripe.Subscription,+ "list_async",+ recorded("others", _subscription_list(live)),+ ),+ modify=mocker.patch.object(+ stripe.Subscription, "modify_async", recorded("modify", converted)+ ),+ expire=mocker.patch.object(+ conversion, "expire_other_subscription_checkouts", recorded("expire")+ ),+ sync=mocker.patch.object(+ conversion, "sync_subscription_from_stripe", recorded("sync")+ ),+ modify_for_tier=mocker.patch(+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ ),+ checkout=mocker.patch(+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",+ new_callable=AsyncMock,+ return_value="https://checkout.stripe.com/pay/cs_test_max",+ ),+ )+++def _post_plan(+ client: fastapi.testclient.TestClient, tier: str, billing_cycle: str = "monthly"+):+ return client.post(+ "/credits/subscription",+ json={+ "tier": tier,+ "billing_cycle": billing_cycle,+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ "surface": "billing",+ },+ )+++ "change",+ [+ None,+ {"cancel_at_period_end": False},+ {"converted_at": datetime.now(UTC)},+ {"ends_at": datetime.now(UTC) - timedelta(minutes=1)},+ ],+)+def test_update_subscription_tier_trial_still_waits_for_the_trial_to_end(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+ trial_conversion: MagicMock,+ cancel_pending_trial: TrialState,+ change: dict | None,+) -> None:+ """A TRIAL-tier user whose trial is not cancel-pending keeps today's 409."""+ mocker.patch.object(+ conversion,+ "get_subscription_trial",+ AsyncMock(+ return_value=change and cancel_pending_trial.model_copy(update=change)+ ),+ )++ response = _post_plan(client, "PRO")++ assert response.status_code == 409+ assert response.json()["detail"] == TRIAL_RUNNING_DETAIL+ assert trial_conversion.calls == []+ trial_conversion.modify_for_tier.assert_not_awaited()+ trial_conversion.checkout.assert_not_awaited()+++def test_update_subscription_tier_cancel_pending_trial_converts_its_own_plan(+ client: fastapi.testclient.TestClient,+ trial_conversion: MagicMock,+ track_checkout_started: AsyncMock,+) -> None:+ response = _post_plan(client, "PRO")++ assert response.status_code == 200+ assert response.json()["url"] == ""+ assert trial_conversion.calls == [+ f"lock:{TEST_USER_ID}",+ "retrieve",+ "expire",+ "others",+ "modify",+ "sync",+ "unlock",+ ]+ trial_conversion.retrieve.assert_awaited_once_with("sub_1")+ trial_conversion.expire.assert_awaited_once_with("cus_1")+ trial_conversion.modify.assert_awaited_once_with(+ "sub_1",+ cancel_at_period_end=False,+ trial_end="now",+ 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_not_awaited()+ track_checkout_started.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_models.py b/autogpt_platform/backend/backend/api/features/subscription_trial_models.pynew file mode 100644index 0000000000..31bfca36b4--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_models.py@@ -0,0 +1,44 @@+from datetime import datetime+from typing import Literal++from pydantic import BaseModel, Field++from backend.data.subscription_trial_config import AcceptedTrialOffer+from backend.data.subscription_trial_rejection import TrialRejectionReason+++class TrialOfferResponse(BaseModel):+ token: str+ version: str+ duration_days: int+ tier: Literal["BASIC", "PRO", "MAX", "BUSINESS"]+ billing_cycle: Literal["monthly", "yearly"]+ unit_amount: int+ currency: str+ onboarding_credit_amount: int++ @classmethod+ def from_offer(cls, offer: AcceptedTrialOffer) -> "TrialOfferResponse":+ return cls(**offer.model_dump(), token=offer.token)+++class TrialStatusResponse(BaseModel):+ eligible: bool = False+ offer: TrialOfferResponse | None = None+ status: str | None = None+ rejection_reason: TrialRejectionReason | None = None+ ends_at: datetime | None = None+ cancel_at_period_end: bool = False+ allowance_used_percent: float | None = None+ active: bool = False+ converted: bool = False+ onboarding_credits_previously_received: bool = False+++class TrialCheckoutRequest(BaseModel):+ offer_token: str = Field(pattern=r"^[a-f0-9]{64}$")+ return_to: Literal["onboarding", "billing"] = "billing"+++class TrialCheckoutResponse(BaseModel):+ url: strdiff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.pyindex fe37c3fc9a..ef9f88b852 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py@@ -1,11 +1,9 @@import logging-from datetime import datetime-from typing import Annotated, Literal+from typing import Annotated, Awaitableimport stripefrom autogpt_libs.auth import get_user_idfrom fastapi import APIRouter, Depends, Header, HTTPException, Security-from pydantic import BaseModel, Fieldfrom backend.api.features.billing.client_country import ( # noqa: F401 -- re-exportedCLIENT_COUNTRY_SCOPE,@@ -15,13 +13,24 @@ from backend.api.features.billing.client_country import ( # noqa: F401 -- re-exfrom backend.api.features.billing.credits_rate_limit import (enforce_subscription_status_rate_limit,)+from backend.api.features.subscription_trial_models import (+ TrialCheckoutRequest,+ TrialCheckoutResponse,+ TrialOfferResponse,+ TrialStatusResponse,+)from backend.data.checkout_audience import schedule_checkout_opened-from backend.data.credit import _datafast_metadata, sync_subscription_from_stripe+from backend.data.credit import _datafast_metadatafrom backend.data.stripe_client import stripe_callfrom backend.data.subscription_trial import (get_subscription_trial,has_received_onboarding_credit,)+from backend.data.subscription_trial_cancel import (+ TrialChangeRefused,+ resume_trial_subscription,+ schedule_trial_cancellation,+)from backend.data.subscription_trial_capacity import trial_seat_availablefrom backend.data.subscription_trial_checkout import (TrialUnavailable,@@ -29,8 +38,7 @@ from backend.data.subscription_trial_checkout import (create_trial_checkout,resolve_trial_price,)-from backend.data.subscription_trial_config import AcceptedTrialOffer, get_trial_offer-from backend.data.subscription_trial_rejection import TrialRejectionReason+from backend.data.subscription_trial_config import get_trial_offerfrom backend.data.user import get_user_by_idfrom backend.util.product_analytics import track_checkout_startedfrom backend.util.settings import Settings@@ -45,43 +53,6 @@ router = APIRouter(CurrentUser = Annotated[str, Security(get_user_id)]-class TrialOfferResponse(BaseModel):- token: str- version: str- duration_days: int- tier: Literal["BASIC", "PRO", "MAX", "BUSINESS"]- billing_cycle: Literal["monthly", "yearly"]- unit_amount: int- currency: str- onboarding_credit_amount: int-- @classmethod- def from_offer(cls, offer: AcceptedTrialOffer) -> "TrialOfferResponse":- return cls(**offer.model_dump(), token=offer.token)---class TrialStatusResponse(BaseModel):- eligible: bool = False- offer: TrialOfferResponse | None = None- status: str | None = None- rejection_reason: TrialRejectionReason | None = None- ends_at: datetime | None = None- cancel_at_period_end: bool = False- allowance_used_percent: float | None = None- active: bool = False- converted: bool = False- onboarding_credits_previously_received: bool = False---class TrialCheckoutRequest(BaseModel):- offer_token: str = Field(pattern=r"^[a-f0-9]{64}$")- return_to: Literal["onboarding", "billing"] = "billing"---class TrialCheckoutResponse(BaseModel):- url: str--@router.get("")async def get_trial_status(user_id: CurrentUser, country: ClientCountry = None@@ -215,30 +186,41 @@ async def cancel_trial(user_id: CurrentUser) -> TrialStatusResponse:or trial.converted_at is not None):raise HTTPException(409, "No trial subscription is available to cancel")- try:- subscription = await stripe_call(- stripe.Subscription.retrieve_async, trial.subscription_id- )- if subscription.customer != trial.customer_id or subscription.status not in (- "trialing",- "canceled",- ):- raise HTTPException(- 409, "This trial has ended. Manage the plan in billing."- )- if subscription.status == "trialing":- subscription = await stripe_call(- stripe.Subscription.cancel_async,- trial.subscription_id,- invoice_now=False,- prorate=False,+ await _apply_trial_change(+ schedule_trial_cancellation(trial), "Unable to cancel your trial. Please retry."+ )+ return await get_trial_status(user_id)+++ "/resume",+ responses={+ 409: {+ "description": (+ "No live cancel-pending trial to resume, another plan is active,"+ " or the trial is already being updated")- except stripe.StripeError as exc:- raise HTTPException(502, "Unable to cancel your trial. Please retry.") from exc- await sync_subscription_from_stripe(dict(subscription))+ },+ 502: {"description": "Stripe update temporarily unavailable"},+ },+)+async def resume_trial(user_id: CurrentUser) -> TrialStatusResponse:+ trial = await get_subscription_trial(user_id)+ await _apply_trial_change(+ resume_trial_subscription(trial), "Unable to resume your trial. Please retry."+ )return await get_trial_status(user_id)+async def _apply_trial_change(change: Awaitable[None], retry: str) -> None:+ try:+ await change+ except TrialChangeRefused as exc:+ raise HTTPException(409, str(exc)) from exc+ except stripe.StripeError as exc:+ raise HTTPException(502, retry) from exc++@router.post("/confirm",responses={diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_cancel_test.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_cancel_test.pynew file mode 100644index 0000000000..943be82e82--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_cancel_test.py@@ -0,0 +1,235 @@+"""Canceling a trial schedules its end: access holds until the trial would have+ended, and the cancellation can be resumed."""++from contextlib import asynccontextmanager+from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from httpx import ASGITransport, AsyncClient++from backend.api.features import subscription_trial_routes as routes+from backend.api.features import subscription_trial_routes_test as routes_test+from backend.data import subscription_trial_cancel as trial_cancel+from backend.data.subscription_checkout import SubscriptionCheckoutUnavailable+from backend.data.subscription_trial import TrialState++ENDED = "This trial has ended. Manage the plan in billing."++billing_return_origin = routes_test.billing_return_origin+track_checkout_started = routes_test.track_checkout_started+trial = routes_test.trial+++def _started(trial: TrialState, **changes) -> TrialState:+ now = datetime.now(UTC)+ return trial.model_copy(+ update={+ "subscription_id": "sub_1",+ "status": "trialing",+ "consumed_at": now,+ "card_verified_at": now,+ "started_at": now,+ "ends_at": now + timedelta(days=5),+ **changes,+ }+ )+++def _live(trial: TrialState, **changes):+ return routes.stripe.Subscription.construct_from(+ {+ "id": "sub_1",+ "customer": trial.customer_id,+ "status": "trialing",+ "cancel_at_period_end": False,+ "trial_end": int((datetime.now(UTC) + timedelta(days=5)).timestamp()),+ "metadata": {"trial_enrollment_id": trial.id, "user_id": trial.user_id},+ **changes,+ },+ "test-key",+ )+++def live_stripe():+ """Stripe (a customer with no other subscription), the syncs, the checkout+ lock and the status lookups a cancel or resume reaches.+ ``lock.side_effect`` makes the checkout lock busy."""+ calls = MagicMock()+ no_others = routes.stripe.ListObject.construct_from(+ {"data": [], "has_more": False}, "test-key"+ )++ @asynccontextmanager+ async def lock(user_id: str):+ calls.lock(user_id)+ yield++ with (+ patch.object(trial_cancel, "subscription_checkout_lock", lock),+ patch.object(routes.stripe.Subscription, "retrieve_async", AsyncMock()) as get,+ patch.object(+ routes.stripe.Subscription,+ "list_async",+ AsyncMock(return_value=no_others),+ ) as others,+ patch.object(routes.stripe.Subscription, "modify_async", AsyncMock()) as modify,+ patch.object(routes.stripe.Subscription, "cancel_async", AsyncMock()) as end,+ patch.object(+ trial_cancel, "expire_other_subscription_checkouts", AsyncMock()+ ) as expire,+ patch.object(+ trial_cancel, "sync_subscription_from_stripe", AsyncMock()+ ) as sync,+ patch.object(+ routes, "has_received_onboarding_credit", AsyncMock(return_value=False)+ ),+ patch.object(+ trial_cancel,+ "subscription_card_can_be_charged",+ AsyncMock(return_value=True),+ ),+ ):+ for name, mock in (+ ("retrieve", get),+ ("others", others),+ ("modify", modify),+ ("end_now", end),+ ("expire", expire),+ ("sync", sync),+ ):+ calls.attach_mock(mock, name)+ yield calls+++async def test_cancel_keeps_access_until_trial_end(trial, live_stripe):+ started = _started(trial)+ pending = _live(started, cancel_at_period_end=True)+ live_stripe.retrieve.return_value = _live(started)+ live_stripe.modify.return_value = pending+ after = started.model_copy(update={"cancel_at_period_end": True})+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(side_effect=[started, after])+ ):+ status = await routes.cancel_trial(started.user_id)+ live_stripe.lock.assert_called_once_with(started.user_id)+ live_stripe.modify.assert_awaited_once_with("sub_1", cancel_at_period_end=True)+ live_stripe.end_now.assert_not_awaited()+ live_stripe.sync.assert_awaited_once_with(dict(pending))+ assert status.active and status.status == "trialing"+ assert status.cancel_at_period_end++[email protected]("status", ["canceled", "active"], ids=["ended", "paid"])+async def test_cancel_after_the_trial_ended_reconciles_then_conflicts(+ trial, live_stripe, status+):+ started = _started(trial)+ ended = _live(started, status=status)+ live_stripe.retrieve.return_value = ended+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=started)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.cancel_trial(started.user_id)+ assert (error.value.status_code, error.value.detail) == (409, ENDED)+ live_stripe.sync.assert_awaited_once_with(dict(ended))+ live_stripe.modify.assert_not_awaited()+ live_stripe.end_now.assert_not_awaited()+++ "change",+ [+ {"customer": "cus_other"},+ {"metadata": {"trial_enrollment_id": "trial-x", "user_id": "user-1"}},+ ],+ ids=["other-customer", "other-enrollment"],+)+async def test_cancel_refuses_a_subscription_the_trial_does_not_own(+ trial, live_stripe, change+):+ started = _started(trial)+ live_stripe.retrieve.return_value = _live(started, **change)+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=started)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.cancel_trial(started.user_id)+ assert (error.value.status_code, error.value.detail) == (409, ENDED)+ live_stripe.modify.assert_not_awaited()+ live_stripe.end_now.assert_not_awaited()+ live_stripe.sync.assert_not_awaited()+++async def test_cancel_stripe_failure_is_retryable_without_a_sync(trial, live_stripe):+ started = _started(trial)+ live_stripe.retrieve.return_value = _live(started)+ live_stripe.modify.side_effect = routes.stripe.APIConnectionError("unreachable")+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=started)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.cancel_trial(started.user_id)+ assert error.value.status_code == 502+ assert error.value.detail == "Unable to cancel your trial. Please retry."+ live_stripe.sync.assert_not_awaited()+++async def test_cancel_while_the_trial_is_being_updated_is_a_retryable_conflict(+ trial, live_stripe+):+ """Subscribe now converting the trial in another tab holds the lock; a+ cancel landing after it would schedule the new paid plan to end."""+ started = _started(trial)+ live_stripe.lock.side_effect = SubscriptionCheckoutUnavailable(+ "Another checkout is already starting. Please retry."+ )+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=started)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.cancel_trial(started.user_id)+ assert (error.value.status_code, error.value.detail) == (+ 409,+ "Your trial is already being updated. Please retry.",+ )+ live_stripe.retrieve.assert_not_awaited()+ live_stripe.modify.assert_not_awaited()+ live_stripe.sync.assert_not_awaited()+++async def test_cancel_of_a_converted_trial_is_conflict(trial, live_stripe):+ converted = _started(trial, converted_at=datetime.now(UTC))+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=converted)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.cancel_trial(converted.user_id)+ assert error.value.status_code == 409+ live_stripe.retrieve.assert_not_awaited()+++async def test_cancel_route_schedules_the_end(trial, live_stripe):+ started = _started(trial)+ live_stripe.retrieve.return_value = _live(started)+ live_stripe.modify.return_value = _live(started, cancel_at_period_end=True)+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=started)+ ):+ async with AsyncClient(+ transport=ASGITransport(app=routes_test._app(started)),+ base_url="https://example.com",+ ) as client:+ response = await client.post("/credits/trial/cancel")+ assert response.status_code == 200+ live_stripe.modify.assert_awaited_once_with("sub_1", cancel_at_period_end=True)+ live_stripe.end_now.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_resume_test.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_resume_test.pynew file mode 100644index 0000000000..612039368d--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_resume_test.py@@ -0,0 +1,128 @@+"""Resuming a scheduled trial cancellation."""++from datetime import UTC, datetime+from unittest.mock import AsyncMock, call, patch++import pytest++from backend.api.features import subscription_trial_routes as routes+from backend.api.features import subscription_trial_routes_cancel_test as cancel_test+from backend.api.features import subscription_trial_routes_test as routes_test+from backend.api.features.subscription_trial_routes_cancel_test import (+ ENDED,+ _live,+ _started,+)+from backend.data.subscription_checkout import SubscriptionCheckoutUnavailable++billing_return_origin = routes_test.billing_return_origin+track_checkout_started = routes_test.track_checkout_started+trial = routes_test.trial+live_stripe = cancel_test.live_stripe+++async def test_resume_takes_back_a_scheduled_cancellation(trial, live_stripe):+ pending = _started(trial, cancel_at_period_end=True)+ resumed = _live(pending)+ live_stripe.retrieve.return_value = _live(pending, cancel_at_period_end=True)+ live_stripe.modify.return_value = resumed+ after = pending.model_copy(update={"cancel_at_period_end": False})+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(side_effect=[pending, after])+ ):+ status = await routes.resume_trial(pending.user_id)+ live_stripe.expire.assert_awaited_once_with("cus_1")+ live_stripe.modify.assert_awaited_once_with("sub_1", cancel_at_period_end=False)+ live_stripe.sync.assert_awaited_once_with(dict(resumed))+ assert status.active and not status.cancel_at_period_end+++ "changes,live,detail",+ [+ ({}, {}, "Nothing to resume."),+ ({"converted_at": datetime.now(UTC)}, None, "Nothing to resume."),+ ({}, {"status": "canceled", "cancel_at_period_end": True}, ENDED),+ ],+ ids=["not-pending", "converted", "ended"],+)+async def test_resume_without_a_live_scheduled_cancellation_is_conflict(+ trial, live_stripe, changes, live, detail+):+ current = _started(trial, cancel_at_period_end=True, **changes)+ live_stripe.retrieve.return_value = None if live is None else _live(current, **live)+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=current)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.resume_trial(current.user_id)+ assert (error.value.status_code, error.value.detail) == (409, detail)+ live_stripe.modify.assert_not_awaited()+ live_stripe.expire.assert_not_awaited()+ synced = [] if live is None else [call(dict(live_stripe.retrieve.return_value))]+ assert live_stripe.sync.await_args_list == synced+++async def test_resume_while_a_checkout_is_starting_is_a_retryable_conflict(+ trial, live_stripe+):+ pending = _started(trial, cancel_at_period_end=True)+ live_stripe.lock.side_effect = SubscriptionCheckoutUnavailable(+ "Another checkout is already starting. Please retry."+ )+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=pending)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.resume_trial(pending.user_id)+ assert (error.value.status_code, error.value.detail) == (+ 409,+ "Your trial is already being updated. Please retry.",+ )+ live_stripe.retrieve.assert_not_awaited()+ live_stripe.expire.assert_not_awaited()+ live_stripe.modify.assert_not_awaited()+++async def test_resume_with_another_plan_live_is_conflict_untouched(trial, live_stripe):+ """A plan bought while the trial was cancel-pending must not be joined by+ the trial converting at its end."""+ pending = _started(trial, cancel_at_period_end=True)+ live_stripe.retrieve.return_value = _live(pending, cancel_at_period_end=True)+ live_stripe.others.return_value = routes.stripe.ListObject.construct_from(+ {+ "data": [{"id": "sub_max", "object": "subscription", "status": "active"}],+ "has_more": False,+ },+ "test-key",+ )+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=pending)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.resume_trial(pending.user_id)+ assert (error.value.status_code, error.value.detail) == (+ 409,+ "Another plan is already active. Manage it in billing.",+ )+ live_stripe.modify.assert_not_awaited()+ live_stripe.sync.assert_not_awaited()+++async def test_resume_stripe_failure_is_retryable_without_a_sync(trial, live_stripe):+ pending = _started(trial, cancel_at_period_end=True)+ live_stripe.retrieve.return_value = _live(pending, cancel_at_period_end=True)+ live_stripe.modify.side_effect = routes.stripe.APIConnectionError("unreachable")+ with patch.object(+ routes, "get_subscription_trial", AsyncMock(return_value=pending)+ ):+ with pytest.raises(routes.HTTPException) as error:+ await routes.resume_trial(pending.user_id)+ assert error.value.status_code == 502+ assert error.value.detail == "Unable to resume your trial. Please retry."+ live_stripe.sync.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.pyindex 8168929eb8..c2400c9998 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py@@ -1,5 +1,5 @@from datetime import UTC, datetime, timedelta-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, patchimport jwtimport pytest@@ -223,94 +223,6 @@ async def test_unavailable_offer_is_conflict_not_success(trial):assert error.value.status_code == 409-async def test_cancellation_ends_trial_immediately(trial):- trial = trial.model_copy(- update={"subscription_id": "sub_1", "consumed_at": datetime.now(UTC)}- )- canceled = {"id": "sub_1", "customer": trial.customer_id, "status": "canceled"}- with (- patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),- patch.object(- routes.stripe.Subscription,- "retrieve_async",- AsyncMock(- return_value=MagicMock(customer=trial.customer_id, status="trialing")- ),- ),- patch.object(- routes.stripe.Subscription, "cancel_async", AsyncMock(return_value=canceled)- ) as cancel,- patch.object(- routes.stripe.Subscription, "modify_async", AsyncMock(return_value=canceled)- ) as modify,- patch.object(routes, "sync_subscription_from_stripe", AsyncMock()) as sync,- patch.object(- routes,- "get_trial_status",- AsyncMock(return_value=routes.TrialStatusResponse(status="canceled")),- ),- ):- result = await routes.cancel_trial(trial.user_id)- cancel.assert_awaited_once_with("sub_1", invoice_now=False, prorate=False)- modify.assert_not_awaited()- sync.assert_awaited_once_with(canceled)- assert not result.active---async def test_cancellation_retry_reconciles_an_already_canceled_trial(trial):- trial = trial.model_copy(- update={"subscription_id": "sub_1", "consumed_at": datetime.now(UTC)}- )- canceled = routes.stripe.Subscription.construct_from(- {"id": "sub_1", "customer": trial.customer_id, "status": "canceled"}, "test-key"- )- with (- patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),- patch.object(- routes.stripe.Subscription,- "retrieve_async",- AsyncMock(return_value=canceled),- ),- patch.object(routes.stripe.Subscription, "cancel_async", AsyncMock()) as cancel,- patch.object(routes, "sync_subscription_from_stripe", AsyncMock()) as sync,- patch.object(- routes,- "get_trial_status",- AsyncMock(return_value=routes.TrialStatusResponse(status="canceled")),- ),- ):- assert not (await routes.cancel_trial(trial.user_id)).active- cancel.assert_not_awaited()- sync.assert_awaited_once_with(dict(canceled))--- "customer,status", [("cus_other", "trialing"), ("cus_1", "active")]-)-async def test_cancellation_cannot_cancel_another_customer_or_paid_plan(- trial, customer, status-):- trial = trial.model_copy(- update={"subscription_id": "sub_1", "consumed_at": datetime.now(UTC)}- )- with (- patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),- patch.object(- routes.stripe.Subscription,- "retrieve_async",- AsyncMock(return_value=MagicMock(customer=customer, status=status)),- ),- patch.object(routes.stripe.Subscription, "cancel_async", AsyncMock()) as cancel,- ):- with pytest.raises(routes.HTTPException) as error:- await routes.cancel_trial(trial.user_id)- assert error.value.status_code == 409- cancel.assert_not_awaited()--@pytest.mark.asyncioasync def test_full_trial_hides_a_pending_enrollments_offer(trial):"""No seat, no card screen: the cap is enforced before anyone pays."""diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_schema_test.py b/autogpt_platform/backend/backend/api/features/subscription_trial_schema_test.pyindex 8930ac0077..0b48b1b93c 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_schema_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_schema_test.py@@ -4,7 +4,7 @@ from fastapi import FastAPIfrom backend.api.features.subscription_trial_routes import router[email protected]("path", ["/cancel", "/confirm"])[email protected]("path", ["/cancel", "/resume", "/confirm"])def test_trial_mutation_errors_are_documented(path):app = FastAPI()app.include_router(router)diff --git a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.pyindex 0d48cd2427..8c094a3937 100644--- a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py@@ -370,6 +370,7 @@ TRIAL_CREDITS_ROUTES = {"cancel_trial","confirm_trial","get_trial_status",+ "resume_trial","start_trial_checkout",}# Routes that never resolve the org-pooled credit model at all. The reason isdiff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex 071be626d9..2a7b1812e9 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -1844,6 +1844,12 @@ async def _get_active_subscription_cached(return await _get_active_subscription(customer_id)+def invalidate_active_subscription_cache(customer_id: str) -> None:+ """Drop the cached lookup after changing the subscription in Stripe, so the+ status returned right after shows the new period instead of the old one."""+ _get_active_subscription_cached.cache_delete(customer_id)++async def get_user_billing_cycle(user_id: str) -> BillingCycle | None:"""Return the billing cycle ("monthly"/"yearly") of the user's active sub.@@ -2387,6 +2393,11 @@ async def get_pending_subscription_change(sub = await _get_active_subscription(user.stripe_customer_id)if sub is None:return None+ if sub.get("status") == "trialing" and (sub.get("metadata") or {}).get(+ "trial_enrollment_id"+ ):+ # A cancel-pending trial is not a paid plan with a downgrade queued.+ return Noneperiod_end = sub.current_period_endif not isinstance(period_end, int):return None@@ -3186,6 +3197,18 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:sub_id = _invoice_subscription_id(invoice)invoice_id: str = invoice.get("id", "")+ 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.+ logger.info(+ "handle_subscription_payment_failure: first payment of new sub %s"+ " failed for user %s; leaving it to Checkout",+ sub_id,+ user.id,+ )+ return+if amount_due <= 0:logger.info("handle_subscription_payment_failure: amount_due=%d for user %s;"diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.pyindex b4cfb564ee..1a5386c862 100644--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py@@ -1827,6 +1827,42 @@ async def test_handle_subscription_payment_failure_balance_covers_pays_invoice()mock_pay.assert_called_once_with("in_abc123", paid_out_of_band=True)+async def test_handle_subscription_payment_failure_ignores_a_new_plans_first_payment():+ """A card declined in Checkout leaves the new plan incomplete for the+ customer to retry. Treating it as a lapsed plan would cancel every live+ subscription, including a cancel-pending trial that still has access."""+ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.TRIAL)+ invoice = {+ "id": "in_first",+ "customer": "cus_123",+ "subscription": "sub_new_max",+ "amount_due": 32000,+ "billing_reason": "subscription_create",+ }++ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.data.credit.UserCredit._add_transaction", new_callable=AsyncMock+ ) as mock_add_tx,+ patch(+ "backend.data.credit._cancel_customer_subscriptions",+ new_callable=AsyncMock,+ ) as mock_cancel,+ patch(+ "backend.data.credit.set_subscription_tier", new_callable=AsyncMock+ ) as mock_set,+ ):+ await handle_subscription_payment_failure(invoice)+ mock_add_tx.assert_not_awaited()+ mock_cancel.assert_not_awaited()+ mock_set.assert_not_awaited()++@pytest.mark.asyncioasync def test_handle_subscription_payment_failure_invoice_pay_error_does_not_raise():"""Failure to mark the invoice as paid is logged but does not propagate."""diff --git a/autogpt_platform/backend/backend/data/credit_trial_subscription_test.py b/autogpt_platform/backend/backend/data/credit_trial_subscription_test.pynew file mode 100644index 0000000000..bb8b92d38f--- /dev/null+++ b/autogpt_platform/backend/backend/data/credit_trial_subscription_test.py@@ -0,0 +1,195 @@+"""Stripe subscription sync and pending-change lookups for a trial whose+cancellation is scheduled for the end of the trial."""++import time+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+import stripe+from prisma.enums import SubscriptionTier++from backend.data import credit_subscription_test+from backend.data.credit import (+ _get_active_subscription_cached,+ get_pending_subscription_change,+ invalidate_active_subscription_cache,+ sync_subscription_from_stripe,+)+from backend.data.credit_subscription_test import _clear_cache, _make_user++_clear_active_subscription_cache = (+ credit_subscription_test._clear_active_subscription_cache+)+++async def test_new_plan_ends_cancel_pending_trial_without_invoice():+ """A plan bought while the trial is cancel-pending ends the trial at once,+ with no invoice or proration, once the new subscription is active."""+ metadata = {"user_id": "user-1"}+ max_sub = {+ "id": "sub_max",+ "customer": "cus_123",+ "status": "active",+ "items": {"data": [{"price": {"id": "price_max_monthly"}}]},+ "metadata": metadata,+ }+ trial_sub = {+ "id": "sub_trial",+ "customer": "cus_123",+ "status": "trialing",+ "cancel_at_period_end": True,+ "metadata": {**metadata, "trial_enrollment_id": "trial-1"},+ }+ ended_trial = {**trial_sub, "status": "canceled"}+ events: list[str] = []++ async def list_subscriptions(*, customer: str, status: str, limit: int):+ return MagicMock(+ data=[max_sub] if status == "active" else [trial_sub], has_more=False+ )++ async def cancel(sub_id: str, **params):+ events.append(f"cancel:{sub_id}")+ return ended_trial++ async def set_tier(user_id: str, tier: SubscriptionTier, **kwargs):+ events.append(f"tier:{tier.value}")++ async def price_id(tier: SubscriptionTier, billing_cycle: str = "monthly"):+ return {SubscriptionTier.MAX: "price_max_monthly"}.get(tier)++ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(+ find_first=AsyncMock(+ return_value=_make_user(tier=SubscriptionTier.TRIAL)+ )+ ),+ ),+ patch("backend.data.credit.get_subscription_price_id", side_effect=price_id),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ new_callable=AsyncMock,+ side_effect=list_subscriptions,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.cancel_async",+ new_callable=AsyncMock,+ side_effect=cancel,+ ) as mock_cancel,+ patch(+ "backend.data.credit.reconcile_trial_subscription",+ new_callable=AsyncMock,+ return_value=(ended_trial, None),+ ) as reconcile,+ patch(+ "backend.data.credit.set_subscription_tier",+ new_callable=AsyncMock,+ side_effect=set_tier,+ ) as mock_set,+ ):+ await sync_subscription_from_stripe(max_sub)++ mock_cancel.assert_awaited_once_with("sub_trial", invoice_now=False, prorate=False)+ reconcile.assert_awaited_once_with("user-1", "sub_trial")+ mock_set.assert_awaited_once_with(+ "user-1", SubscriptionTier.MAX, track_lifecycle=False+ )+ assert events == ["cancel:sub_trial", "tier:MAX"]+++async def _pending_change_for(subscription: dict):+ _clear_cache(get_pending_subscription_change)+ mock_list = MagicMock()+ mock_list.data = [stripe.Subscription.construct_from(subscription, "k")]+ with (+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=MagicMock(stripe_customer_id="cus_abc"),+ ),+ patch(+ "backend.data.credit.get_subscription_price_id",+ new_callable=AsyncMock,+ return_value="price_pro",+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ new_callable=AsyncMock,+ return_value=mock_list,+ ),+ patch(+ "backend.data.credit.stripe.SubscriptionSchedule.retrieve_async",+ new_callable=AsyncMock,+ ) as retrieve_schedule,+ ):+ result = await get_pending_subscription_change("user-1")+ retrieve_schedule.assert_not_awaited()+ return result+++async def test_get_pending_subscription_change_ignores_cancel_pending_trial():+ """A trial scheduled to end has no paid plan to downgrade from."""+ result = await _pending_change_for(+ {+ "id": "sub_trial",+ "status": "trialing",+ "current_period_end": int(time.time()) + 5 * 24 * 3600,+ "cancel_at_period_end": True,+ "schedule": None,+ "metadata": {"trial_enrollment_id": "trial-1", "user_id": "user-1"},+ }+ )++ assert result is None+++ "metadata", [{}, {"trial_enrollment_id": "trial-1", "user_id": "user-1"}]+)+async def test_get_pending_subscription_change_reports_paid_cancel(metadata):+ """A paid subscription, including a converted trial, still reports its+ scheduled cancellation."""+ period_end = int(time.time()) + 10 * 24 * 3600+ result = await _pending_change_for(+ {+ "id": "sub_pro",+ "status": "active",+ "current_period_end": period_end,+ "cancel_at_period_end": True,+ "schedule": None,+ "metadata": metadata,+ }+ )++ assert result is not None+ pending_tier, effective_at, pending_cycle = result+ assert pending_tier == SubscriptionTier.NO_TIER+ assert int(effective_at.timestamp()) == period_end+ assert pending_cycle is None+++async def test_invalidating_the_subscription_lookup_refetches_only_that_customer():+ """A subscription changed in place is read fresh on the next status call;+ other customers keep their cached lookup."""+ trialing = {"id": "sub_trial", "status": "trialing"}+ converted = {"id": "sub_trial", "status": "active"}+ other = {"id": "sub_other", "status": "active"}+ with patch(+ "backend.data.credit._get_active_subscription",+ new_callable=AsyncMock,+ side_effect=[trialing, other, converted],+ ) as lookup:+ assert await _get_active_subscription_cached("cus_trial") is trialing+ assert await _get_active_subscription_cached("cus_other") is other++ invalidate_active_subscription_cache("cus_trial")++ assert await _get_active_subscription_cached("cus_trial") is converted+ assert await _get_active_subscription_cached("cus_other") is other+ assert lookup.await_count == 3diff --git a/autogpt_platform/backend/backend/data/posthog_lifecycle_trial_cancel_test.py b/autogpt_platform/backend/backend/data/posthog_lifecycle_trial_cancel_test.pynew file mode 100644index 0000000000..022f26b390--- /dev/null+++ b/autogpt_platform/backend/backend/data/posthog_lifecycle_trial_cancel_test.py@@ -0,0 +1,104 @@+"""The lifecycle status of a trial canceled at period end: trial canceled+while it runs out, in trial again once resumed, and subscribed as soon as+another plan is bought or the trial converts early."""++from datetime import timedelta++import pytest+from prisma.enums import SubscriptionTier++from backend.data.posthog_lifecycle import LifecycleSnapshot, StripeSubscriptionFacts+from backend.data.posthog_lifecycle_test import (+ NOW,+ SIGNUP,+ TRIAL_START,+ snapshot,+ sub,+ trial,+ user,+)++TRIAL_END = NOW + timedelta(days=5)+++def _trial_sub(status: str = "trialing", **extra) -> StripeSubscriptionFacts:+ extra.setdefault("trial_end", TRIAL_END)+ return sub("sub_trial", status, start=TRIAL_START, enrollment="trial-1", **extra)+++def test_cancel_pending_trial_is_trial_canceled_without_subscription_dates():+ pending = _trial_sub(cancel_at_period_end=True, canceled_at=NOW)+ result = snapshot(+ t=trial(cancel_at_period_end=True, ends_at=TRIAL_END), subs=[pending]+ )+ assert result == LifecycleSnapshot(+ subscription_status="trial_canceled",+ signup_at=SIGNUP,+ trial_started_at=TRIAL_START,+ )+++def test_cancel_then_resume_goes_back_to_in_trial():+ steps = [(True, "trial_canceled"), (False, "in_trial"), (True, "trial_canceled")]+ for pending, expected in steps:+ result = snapshot(+ t=trial(cancel_at_period_end=pending, ends_at=TRIAL_END),+ subs=[_trial_sub(cancel_at_period_end=pending)],+ )+ assert result.subscription_status == expected++[email protected]("deleted", [False, True], ids=["awaiting-delete", "deleted"])+def test_cancel_pending_trial_that_reached_its_end_is_trial_canceled(deleted: bool):+ """Stripe ends it at trial_end with no invoice; it never became a paid+ subscription, so it is not subscription_ended."""+ end = NOW - timedelta(minutes=5)+ status = "canceled" if deleted else "trialing"+ ended = _trial_sub(+ status,+ trial_end=end,+ cancel_at_period_end=True,+ canceled_at=NOW - timedelta(days=2),+ ended_at=end if deleted else None,+ )+ t = trial(status=status, cancel_at_period_end=True, ends_at=end)+ assert snapshot(t=t, subs=[ended]) == LifecycleSnapshot(+ subscription_status="trial_canceled",+ signup_at=SIGNUP,+ trial_started_at=TRIAL_START,+ )+++def test_buying_another_plan_while_cancel_pending_is_subscribed():+ """The new plan is live before the trial subscription is canceled, and+ stays the answer after."""+ max_sub = sub("sub_max", start=NOW)+ before = (+ trial(cancel_at_period_end=True, ends_at=TRIAL_END),+ _trial_sub(cancel_at_period_end=True),+ )+ after = (+ trial(status="canceled", cancel_at_period_end=True, ends_at=NOW),+ _trial_sub("canceled", canceled_at=NOW, ended_at=NOW),+ )+ for t, trial_sub in (before, after):+ result = snapshot(u=user(SubscriptionTier.MAX), t=t, subs=[trial_sub, max_sub])+ assert result == LifecycleSnapshot(+ subscription_status="subscribed",+ signup_at=SIGNUP,+ trial_started_at=TRIAL_START,+ subscription_started_at=max_sub.started_at,+ )+++def test_converting_early_while_cancel_pending_is_subscribed_from_conversion():+ """Subscribe now ends the trial early and clears the cancellation in the+ same update, so it reads as a trial awaiting its charge, then subscribed."""+ early_end = NOW - timedelta(seconds=1)+ live = _trial_sub("active", trial_end=early_end)+ charging = trial(status="active", ends_at=early_end)+ assert snapshot(t=charging, subs=[live]).subscription_status == "in_trial"+ converted = trial(status="active", ends_at=early_end, converted_at=NOW)+ result = snapshot(u=user(SubscriptionTier.PRO), t=converted, subs=[live])+ assert result.subscription_status == "subscribed"+ assert result.subscription_started_at == NOWdiff --git a/autogpt_platform/backend/backend/data/subscription_checkout.py b/autogpt_platform/backend/backend/data/subscription_checkout.pyindex 5ac0942555..1e0990b3c4 100644--- a/autogpt_platform/backend/backend/data/subscription_checkout.py+++ b/autogpt_platform/backend/backend/data/subscription_checkout.py@@ -2,6 +2,7 @@from contextlib import asynccontextmanagerfrom datetime import timedelta+from typing import Callableimport stripefrom pydantic import BaseModel@@ -10,11 +11,19 @@ from backend.data.db import query_raw_with_schema, transactionfrom backend.data.stripe_client import stripe_call, stripe_list_itemsfrom backend.data.subscription_trial import get_subscription_trial+_ENDED_STATUSES = ("canceled", "incomplete_expired")+_ACCESS_STATUSES = ("active", "trialing")+ANOTHER_PLAN_LIVE = "Another plan is already active. Manage it in billing."+class SubscriptionCheckoutUnavailable(ValueError):pass+class AnotherPlanLive(SubscriptionCheckoutUnavailable):+ """A plan bought while the trial was cancel-pending has not ended it yet."""++class CheckoutLock(BaseModel):acquired: bool@@ -49,6 +58,42 @@ async def expire_other_subscription_checkouts(await stripe_call(stripe.checkout.Session.expire_async, session.id)+async def other_plan_is_live(customer_id: str, exclude_subscription_id: str) -> bool:+ """Whether the customer has a plan besides this one that has not ended.++ A plan bought through Checkout while a trial is cancel-pending ends the+ trial only once its webhook is handled, and the stale-subscription cleanup+ can fail; until then both are live, so keeping the trial would bill twice.+ """+ return await _another_plan(+ customer_id,+ exclude_subscription_id,+ lambda status: status not in _ENDED_STATUSES,+ )+++async def other_plan_has_access(customer_id: str, exclude_subscription_id: str) -> bool:+ """Whether a plan besides this one grants access now. Unlike+ other_plan_is_live, a Checkout whose first payment failed or is still+ pending does not count: its subscription is ``incomplete`` and grants+ nothing, so it must not end a trial that still has access."""+ return await _another_plan(+ customer_id, exclude_subscription_id, lambda status: status in _ACCESS_STATUSES+ )+++async def _another_plan(+ customer_id: str, exclude_subscription_id: str, counts: Callable[[str], bool]+) -> bool:+ subscriptions = await stripe_call(+ stripe.Subscription.list_async, customer=customer_id, status="all", limit=100+ )+ async for subscription in stripe_list_items(subscriptions):+ if subscription.id != exclude_subscription_id and counts(subscription.status):+ return True+ return False++async def ensure_no_unconverted_trial(user_id: str, customer_id: str) -> None:trial = await get_subscription_trial(user_id)if trial is None or trial.converted_at:@@ -56,11 +101,29 @@ async def ensure_no_unconverted_trial(user_id: str, customer_id: str) -> None:subscriptions = await stripe_call(stripe.Subscription.list_async, customer=customer_id, status="all", limit=100)+ trial_is_cancel_pending = another_plan_is_live = Falseasync for subscription in stripe_list_items(subscriptions):- if (subscription.metadata or {}).get(- "trial_enrollment_id"- ) == trial.id and subscription.status not in ("canceled", "incomplete_expired"):+ live = subscription.status not in _ENDED_STATUSES+ if (subscription.metadata or {}).get("trial_enrollment_id") != trial.id:+ another_plan_is_live |= live+ elif not _ends_without_converting(subscription):raise SubscriptionCheckoutUnavailable("This account already has a trial subscription. ""Manage it in billing before starting another plan.")+ else:+ trial_is_cancel_pending |= live+ # A plan bought while the trial is cancel-pending ends the trial only once+ # its webhook is handled; another Checkout before then would bill twice.+ if trial_is_cancel_pending and another_plan_is_live:+ raise AnotherPlanLive(ANOTHER_PLAN_LIVE)+++def _ends_without_converting(subscription: stripe.Subscription) -> bool:+ """A cancel-pending trial never bills, and the stale-subscription cleanup+ ends it as soon as the new plan's subscription is active."""+ if subscription.status in _ENDED_STATUSES:+ return True+ return subscription.status == "trialing" and bool(+ subscription.get("cancel_at_period_end")+ )diff --git a/autogpt_platform/backend/backend/data/subscription_checkout_test.py b/autogpt_platform/backend/backend/data/subscription_checkout_test.pyindex 64e087930c..9aea13bc32 100644--- a/autogpt_platform/backend/backend/data/subscription_checkout_test.py+++ b/autogpt_platform/backend/backend/data/subscription_checkout_test.py@@ -119,3 +119,207 @@ async def test_checkout_history_pagination_has_a_bounded_timeout():"user-1", "cus_test")next_page.assert_awaited_once()+++def _trial_history(**subscription) -> stripe.ListObject:+ return stripe.ListObject.construct_from(+ {+ "data": [+ {+ "id": "sub_trial",+ "metadata": {"trial_enrollment_id": "trial-1"},+ **subscription,+ }+ ],+ "has_more": False,+ },+ "test-key",+ )+++async def test_cancel_pending_trial_does_not_block_another_plan():+ with (+ patch.object(+ subscription_checkout,+ "get_subscription_trial",+ AsyncMock(return_value=MagicMock(id="trial-1", converted_at=None)),+ ),+ patch.object(+ stripe.Subscription,+ "list_async",+ AsyncMock(+ return_value=_trial_history(+ status="trialing", cancel_at_period_end=True+ )+ ),+ ),+ ):+ await subscription_checkout.ensure_no_unconverted_trial("user-1", "cus_test")+++ "subscription",+ [+ {"status": "trialing", "cancel_at_period_end": False},+ {"status": "trialing"},+ {"status": "active", "cancel_at_period_end": True},+ {"status": "past_due", "cancel_at_period_end": True},+ ],+)+async def test_running_or_unconverted_trial_still_blocks_another_plan(subscription):+ with (+ patch.object(+ subscription_checkout,+ "get_subscription_trial",+ AsyncMock(return_value=MagicMock(id="trial-1", converted_at=None)),+ ),+ patch.object(+ stripe.Subscription,+ "list_async",+ AsyncMock(return_value=_trial_history(**subscription)),+ ),+ ):+ with pytest.raises(+ subscription_checkout.SubscriptionCheckoutUnavailable,+ match="already has a trial subscription",+ ):+ await subscription_checkout.ensure_no_unconverted_trial(+ "user-1", "cus_test"+ )+++def _subscriptions(*subscriptions: dict, has_more: bool = False) -> stripe.ListObject:+ return stripe.ListObject.construct_from(+ {"data": list(subscriptions), "has_more": has_more}, "test-key"+ )+++ "status", ["active", "trialing", "past_due", "incomplete", "unpaid", "paused"]+)+async def test_another_plan_that_has_not_ended_is_live(status):+ listed = _subscriptions(+ {"id": "sub_trial", "status": "trialing"}, {"id": "sub_max", "status": status}+ )+ with patch.object(+ stripe.Subscription, "list_async", AsyncMock(return_value=listed)+ ) as list_async:+ assert await subscription_checkout.other_plan_is_live("cus_test", "sub_trial")+ list_async.assert_awaited_once_with(customer="cus_test", status="all", limit=100)+++ "others",+ [+ [],+ [{"id": "sub_old", "status": "canceled"}],+ [{"id": "sub_abandoned", "status": "incomplete_expired"}],+ ],+ ids=["only-this-one", "canceled", "incomplete-expired"],+)+async def test_this_plan_and_ended_plans_are_not_another_live_plan(others):+ listed = _subscriptions({"id": "sub_trial", "status": "trialing"}, *others)+ with patch.object(+ stripe.Subscription, "list_async", AsyncMock(return_value=listed)+ ):+ assert not await subscription_checkout.other_plan_is_live(+ "cus_test", "sub_trial"+ )+++ "status,has_access",+ [+ ("active", True),+ ("trialing", True),+ ("incomplete", False),+ ("past_due", False),+ ("canceled", False),+ ],+)+async def test_only_an_active_or_trialing_plan_grants_access(status, has_access):+ """An incomplete plan (a Checkout whose first payment failed or is still+ pending) grants nothing, so it must not end a trial that still has access."""+ listed = _subscriptions(+ {"id": "sub_trial", "status": "trialing"}, {"id": "sub_max", "status": status}+ )+ with patch.object(+ stripe.Subscription, "list_async", AsyncMock(return_value=listed)+ ):+ assert (+ await subscription_checkout.other_plan_has_access("cus_test", "sub_trial")+ is has_access+ )+++async def test_a_live_plan_on_a_later_page_is_found():+ first = _subscriptions({"id": "sub_old", "status": "canceled"}, has_more=True)+ second = _subscriptions({"id": "sub_max", "status": "active"})+ with (+ patch.object(stripe.Subscription, "list_async", AsyncMock(return_value=first)),+ patch.object(+ stripe.ListObject, "next_page_async", AsyncMock(return_value=second)+ ) as next_page,+ ):+ assert await subscription_checkout.other_plan_is_live("cus_test", "sub_trial")+ next_page.assert_awaited_once()+++def _cancel_pending_trial_and(*others: dict) -> stripe.ListObject:+ trial = {+ "id": "sub_trial",+ "status": "trialing",+ "cancel_at_period_end": True,+ "metadata": {"trial_enrollment_id": "trial-1"},+ }+ return _subscriptions(*others, trial)++[email protected]("status", ["active", "trialing", "past_due", "incomplete"])+async def test_cancel_pending_trial_blocks_checkout_while_another_plan_is_live(status):+ """A plan bought while the trial is cancel-pending ends the trial only once+ its webhook is handled; a second Checkout before then bills twice."""+ listed = _cancel_pending_trial_and(+ {"id": "sub_max", "status": status, "metadata": {}}+ )+ with (+ patch.object(+ subscription_checkout,+ "get_subscription_trial",+ AsyncMock(return_value=MagicMock(id="trial-1", converted_at=None)),+ ),+ patch.object(stripe.Subscription, "list_async", AsyncMock(return_value=listed)),+ ):+ with pytest.raises(subscription_checkout.AnotherPlanLive) as refused:+ await subscription_checkout.ensure_no_unconverted_trial(+ "user-1", "cus_test"+ )++ assert isinstance(+ refused.value, subscription_checkout.SubscriptionCheckoutUnavailable+ )+ assert str(refused.value) == "Another plan is already active. Manage it in billing."++[email protected]("status", ["canceled", "incomplete_expired"])+async def test_cancel_pending_trial_ignores_plans_that_ended(status):+ listed = _cancel_pending_trial_and(+ {"id": "sub_old", "status": status, "metadata": {}}+ )+ with (+ patch.object(+ subscription_checkout,+ "get_subscription_trial",+ AsyncMock(return_value=MagicMock(id="trial-1", converted_at=None)),+ ),+ patch.object(stripe.Subscription, "list_async", AsyncMock(return_value=listed)),+ ):+ await subscription_checkout.ensure_no_unconverted_trial("user-1", "cus_test")diff --git a/autogpt_platform/backend/backend/data/subscription_trial_cancel.py b/autogpt_platform/backend/backend/data/subscription_trial_cancel.pynew file mode 100644index 0000000000..90678b0d2f--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_trial_cancel.py@@ -0,0 +1,133 @@+"""Schedule a trial's end, or take that back, while the trial keeps its access.++Stripe ends a cancel-pending trial at trial_end with no invoice. Neither change+sends a notice here: the customer.subscription.updated webhook does, once per+flip, keyed by the trial's notification revision.+"""++from datetime import UTC, datetime++import stripe++from backend.data.credit import sync_subscription_from_stripe+from backend.data.stripe_client import stripe_call+from backend.data.subscription_checkout import (+ ANOTHER_PLAN_LIVE,+ SubscriptionCheckoutUnavailable,+ expire_other_subscription_checkouts,+ other_plan_is_live,+ subscription_checkout_lock,+)+from backend.data.subscription_trial import TrialState+from backend.data.subscription_trial_payment import subscription_card_can_be_charged++TRIAL_ENDED = "This trial has ended. Manage the plan in billing."+NOTHING_TO_RESUME = "Nothing to resume."+TRIAL_BUSY = "Your trial is already being updated. Please retry."+CARD_NEEDED = "Update your card under Payment method, then resume your trial."+++class TrialChangeRefused(ValueError):+ """The live trial cannot take this change; the message is safe to show."""+++async def schedule_trial_cancellation(trial: TrialState) -> None:+ """Under the checkout lock, so it never lands on the paid plan that+ subscribing now converts the trial into."""+ try:+ async with subscription_checkout_lock(trial.user_id):+ await _schedule_locked(trial)+ except SubscriptionCheckoutUnavailable as exc:+ raise TrialChangeRefused(TRIAL_BUSY) from exc+++async def resume_trial_subscription(trial: TrialState | None) -> None:+ if (+ trial is None+ or trial.subscription_id is None+ or trial.consumed_at is None+ or trial.converted_at is not None+ ):+ raise TrialChangeRefused(NOTHING_TO_RESUME)+ try:+ async with subscription_checkout_lock(trial.user_id):+ await _resume_locked(trial)+ except SubscriptionCheckoutUnavailable as exc:+ raise TrialChangeRefused(TRIAL_BUSY) from exc+++async def _schedule_locked(trial: TrialState) -> None:+ subscription = await _live_trial_subscription(trial)+ if not subscription.get("cancel_at_period_end"):+ subscription = await _change_live_trial(+ subscription, {"cancel_at_period_end": True}+ )+ await sync_subscription_from_stripe(dict(subscription))+++async def _resume_locked(trial: TrialState) -> None:+ subscription = await _live_trial_subscription(trial)+ if (subscription.get("trial_end") or 0) <= datetime.now(UTC).timestamp():+ raise await _synced_refusal(subscription, TRIAL_ENDED)+ if not subscription.get("cancel_at_period_end"):+ raise await _synced_refusal(subscription, NOTHING_TO_RESUME)+ # Only a cancel-pending trial keeps access without a card Stripe can charge;+ # resuming without one would end the access it still has.+ if not await subscription_card_can_be_charged(subscription.id, datetime.now(UTC)):+ raise TrialChangeRefused(CARD_NEEDED)+ # A plan checkout opened while cancel-pending must not complete beside the+ # resumed trial: that would leave two live subscriptions. The checkout lock+ # keeps a new one from opening between this expiry and the resume.+ await expire_other_subscription_checkouts(trial.customer_id)+ # A plan already bought that way ends the trial only once its webhook (or+ # the stale-subscription cleanup) runs; resuming before then would let the+ # trial convert next to it and bill twice.+ if await other_plan_is_live(trial.customer_id, subscription.id):+ raise TrialChangeRefused(ANOTHER_PLAN_LIVE)+ subscription = await _change_live_trial(+ subscription, {"cancel_at_period_end": False}+ )+ await sync_subscription_from_stripe(dict(subscription))+++async def _live_trial_subscription(trial: TrialState) -> stripe.Subscription:+ if trial.subscription_id is None:+ raise TrialChangeRefused(TRIAL_ENDED)+ subscription = await stripe_call(+ stripe.Subscription.retrieve_async, trial.subscription_id+ )+ metadata = subscription.get("metadata") or {}+ if (+ subscription.get("customer") != trial.customer_id+ or metadata.get("trial_enrollment_id") != trial.id+ or metadata.get("user_id") != trial.user_id+ ):+ raise TrialChangeRefused(TRIAL_ENDED)+ if subscription.get("status") != "trialing":+ raise await _synced_refusal(subscription, TRIAL_ENDED)+ return subscription+++async def _synced_refusal(+ subscription: stripe.Subscription, message: str+) -> TrialChangeRefused:+ """Stripe moved on before its webhook landed: save its state first, so the+ status the person reloads shows why the change was refused."""+ await sync_subscription_from_stripe(dict(subscription))+ return TrialChangeRefused(message)+++async def _change_live_trial(+ subscription: stripe.Subscription, change: stripe.Subscription.ModifyParams+) -> stripe.Subscription:+ try:+ return await stripe_call(+ stripe.Subscription.modify_async, subscription.id, **change+ )+ except stripe.InvalidRequestError as exc:+ # Stripe rejects the update once the trial has ended between our read+ # and the write; anything else stays a retryable failure.+ latest = await stripe_call(stripe.Subscription.retrieve_async, subscription.id)+ if latest.get("status") != "canceled":+ raise+ raise await _synced_refusal(latest, TRIAL_ENDED) from excdiff --git a/autogpt_platform/backend/backend/data/subscription_trial_cancel_reconcile_test.py b/autogpt_platform/backend/backend/data/subscription_trial_cancel_reconcile_test.pynew file mode 100644index 0000000000..33f5401717--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_trial_cancel_reconcile_test.py@@ -0,0 +1,291 @@+"""Reconciling a trial whose cancellation is scheduled: it keeps access until+the trial ends, then ends, or converts once resumed."""++from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, patch++import pytest+import stripe+from prisma.enums import SubscriptionTier++from backend.data import subscription_trial_stripe as fulfillment+from backend.data.subscription_trial import TrialState+from backend.data.subscription_trial_rejection import TrialRejectionReason++pytest_plugins = ("backend.data.subscription_trial_fixtures",)+++def _recorded_cancel_pending(trial: TrialState) -> TrialState:+ now = datetime.now(UTC)+ return trial.model_copy(+ update={+ "status": "trialing",+ "consumed_at": now - timedelta(days=2),+ "card_verified_at": now - timedelta(days=2),+ "subscription_id": "sub_1",+ "cancel_at_period_end": True,+ "notification_revision": 1,+ }+ )+++async def test_scheduled_cancellation_keeps_access_until_trial_end(+ trial, subscription, boundaries+):+ subscription["cancel_at_period_end"] = True+ with patch.object(+ fulfillment.stripe.Subscription, "cancel_async", AsyncMock()+ ) as cancel:+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] == SubscriptionTier.TRIAL+ cancel.assert_not_awaited()+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]+ assert saved["status"] == "trialing"+ assert saved["cancelAtPeriodEnd"] is True+ assert saved["notificationRevision"] == 1+ assert boundaries.user.update_many.await_args.kwargs["data"] == {+ "subscriptionTier": SubscriptionTier.TRIAL+ }+++ "reason,claimed,fingerprint",+ [+ (TrialRejectionReason.INTRO_OFFER_ALREADY_USED, False, "fp_test"),+ (TrialRejectionReason.CARD_VERIFICATION_FAILED, True, None),+ ],+)+async def test_rejected_cancel_pending_trial_is_still_canceled_immediately(+ trial, subscription, boundaries, reason, claimed, fingerprint+):+ subscription["cancel_at_period_end"] = True+ subscription["default_payment_method"]["card"]["fingerprint"] = fingerprint+ canceled = {**subscription, "status": "canceled"}+ with (+ patch.object(+ fulfillment, "claim_trial_identities", AsyncMock(return_value=claimed)+ ),+ patch.object(+ fulfillment.stripe.Subscription,+ "cancel_async",+ AsyncMock(return_value=canceled),+ ) as cancel,+ ):+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] == SubscriptionTier.NO_TIER+ assert cancel.await_args.kwargs["invoice_now"] is False+ assert cancel.await_args.kwargs["prorate"] is False+ assert cancel.await_args.kwargs["cancellation_details"] == {+ "comment": reason.stripe_comment+ }+ assert (+ boundaries.subscriptiontrial.update.await_args.kwargs["data"]["rejectionReason"]+ == reason+ )+++async def test_scheduled_cancellation_ends_access_when_stripe_ends_the_trial(+ trial, subscription, boundaries+):+ """customer.subscription.deleted at trial end: no tier, no conversion."""+ trial = _recorded_cancel_pending(trial)+ ended_at = int(datetime.now(UTC).timestamp()) - 30+ subscription.update(+ status="canceled",+ cancel_at_period_end=True,+ trial_end=ended_at,+ ended_at=ended_at,+ )+ with patch.object(+ fulfillment.stripe.Subscription, "cancel_async", AsyncMock()+ ) as cancel:+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] == SubscriptionTier.NO_TIER+ cancel.assert_not_awaited()+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]+ assert saved["status"] == "canceled"+ assert saved["endsAt"] == datetime.fromtimestamp(ended_at, UTC)+ assert saved["convertedAt"] is None+ assert saved["stripeConversionInvoiceId"] is None+ assert saved["notificationRevision"] == 1+ assert boundaries.user.update_many.await_args.kwargs["data"] == {+ "subscriptionTier": SubscriptionTier.NO_TIER+ }+++async def test_resumed_trial_converts_at_trial_end(trial, subscription, boundaries):+ now = datetime.now(UTC)+ trial = trial.model_copy(+ update={+ "status": "trialing",+ "consumed_at": now - timedelta(days=7),+ "card_verified_at": now - timedelta(days=7),+ "subscription_id": "sub_1",+ "notification_revision": 2,+ }+ )+ end = int(now.timestamp()) - 60+ subscription.update(+ status="active",+ trial_end=end,+ latest_invoice={+ "id": "in_1",+ "status": "paid",+ "created": end,+ "billing_reason": "subscription_cycle",+ },+ )+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] == SubscriptionTier.PRO+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]+ assert saved["convertedAt"] is not None+ assert saved["stripeConversionInvoiceId"] == "in_1"+ assert saved["notificationRevision"] == 2+++async def test_a_cancel_pending_trial_ends_once_another_plan_is_live(+ trial, subscription, boundaries+):+ """A plan bought while cancel-pending ends the trial in its own cleanup,+ which can fail; the trial must never write TRIAL over that paid plan."""+ trial = _recorded_cancel_pending(trial)+ subscription["cancel_at_period_end"] = True+ ended_at = int(datetime.now(UTC).timestamp())+ canceled = {**subscription, "status": "canceled", "ended_at": ended_at}+ max_plan = stripe.ListObject.construct_from(+ {+ "data": [{"id": "sub_max", "object": "subscription", "status": "active"}],+ "has_more": False,+ },+ "test-key",+ )+ with (+ patch.object(+ fulfillment.stripe.Subscription,+ "list_async",+ AsyncMock(return_value=max_plan),+ ),+ patch.object(+ fulfillment.stripe.Subscription,+ "cancel_async",+ AsyncMock(return_value=canceled),+ ) as cancel,+ ):+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] is None+ cancel.assert_awaited_once()+ assert cancel.await_args.args == ("sub_1",)+ assert cancel.await_args.kwargs["invoice_now"] is False+ assert cancel.await_args.kwargs["prorate"] is False+ assert "cancellation_details" not in cancel.await_args.kwargs+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]+ assert saved["status"] == "canceled"+ assert saved["rejectionReason"] is None+ boundaries.user.update_many.assert_not_awaited()++[email protected]("status", ["incomplete", "past_due"])+async def test_a_plan_that_grants_no_access_never_ends_a_cancel_pending_trial(+ trial, subscription, boundaries, status+):+ """A Checkout whose first payment failed or is still pending leaves its+ subscription incomplete for up to a day. It grants nothing, so the trial+ keeps the access it was promised until trial_end."""+ trial = _recorded_cancel_pending(trial)+ subscription["cancel_at_period_end"] = True+ unpaid_plan = stripe.ListObject.construct_from(+ {+ "data": [{"id": "sub_max", "object": "subscription", "status": status}],+ "has_more": False,+ },+ "test-key",+ )+ with (+ patch.object(+ fulfillment.stripe.Subscription,+ "list_async",+ AsyncMock(return_value=unpaid_plan),+ ),+ patch.object(+ fulfillment.stripe.Subscription, "cancel_async", AsyncMock()+ ) as cancel,+ ):+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] == SubscriptionTier.TRIAL+ cancel.assert_not_awaited()+++async def test_a_cancel_pending_trial_on_changed_items_ends_now(+ trial, subscription, boundaries+):+ """The reconcile refuses an unconverted trial on any price but the accepted+ one, so a cancel-pending trial whose items changed ends now, as every+ cancel-pending trial used to, instead of failing every sync."""+ subscription.update(cancel_at_period_end=True, items=None)+ canceled = {**subscription, "status": "canceled", "cancel_at_period_end": False}+ with patch.object(+ fulfillment.stripe.Subscription,+ "cancel_async",+ AsyncMock(return_value=canceled),+ ) as cancel:+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] == SubscriptionTier.NO_TIER+ cancel.assert_awaited_once()+++async def test_a_trial_not_cancel_pending_never_looks_for_other_plans(+ trial, boundaries+):+ with patch.object(+ fulfillment.stripe.Subscription, "list_async", AsyncMock()+ ) as others:+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] == SubscriptionTier.TRIAL+ others.assert_not_awaited()+++async def test_a_cancel_pending_trial_keeps_access_after_its_card_expires(+ trial, subscription, boundaries+):+ """No charge is coming, so the card verified at the start is enough until+ the trial ends."""+ trial = _recorded_cancel_pending(trial)+ subscription["cancel_at_period_end"] = True+ subscription["default_payment_method"]["card"].update(exp_month=1, exp_year=2020)+ result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)+ assert result is not None and result[1] == SubscriptionTier.TRIAL+ saved = boundaries.subscriptiontrial.update.await_args.kwargs["data"]+ assert saved["cardVerifiedAt"] == trial.card_verified_at+++ "pending,verified,expected",+ [+ (True, True, SubscriptionTier.TRIAL),+ (False, True, SubscriptionTier.NO_TIER),+ (True, False, SubscriptionTier.NO_TIER),+ ],+ ids=["cancel-pending", "converting", "never-verified"],+)+def test_only_a_cancel_pending_trial_skips_the_card_check(+ trial, pending, verified, expected+):+ now = datetime.now(UTC)+ trial = trial.model_copy(update={"card_verified_at": now if verified else None})+ snapshot = fulfillment.SubscriptionSnapshot(+ id="sub_1",+ customer="cus_1",+ status="trialing",+ trial_end=int(now.timestamp()) + 86400,+ cancel_at_period_end=pending,+ )+ assert fulfillment.trial_subscription_tier(trial, snapshot, now) == expecteddiff --git a/autogpt_platform/backend/backend/data/subscription_trial_cancel_test.py b/autogpt_platform/backend/backend/data/subscription_trial_cancel_test.pynew file mode 100644index 0000000000..2bb253a07c--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_trial_cancel_test.py@@ -0,0 +1,415 @@+from contextlib import asynccontextmanager+from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, MagicMock, call, patch++import pytest+import stripe++from backend.data import subscription_trial_cancel as cancel+from backend.data.subscription_checkout import SubscriptionCheckoutUnavailable+from backend.data.subscription_trial import TrialState+from backend.data.subscription_trial_config import AcceptedTrialOffer++ENDED = "This trial has ended. Manage the plan in billing."+++def trial() -> TrialState:+ now = datetime.now(UTC)+ return TrialState(+ id="trial-1",+ user_id="user-1",+ customer_id="cus_1",+ offer=AcceptedTrialOffer(+ version="cancel-v1",+ new_users_from=now - timedelta(days=3),+ duration_days=7,+ tier="PRO",+ billing_cycle="monthly",+ daily_cost_limit=250_000,+ weekly_cost_limit=1_000_000,+ total_cost_limit=1_000_000,+ onboarding_credit_amount=300,+ price_id="price_pro",+ unit_amount=5000,+ currency="usd",+ ),+ checkout_session_id="cs_1",+ subscription_id="sub_1",+ checkout_attempt=0,+ success_url="https://example.com/ok",+ cancel_url="https://example.com/no",+ checkout_metadata={},+ status="trialing",+ card_verified_at=now - timedelta(days=2),+ started_at=now - timedelta(days=2),+ ends_at=now + timedelta(days=5),+ consumed_at=now - timedelta(days=2),+ converted_at=None,+ cancel_at_period_end=False,+ cost_microdollars=0,+ )+++def _live(trial: TrialState, **changes) -> stripe.Subscription:+ return stripe.Subscription.construct_from(+ {+ "id": "sub_1",+ "customer": trial.customer_id,+ "status": "trialing",+ "cancel_at_period_end": False,+ "trial_end": int((datetime.now(UTC) + timedelta(days=5)).timestamp()),+ "metadata": {"trial_enrollment_id": trial.id, "user_id": trial.user_id},+ **changes,+ },+ "test-key",+ )+++def api():+ """Stripe, the sync, the other-plan check and the checkout lock as this+ module calls them, recorded in call order. ``api.lock.side_effect`` makes+ the lock busy; ``api.other_plan.return_value = True`` makes another plan+ live."""+ calls = MagicMock()++ @asynccontextmanager+ async def lock(user_id: str):+ calls.lock(user_id)+ try:+ yield+ finally:+ calls.unlock()++ with (+ patch.object(cancel, "subscription_checkout_lock", lock),+ patch.object(stripe.Subscription, "retrieve_async", AsyncMock()) as retrieve,+ patch.object(stripe.Subscription, "modify_async", AsyncMock()) as modify,+ patch.object(stripe.Subscription, "cancel_async", AsyncMock()) as end_now,+ patch.object(+ cancel, "expire_other_subscription_checkouts", AsyncMock()+ ) as expire,+ patch.object(+ cancel, "other_plan_is_live", AsyncMock(return_value=False)+ ) as other_plan,+ patch.object(cancel, "sync_subscription_from_stripe", AsyncMock()) as sync,+ patch.object(+ cancel,+ "subscription_card_can_be_charged",+ AsyncMock(return_value=True, name="card"),+ ) as card,+ ):+ calls.card = card+ for name, mock in (+ ("retrieve", retrieve),+ ("modify", modify),+ ("end_now", end_now),+ ("expire", expire),+ ("other_plan", other_plan),+ ("sync", sync),+ ):+ calls.attach_mock(mock, name)+ yield calls+++def _assert_no_writes(api) -> None:+ api.modify.assert_not_awaited()+ api.end_now.assert_not_awaited()+ api.expire.assert_not_awaited()+++async def test_cancel_schedules_the_end_instead_of_ending_the_trial(trial, api):+ pending = _live(trial, cancel_at_period_end=True)+ api.retrieve.return_value = _live(trial)+ api.modify.return_value = pending+ await cancel.schedule_trial_cancellation(trial)+ api.modify.assert_awaited_once_with("sub_1", cancel_at_period_end=True)+ api.end_now.assert_not_awaited()+ api.sync.assert_awaited_once_with(dict(pending))+++async def test_a_second_cancel_writes_nothing_to_stripe(trial, api):+ pending = _live(trial, cancel_at_period_end=True)+ api.retrieve.return_value = pending+ await cancel.schedule_trial_cancellation(trial)+ _assert_no_writes(api)+ api.sync.assert_awaited_once_with(dict(pending))+++async def test_cancel_holds_the_checkout_lock_from_read_to_sync(trial, api):+ """Subscribe now converts the trial under this lock: a cancel landing in+ between would schedule the new paid plan to end."""+ pending = _live(trial, cancel_at_period_end=True)+ api.retrieve.return_value = _live(trial)+ api.modify.return_value = pending+ await cancel.schedule_trial_cancellation(trial)+ assert api.mock_calls == [+ call.lock("user-1"),+ call.retrieve("sub_1"),+ call.modify("sub_1", cancel_at_period_end=True),+ call.sync(dict(pending)),+ call.unlock(),+ ]+++async def test_cancel_while_the_trial_is_being_updated_is_refused_untouched(trial, api):+ api.lock.side_effect = SubscriptionCheckoutUnavailable(+ "Another checkout is already starting. Please retry."+ )+ with pytest.raises(+ cancel.TrialChangeRefused,+ match="^Your trial is already being updated. Please retry.$",+ ):+ await cancel.schedule_trial_cancellation(trial)+ api.retrieve.assert_not_awaited()+ _assert_no_writes(api)+ api.sync.assert_not_awaited()+++async def test_resume_takes_back_the_scheduled_end(trial, api):+ resumed = _live(trial)+ api.retrieve.return_value = _live(trial, cancel_at_period_end=True)+ api.modify.return_value = resumed+ await cancel.resume_trial_subscription(trial)+ api.modify.assert_awaited_once_with("sub_1", cancel_at_period_end=False)+ api.sync.assert_awaited_once_with(dict(resumed))+++async def test_resume_without_a_card_stripe_can_charge_is_refused_untouched(trial, api):+ """Only a cancel-pending trial keeps access on a card Stripe can't+ charge; resuming would end the access it still has."""+ api.retrieve.return_value = _live(trial, cancel_at_period_end=True)+ api.card.return_value = False+ with pytest.raises(+ cancel.TrialChangeRefused,+ match="^Update your card under Payment method, then resume your trial.$",+ ):+ await cancel.resume_trial_subscription(trial)+ assert api.card.await_args.args[0] == "sub_1"+ _assert_no_writes(api)+ api.sync.assert_not_awaited()+++async def test_resume_expires_other_open_checkouts_before_resuming(trial, api):+ """A plan checkout opened while cancel-pending must not complete beside the+ resumed trial and leave two live subscriptions."""+ api.retrieve.return_value = _live(trial, cancel_at_period_end=True)+ api.modify.return_value = _live(trial)+ await cancel.resume_trial_subscription(trial)+ writes = [c for c in api.mock_calls if c[0] in ("expire", "modify")]+ assert writes == [+ call.expire("cus_1"),+ call.modify("sub_1", cancel_at_period_end=False),+ ]+++async def test_resume_holds_the_checkout_lock_from_read_to_sync(trial, api):+ """No plan checkout can open between the expiry and the resume, where it+ would escape the expiry and could complete beside the resumed trial."""+ resumed = _live(trial)+ api.retrieve.return_value = _live(trial, cancel_at_period_end=True)+ api.modify.return_value = resumed+ await cancel.resume_trial_subscription(trial)+ assert api.mock_calls == [+ call.lock("user-1"),+ call.retrieve("sub_1"),+ call.expire("cus_1"),+ call.other_plan("cus_1", "sub_1"),+ call.modify("sub_1", cancel_at_period_end=False),+ call.sync(dict(resumed)),+ call.unlock(),+ ]+++async def test_resume_is_refused_while_another_plan_is_live(trial, api):+ """A plan bought through Checkout while cancel-pending ends the trial only+ once its webhook or the stale-subscription cleanup runs; resuming before+ then would let the trial convert next to it and bill twice."""+ api.retrieve.return_value = _live(trial, cancel_at_period_end=True)+ api.other_plan.return_value = True+ with pytest.raises(+ cancel.TrialChangeRefused,+ match="^Another plan is already active. Manage it in billing.$",+ ):+ await cancel.resume_trial_subscription(trial)+ assert api.mock_calls == [+ call.lock("user-1"),+ call.retrieve("sub_1"),+ call.expire("cus_1"),+ call.other_plan("cus_1", "sub_1"),+ call.unlock(),+ ]+++async def test_resume_while_a_checkout_is_starting_is_refused_untouched(trial, api):+ """Another tab resuming, or a plan change starting, holds the lock."""+ api.lock.side_effect = SubscriptionCheckoutUnavailable(+ "Another checkout is already starting. Please retry."+ )+ with pytest.raises(+ cancel.TrialChangeRefused,+ match="^Your trial is already being updated. Please retry.$",+ ):+ await cancel.resume_trial_subscription(trial)+ api.retrieve.assert_not_awaited()+ _assert_no_writes(api)+ api.sync.assert_not_awaited()+++async def test_resume_without_a_scheduled_end_reconciles_then_writes_nothing(+ trial, api+):+ """The saved trial can still say cancel-pending (a renewal in the billing+ portal whose webhook has not landed): the sync lets the reload show it."""+ live = _live(trial)+ api.retrieve.return_value = live+ with pytest.raises(cancel.TrialChangeRefused, match="^Nothing to resume.$"):+ await cancel.resume_trial_subscription(trial)+ _assert_no_writes(api)+ api.sync.assert_awaited_once_with(dict(live))+++async def test_resume_after_trial_end_is_reconciled_then_refused(trial, api):+ past = int((datetime.now(UTC) - timedelta(minutes=1)).timestamp())+ live = _live(trial, cancel_at_period_end=True, trial_end=past)+ api.retrieve.return_value = live+ with pytest.raises(cancel.TrialChangeRefused) as refused:+ await cancel.resume_trial_subscription(trial)+ assert str(refused.value) == ENDED+ _assert_no_writes(api)+ api.sync.assert_awaited_once_with(dict(live))+++ "change",+ [+ lambda trial: trial.model_copy(update={"converted_at": datetime.now(UTC)}),+ lambda trial: trial.model_copy(update={"consumed_at": None}),+ lambda trial: trial.model_copy(update={"subscription_id": None}),+ lambda trial: None,+ ],+ ids=["converted", "not-started", "no-subscription", "no-trial"],+)+async def test_resume_needs_a_started_unconverted_trial(trial, api, change):+ with pytest.raises(cancel.TrialChangeRefused, match="^Nothing to resume.$"):+ await cancel.resume_trial_subscription(change(trial))+ api.retrieve.assert_not_awaited()+ _assert_no_writes(api)+++OPERATIONS = [+ pytest.param(cancel.schedule_trial_cancellation, False, id="cancel"),+ pytest.param(cancel.resume_trial_subscription, True, id="resume"),+]++[email protected]("operation,pending", OPERATIONS)[email protected]("status", ["canceled", "active", "past_due"])+async def test_a_trial_stripe_no_longer_runs_is_reconciled_then_refused(+ trial, api, operation, pending, status+):+ """Stripe ended or converted it before its webhook landed: the sync lets+ the status the person reloads show what happened."""+ ended = _live(trial, status=status, cancel_at_period_end=pending)+ api.retrieve.return_value = ended+ with pytest.raises(cancel.TrialChangeRefused) as refused:+ await operation(trial)+ assert str(refused.value) == ENDED+ api.sync.assert_awaited_once_with(dict(ended))+ _assert_no_writes(api)++[email protected]("operation,pending", OPERATIONS)+async def test_a_trial_ending_mid_update_is_reconciled_then_refused(+ trial, api, operation, pending+):+ ended = _live(trial, status="canceled", cancel_at_period_end=pending)+ api.retrieve.side_effect = [_live(trial, cancel_at_period_end=pending), ended]+ api.modify.side_effect = stripe.InvalidRequestError(+ "A canceled subscription can only update its cancellation_details", None+ )+ with pytest.raises(cancel.TrialChangeRefused) as refused:+ await operation(trial)+ assert str(refused.value) == ENDED+ api.sync.assert_awaited_once_with(dict(ended))++[email protected]("operation,pending", OPERATIONS)+async def test_a_rejected_update_on_a_live_trial_stays_retryable(+ trial, api, operation, pending+):+ api.retrieve.return_value = _live(trial, cancel_at_period_end=pending)+ api.modify.side_effect = stripe.InvalidRequestError("Try again", None)+ with pytest.raises(stripe.InvalidRequestError):+ await operation(trial)+ api.sync.assert_not_awaited()++[email protected]("operation,pending", OPERATIONS)+async def test_a_stripe_failure_changes_nothing(trial, api, operation, pending):+ api.retrieve.return_value = _live(trial, cancel_at_period_end=pending)+ api.modify.side_effect = stripe.APIConnectionError("Stripe is unreachable")+ with pytest.raises(stripe.StripeError):+ await operation(trial)+ api.sync.assert_not_awaited()+++async def test_resume_stops_if_open_checkouts_cannot_be_expired(trial, api):+ api.retrieve.return_value = _live(trial, cancel_at_period_end=True)+ api.expire.side_effect = stripe.APIConnectionError("Stripe is unreachable")+ with pytest.raises(stripe.StripeError):+ await cancel.resume_trial_subscription(trial)+ api.modify.assert_not_awaited()+ api.sync.assert_not_awaited()+++async def test_resume_stops_if_other_plans_cannot_be_listed(trial, api):+ api.retrieve.return_value = _live(trial, cancel_at_period_end=True)+ api.other_plan.side_effect = stripe.APIConnectionError("Stripe is unreachable")+ with pytest.raises(stripe.StripeError):+ await cancel.resume_trial_subscription(trial)+ api.modify.assert_not_awaited()+ api.sync.assert_not_awaited()++[email protected]("operation,pending", OPERATIONS)+ "change",+ [+ {"customer": "cus_other"},+ {"metadata": {"trial_enrollment_id": "trial-x", "user_id": "user-1"}},+ {"metadata": {"trial_enrollment_id": "trial-1", "user_id": "user-x"}},+ {"metadata": None},+ ],+ ids=["other-customer", "other-enrollment", "other-user", "no-metadata"],+)+async def test_only_this_enrollments_live_trial_can_change(+ trial, api, operation, pending, change+):+ api.retrieve.return_value = _live(trial, cancel_at_period_end=pending, **change)+ with pytest.raises(cancel.TrialChangeRefused) as refused:+ await operation(trial)+ assert str(refused.value) == ENDED+ _assert_no_writes(api)+ api.sync.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/data/subscription_trial_conversion.py b/autogpt_platform/backend/backend/data/subscription_trial_conversion.pynew file mode 100644index 0000000000..013405954c--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_trial_conversion.py@@ -0,0 +1,148 @@+"""Start the paid plan a cancel-pending trial was accepted for, today."""++import logging+from datetime import UTC, datetime++import stripe+from prisma.enums import SubscriptionTier++from backend.data.credit import (+ invalidate_active_subscription_cache,+ sync_subscription_from_stripe,+)+from backend.data.stripe_client import stripe_call+from backend.data.subscription_checkout import (+ ANOTHER_PLAN_LIVE,+ SubscriptionCheckoutUnavailable,+ expire_other_subscription_checkouts,+ other_plan_is_live,+ 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++logger = logging.getLogger(__name__)++TRIAL_ENDED = "This trial has ended. Manage the plan in billing."+TRIAL_RUNNING = (+ "Your accepted plan starts after your trial. Manage the trial in billing."+)+TRIAL_BUSY = "Your trial is already being updated. Please retry."+++class TrialConversionRefused(Exception):+ """The live trial is no longer one this request may convert."""+++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)+ if trial is None or not _is_cancel_pending(trial):+ return None+ return trial+++def is_trial_plan(+ trial: TrialState, tier: SubscriptionTier, billing_cycle: str+) -> bool:+ """Whether this is the plan the trial accepted. The conversion bills the+ accepted price, the one the plan card shows, even after a re-price."""+ offer = trial.offer+ 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.++ 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.++ 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.+ """+ try:+ async with subscription_checkout_lock(trial.user_id):+ return await _convert_locked(trial)+ except SubscriptionCheckoutUnavailable as exc:+ raise TrialConversionRefused(TRIAL_BUSY) from exc+++async def _convert_locked(trial: TrialState) -> bool:+ subscription = await _live_cancel_pending_subscription(trial)+ if subscription is None:+ return True+ if not await subscription_card_can_be_charged(subscription.id, datetime.now(UTC)):+ return False+ 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",+ )+ invalidate_active_subscription_cache(trial.customer_id)+ if converted.get("status") != "active":+ await sync_subscription_from_stripe(dict(converted))+ raise TrialConversionRefused(TRIAL_ENDED)+ try:+ await sync_subscription_from_stripe(dict(converted))+ except Exception:+ # The card is charged and the plan is live in Stripe; its webhooks+ # save it. Failing now would tell a paying customer it failed.+ logger.exception(+ f"Trial {trial.id} converted in Stripe but the follow-up sync failed"+ )+ return True+++def _is_cancel_pending(trial: TrialState) -> bool:+ return bool(+ trial.subscription_id+ and trial.consumed_at is not None+ and trial.converted_at is None+ and trial.status == "trialing"+ and trial.cancel_at_period_end+ and trial.ends_at is not None+ and trial.ends_at > datetime.now(UTC)+ )+++async def _live_cancel_pending_subscription(+ trial: TrialState,+) -> stripe.Subscription | None:+ """The trial's subscription while it is still cancel-pending, or None+ once Stripe shows it converted (an earlier request whose answer was lost)."""+ if not trial.subscription_id:+ raise TrialConversionRefused(TRIAL_ENDED)+ subscription = await stripe_call(+ stripe.Subscription.retrieve_async, trial.subscription_id+ )+ metadata = subscription.get("metadata") or {}+ if (+ subscription.get("customer") != trial.customer_id+ or metadata.get("trial_enrollment_id") != trial.id+ or metadata.get("user_id") != trial.user_id+ ):+ raise TrialConversionRefused(TRIAL_ENDED)+ status = subscription.get("status")+ running = (subscription.get("trial_end") or 0) > datetime.now(UTC).timestamp()+ if status == "trialing" and running and subscription.get("cancel_at_period_end"):+ return subscription+ # Stripe moved on before its webhook landed: save its state first, so the+ # status the person reloads shows the plan, or why this was refused.+ await sync_subscription_from_stripe(dict(subscription))+ if status == "active":+ return None+ if status == "trialing" and running:+ raise TrialConversionRefused(TRIAL_RUNNING)+ raise TrialConversionRefused(TRIAL_ENDED)diff --git a/autogpt_platform/backend/backend/data/subscription_trial_conversion_test.py b/autogpt_platform/backend/backend/data/subscription_trial_conversion_test.pynew file mode 100644index 0000000000..97408581c3--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_trial_conversion_test.py@@ -0,0 +1,424 @@+from contextlib import asynccontextmanager+from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+import stripe+from prisma.enums import SubscriptionTier++from backend.data import credit+from backend.data import subscription_trial_conversion as conversion+from backend.data.subscription_trial import TrialState++pytest_plugins = ("backend.data.subscription_trial_fixtures",)+++def pending_trial(trial: TrialState) -> TrialState:+ now = datetime.now(UTC)+ return trial.model_copy(+ update={+ "subscription_id": "sub_1",+ "status": "trialing",+ "card_verified_at": now - timedelta(days=2),+ "started_at": now - timedelta(days=2),+ "ends_at": now + timedelta(days=5),+ "consumed_at": now - timedelta(days=2),+ "cancel_at_period_end": True,+ }+ )+++def live(subscription: dict) -> dict:+ return {**subscription, "cancel_at_period_end": True}+++def _subscriptions(*subscriptions: dict) -> stripe.ListObject:+ return stripe.ListObject.construct_from(+ {"data": list(subscriptions), "has_more": False}, "test-key"+ )+++def boundaries(live: dict):+ calls: list[str] = []+ converted = stripe.Subscription.construct_from(+ {**live, "status": "active", "cancel_at_period_end": False}, "test-key"+ )++ def recorded(name: str, result: object = None) -> AsyncMock:+ async def effect(*args, **kwargs):+ calls.append(name)+ return result++ return AsyncMock(side_effect=effect)++ @asynccontextmanager+ async def lock(user_id: str):+ calls.append(f"lock:{user_id}")+ try:+ yield+ finally:+ calls.append("unlock")++ retrieve = recorded(+ "retrieve", stripe.Subscription.construct_from(live, "test-key")+ )+ others = recorded("others", _subscriptions(live))+ with (+ patch.object(conversion, "subscription_checkout_lock", lock),+ patch.object(stripe.Subscription, "retrieve_async", retrieve),+ patch.object(stripe.Subscription, "list_async", others),+ patch.object(+ stripe.Subscription, "modify_async", recorded("modify", converted)+ ) as modify,+ patch.object(+ conversion, "expire_other_subscription_checkouts", recorded("expire")+ ) as expire,+ patch.object(+ conversion, "sync_subscription_from_stripe", recorded("sync")+ ) as sync,+ patch.object(+ conversion,+ "subscription_card_can_be_charged",+ AsyncMock(return_value=True),+ ) as card,+ ):+ yield MagicMock(+ calls=calls,+ retrieve=retrieve,+ others=others,+ modify=modify,+ expire=expire,+ sync=sync,+ card=card,+ converted=converted,+ )+++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 boundaries.calls == [+ "lock:user-1",+ "retrieve",+ "expire",+ "others",+ "modify",+ "sync",+ "unlock",+ ]+ boundaries.retrieve.assert_awaited_once_with("sub_1")+ assert boundaries.card.await_args.args[0] == "sub_1"+ boundaries.expire.assert_awaited_once_with("cus_1")+ boundaries.others.assert_awaited_once_with(+ customer="cus_1", status="all", limit=100+ )+ boundaries.modify.assert_awaited_once_with(+ "sub_1",+ cancel_at_period_end=False,+ trial_end="now",+ payment_behavior="error_if_incomplete",+ )+ boundaries.sync.assert_awaited_once_with(dict(boundaries.converted))+++ "change",+ [+ {"customer": "cus_other"},+ {"metadata": {"trial_enrollment_id": "trial-x", "user_id": "user-1"}},+ {"metadata": {"trial_enrollment_id": "trial-1", "user_id": "user-x"}},+ {"metadata": None},+ ],+)+async def test_refuses_a_subscription_the_trial_does_not_own(+ pending_trial, live, boundaries, change+):+ live.update(change)+ boundaries.retrieve.side_effect = None+ boundaries.retrieve.return_value = stripe.Subscription.construct_from(+ live, "test-key"+ )++ with pytest.raises(conversion.TrialConversionRefused) as refused:+ await conversion.convert_cancel_pending_trial(pending_trial)++ assert str(refused.value) == "This trial has ended. Manage the plan in billing."+ boundaries.expire.assert_not_awaited()+ boundaries.modify.assert_not_awaited()+ boundaries.sync.assert_not_awaited()+++ "change",+ [+ {"status": "past_due"},+ {"trial_end": int((datetime.now(UTC) - timedelta(minutes=1)).timestamp())},+ ],+)+async def test_refuses_a_trial_that_is_no_longer_running(+ pending_trial, live, boundaries, change+):+ """Stripe's state is saved first, so the refreshed page shows why."""+ live.update(change)+ ended = stripe.Subscription.construct_from(live, "test-key")+ boundaries.retrieve.side_effect = None+ boundaries.retrieve.return_value = ended++ with pytest.raises(conversion.TrialConversionRefused, match="has ended"):+ await conversion.convert_cancel_pending_trial(pending_trial)++ boundaries.sync.assert_awaited_once_with(dict(ended))+ boundaries.expire.assert_not_awaited()+ boundaries.modify.assert_not_awaited()+++async def test_a_trial_stripe_already_converted_is_saved_and_succeeds(+ pending_trial, live, boundaries+):+ """A retry after a conversion whose answer was lost: the plan the person+ asked for is already on, so it is saved and reported, never charged again."""+ live.update(status="active", cancel_at_period_end=False)+ converted = stripe.Subscription.construct_from(live, "test-key")+ boundaries.retrieve.side_effect = None+ boundaries.retrieve.return_value = converted++ assert await conversion.convert_cancel_pending_trial(pending_trial)++ boundaries.sync.assert_awaited_once_with(dict(converted))+ boundaries.modify.assert_not_awaited()+++async def test_canceled_trial_is_reconciled_and_refused(+ pending_trial, live, boundaries+):+ live["status"] = "canceled"+ canceled = stripe.Subscription.construct_from(live, "test-key")+ boundaries.retrieve.side_effect = None+ boundaries.retrieve.return_value = canceled++ with pytest.raises(conversion.TrialConversionRefused, match="has ended"):+ await conversion.convert_cancel_pending_trial(pending_trial)++ boundaries.sync.assert_awaited_once_with(dict(canceled))+ boundaries.expire.assert_not_awaited()+ boundaries.modify.assert_not_awaited()+++async def test_resumed_trial_is_refused_like_any_running_trial(+ pending_trial, live, boundaries+):+ live["cancel_at_period_end"] = False+ boundaries.retrieve.side_effect = None+ boundaries.retrieve.return_value = stripe.Subscription.construct_from(+ live, "test-key"+ )++ with pytest.raises(conversion.TrialConversionRefused) as refused:+ await conversion.convert_cancel_pending_trial(pending_trial)++ assert str(refused.value) == (+ "Your accepted plan starts after your trial. Manage the trial in billing."+ )+ boundaries.sync.assert_awaited_once()+ boundaries.expire.assert_not_awaited()+ boundaries.modify.assert_not_awaited()+++async def test_a_card_stripe_cannot_charge_sends_the_conversion_to_checkout(+ 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."""+ boundaries.card.return_value = False++ assert not await conversion.convert_cancel_pending_trial(pending_trial)++ boundaries.expire.assert_not_awaited()+ boundaries.modify.assert_not_awaited()+ boundaries.sync.assert_not_awaited()+++async def test_a_conversion_stripe_did_not_activate_is_saved_and_refused(+ pending_trial, live, boundaries+):+ canceled = stripe.Subscription.construct_from(+ {**live, "status": "canceled"}, "test-key"+ )+ boundaries.modify.side_effect = None+ boundaries.modify.return_value = canceled++ with pytest.raises(conversion.TrialConversionRefused, match="has ended"):+ await conversion.convert_cancel_pending_trial(pending_trial)++ boundaries.sync.assert_awaited_once_with(dict(canceled))+++async def test_a_failed_sync_after_the_charge_still_reports_the_conversion(+ pending_trial, boundaries+):+ """The card is charged and the plan is live in Stripe; its webhooks save+ 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)++ boundaries.modify.assert_awaited_once()+++async def test_a_busy_checkout_lock_is_a_retryable_conflict(pending_trial, boundaries):+ @asynccontextmanager+ async def busy(user_id: str):+ raise conversion.SubscriptionCheckoutUnavailable("busy")+ yield++ with patch.object(conversion, "subscription_checkout_lock", busy):+ with pytest.raises(conversion.TrialConversionRefused) as refused:+ await conversion.convert_cancel_pending_trial(pending_trial)++ assert str(refused.value) == "Your trial is already being updated. Please retry."+ boundaries.retrieve.assert_not_awaited()+ boundaries.modify.assert_not_awaited()++[email protected]("status", ["active", "trialing", "past_due", "incomplete"])+async def test_refuses_while_another_plan_is_live(+ pending_trial, live, boundaries, status+):+ """A plan bought through Checkout ends the trial when its webhook lands;+ converting first would bill the customer for both plans."""+ boundaries.others.side_effect = None+ boundaries.others.return_value = _subscriptions(+ live, {"id": "sub_max", "status": status}+ )++ with pytest.raises(conversion.TrialConversionRefused) as refused:+ await conversion.convert_cancel_pending_trial(pending_trial)++ assert str(refused.value) == (+ "Another plan is already active. Manage it in billing."+ )+ boundaries.expire.assert_awaited_once_with("cus_1")+ boundaries.modify.assert_not_awaited()+ boundaries.sync.assert_not_awaited()+++async def test_ended_plans_do_not_block_the_conversion(pending_trial, live, boundaries):+ boundaries.others.side_effect = None+ boundaries.others.return_value = _subscriptions(+ live,+ {"id": "sub_old", "status": "canceled"},+ {"id": "sub_abandoned", "status": "incomplete_expired"},+ )++ await conversion.convert_cancel_pending_trial(pending_trial)++ boundaries.modify.assert_awaited_once()+ boundaries.sync.assert_awaited_once_with(dict(boundaries.converted))+++def subscription_lookup():+ """The short-lived active-subscription lookup the status route reads."""+ lookup = credit._get_active_subscription_cached+ lookup.cache_delete("cus_1")+ yield lookup+ lookup.cache_delete("cus_1")+++async def test_conversion_refreshes_the_cached_subscription_lookup(+ pending_trial, live, boundaries, subscription_lookup+):+ """The status returned right after shows the paid period, not the trial's."""+ trialing = stripe.Subscription.construct_from(live, "test-key")+ with patch.object(+ credit,+ "_get_active_subscription",+ AsyncMock(side_effect=[trialing, boundaries.converted]),+ ):+ assert await subscription_lookup("cus_1") is trialing+ await conversion.convert_cancel_pending_trial(pending_trial)+ assert await subscription_lookup("cus_1") is boundaries.converted+++async def test_card_decline_leaves_the_trial_cancel_pending(pending_trial, boundaries):+ boundaries.modify.side_effect = stripe.CardError(+ "Your card was declined.", param="card", code="card_declined"+ )++ with pytest.raises(stripe.CardError):+ await conversion.convert_cancel_pending_trial(pending_trial)++ boundaries.sync.assert_not_awaited()+ assert boundaries.calls[-1] == "unlock"+++async def test_finds_a_live_cancel_pending_trial(pending_trial):+ with patch.object(+ conversion, "get_subscription_trial", AsyncMock(return_value=pending_trial)+ ):+ assert await conversion.get_cancel_pending_trial("user-1") == pending_trial+++ "change",+ [+ {"cancel_at_period_end": False},+ {"converted_at": datetime.now(UTC)},+ {"consumed_at": None},+ {"subscription_id": None},+ {"status": "canceled"},+ {"ends_at": datetime.now(UTC) - timedelta(minutes=1)},+ {"ends_at": None},+ ],+)+async def test_other_trials_are_not_cancel_pending(pending_trial, change):+ trial = pending_trial.model_copy(update=change)+ with patch.object(+ conversion, "get_subscription_trial", AsyncMock(return_value=trial)+ ):+ assert await conversion.get_cancel_pending_trial("user-1") is None+++async def test_no_trial_is_not_cancel_pending():+ with patch.object(+ conversion, "get_subscription_trial", AsyncMock(return_value=None)+ ):+ assert await conversion.get_cancel_pending_trial("user-1") is None+++ "tier,billing_cycle,expected",+ [+ (SubscriptionTier.PRO, "monthly", True),+ (SubscriptionTier.MAX, "monthly", False),+ (SubscriptionTier.PRO, "yearly", False),+ ],+)+def test_only_the_accepted_plan_converts_in_place(+ pending_trial, tier, billing_cycle, expected+):+ """The plan is matched on tier and cycle: the conversion bills the price+ the trial accepted, as the plan card shows, even after a re-price."""+ assert conversion.is_trial_plan(pending_trial, tier, billing_cycle) is expecteddiff --git a/autogpt_platform/backend/backend/data/subscription_trial_fulfillment_test.py b/autogpt_platform/backend/backend/data/subscription_trial_fulfillment_test.pyindex 501009964a..4313df5b85 100644--- a/autogpt_platform/backend/backend/data/subscription_trial_fulfillment_test.py+++ b/autogpt_platform/backend/backend/data/subscription_trial_fulfillment_test.py@@ -194,25 +194,6 @@ async def test_reused_identity_cancels_trial_before_granting_access(assert saved["consumedAt"] is not None[email protected]("changed_items", [False, True])-async def test_scheduled_portal_cancellation_ends_trial_immediately(- trial, subscription, boundaries, changed_items-):- subscription["cancel_at_period_end"] = True- if changed_items:- subscription["items"] = None- canceled = {**subscription, "status": "canceled", "cancel_at_period_end": False}- with patch.object(- fulfillment.stripe.Subscription,- "cancel_async",- AsyncMock(return_value=canceled),- ) as cancel:- result = await fulfillment._reconcile_locked(trial, "sub_1", boundaries)- assert result is not None and result[1] == SubscriptionTier.NO_TIER- cancel.assert_awaited_once()--@pytest.mark.asyncioasync def test_canceled_subscription_revokes_access_even_if_items_changed(trial, subscription, boundariesdiff --git a/autogpt_platform/backend/backend/data/subscription_trial_payment.py b/autogpt_platform/backend/backend/data/subscription_trial_payment.pyindex 1205f67d36..6ee644c812 100644--- a/autogpt_platform/backend/backend/data/subscription_trial_payment.py+++ b/autogpt_platform/backend/backend/data/subscription_trial_payment.py@@ -46,6 +46,23 @@ async def get_customer_default_payment_method(customer_id: str) -> PaymentMethodreturn customer.invoice_settings.default_payment_method+async def subscription_card_can_be_charged(subscription_id: str, now: datetime) -> bool:+ """Whether the trial's saved card is one Stripe can charge, by the same+ rule the reconcile grants trial access with."""+ snapshot = SubscriptionSnapshot.model_validate(+ await stripe_call(+ stripe.Subscription.retrieve_async,+ subscription_id,+ expand=["default_payment_method", "latest_invoice"],+ )+ )+ if snapshot.default_payment_method is None and snapshot.default_source is None:+ snapshot.customer_default_payment_method = (+ await get_customer_default_payment_method(snapshot.customer)+ )+ return snapshot.has_verified_card(now)++class Invoice(BaseModel):id: strstatus: str | None = Nonediff --git a/autogpt_platform/backend/backend/data/subscription_trial_stripe.py b/autogpt_platform/backend/backend/data/subscription_trial_stripe.pyindex 480e7b5279..70f7101aae 100644--- a/autogpt_platform/backend/backend/data/subscription_trial_stripe.py+++ b/autogpt_platform/backend/backend/data/subscription_trial_stripe.py@@ -8,6 +8,7 @@ from prisma.enums import SubscriptionTierfrom backend.data.db import query_raw_with_schema, transactionfrom backend.data.stripe_client import stripe_call, stripe_list_items+from backend.data.subscription_checkout import other_plan_has_accessfrom backend.data.subscription_trial import TrialState, get_subscription_trialfrom backend.data.subscription_trial_claims import claim_trial_identitiesfrom backend.data.subscription_trial_payment import Invoice as Invoice@@ -17,6 +18,10 @@ from backend.data.subscription_trial_payment import (from backend.data.subscription_trial_payment import get_customer_default_payment_methodfrom backend.data.subscription_trial_rejection import TrialRejectionReason+# Our clock may trail Stripe's: a trial Stripe ended "now" can read as ending+# a moment from now here.+STRIPE_CLOCK_SKEW_SECONDS = 300+async def reconcile_trial_subscription(user_id: str, subscription_id: str@@ -84,7 +89,7 @@ async def _reconcile_locked(rejection_reason = TrialRejectionReason.CARD_VERIFICATION_FAILEDelif not await claim_trial_identities(trial, fingerprint, tx):rejection_reason = TrialRejectionReason.INTRO_OFFER_ALREADY_USED- if snapshot.cancel_at_period_end or rejection_reason:+ if rejection_reason or await _ends_scheduled_cancellation_now(trial, snapshot):cancel_params: stripe.Subscription.CancelParams = {"invoice_now": False,"prorate": False,@@ -141,6 +146,21 @@ async def _reconcile_locked(return dict(raw), tier+async def _ends_scheduled_cancellation_now(+ trial: TrialState, snapshot: SubscriptionSnapshot+) -> bool:+ """A cancel-pending trial keeps its access until Stripe ends it at trial_end.++ A plan bought meanwhile ends it now, so TRIAL never overwrites that plan if+ its stale-subscription cleanup failed. So do items changed off the accepted+ price: the reconcile refuses an unconverted trial on any other price."""+ if not snapshot.cancel_at_period_end:+ return False+ if not snapshot.has_accepted_price(trial.offer):+ return True+ return await other_plan_has_access(trial.customer_id, snapshot.id)++async def _completed_card_checkout(trial: TrialState, subscription_id: str, tx: Prisma) -> bool:@@ -195,13 +215,17 @@ def trial_subscription_tier(if end is None:return SubscriptionTier.NO_TIERif subscription.status == "trialing" and end > now.timestamp():- if subscription.has_verified_card(now):+ # A cancel-pending trial is never charged, so the card verified at its+ # start holds even if it expires before trial_end.+ if subscription.has_verified_card(now) or (+ subscription.cancel_at_period_end and trial.card_verified_at is not None+ ):return SubscriptionTier.TRIALreturn SubscriptionTier.NO_TIERinvoice = subscription.latest_invoiceif (subscription.status == "active"- and end <= now.timestamp()+ and end <= now.timestamp() + STRIPE_CLOCK_SKEW_SECONDSand invoice is not Noneand invoice.status == "paid"and invoice.created >= enddiff --git a/autogpt_platform/backend/backend/data/subscription_trial_tier_skew_test.py b/autogpt_platform/backend/backend/data/subscription_trial_tier_skew_test.pynew file mode 100644index 0000000000..187d47b0dc--- /dev/null+++ b/autogpt_platform/backend/backend/data/subscription_trial_tier_skew_test.py@@ -0,0 +1,72 @@+"""A trial Stripe has just ended converts even when Stripe's clock runs a+little ahead of ours, as long as its post-trial invoice is paid."""++from datetime import UTC, datetime++import pytest+from prisma.enums import SubscriptionTier++from backend.data import subscription_trial_checkout_test as checkout_test+from backend.data.subscription_trial_stripe import (+ STRIPE_CLOCK_SKEW_SECONDS,+ SubscriptionSnapshot,+ trial_subscription_tier,+)++trial = checkout_test.trial+++ "end_delta,invoice_status,reason,created_delta,expected",+ [+ (60, "paid", "subscription_update", 0, SubscriptionTier.PRO),+ (+ STRIPE_CLOCK_SKEW_SECONDS,+ "paid",+ "subscription_update",+ 0,+ SubscriptionTier.PRO,+ ),+ (+ STRIPE_CLOCK_SKEW_SECONDS + 1,+ "paid",+ "subscription_update",+ 0,+ SubscriptionTier.NO_TIER,+ ),+ (60, "open", "subscription_update", 0, SubscriptionTier.NO_TIER),+ (60, "paid", "subscription_create", 0, SubscriptionTier.NO_TIER),+ (60, "paid", "subscription_update", -1, SubscriptionTier.NO_TIER),+ ],+ ids=[+ "ended-a-minute-ahead",+ "ended-at-the-skew-limit",+ "beyond-the-skew-limit",+ "unpaid",+ "first-invoice",+ "invoice-before-end",+ ],+)+def test_trial_stripe_just_ended_converts_despite_clock_skew(+ trial, end_delta, invoice_status, reason, created_delta, expected+):+ """Ending a trial "now" stamps Stripe's clock, which can run ahead of ours:+ status active already means Stripe ended the trial, and the paid post-trial+ invoice stays the real guard."""+ now = datetime(2026, 9, 10, tzinfo=UTC)+ end = int(now.timestamp()) + end_delta+ subscription = SubscriptionSnapshot.model_validate(+ {+ "id": "sub_1",+ "customer": "cus_1",+ "status": "active",+ "trial_end": end,+ "latest_invoice": {+ "id": "in_1",+ "status": invoice_status,+ "billing_reason": reason,+ "created": end + created_delta,+ },+ }+ )+ assert trial_subscription_tier(trial, subscription, now) == expecteddiff --git a/autogpt_platform/backend/backend/notifications/lifecycle_trial_conversion_test.py b/autogpt_platform/backend/backend/notifications/lifecycle_trial_conversion_test.pynew file mode 100644index 0000000000..f268639932--- /dev/null+++ b/autogpt_platform/backend/backend/notifications/lifecycle_trial_conversion_test.py@@ -0,0 +1,95 @@+"""Billing lifecycle emails for a trial's own subscription: converting a+cancel-pending trial early is not a paid resume, a trial-era cancel or resume+handled after the conversion is not a paid one either, while a converted+trial that is canceled later is a paid cancellation."""++from datetime import datetime, timezone+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from prisma.enums import NotificationType++from backend.notifications import lifecycle, lifecycle_test, trial_test+from backend.notifications.lifecycle_test import _run, _subscription, _User++trial = trial_test.trial+fields_on = lifecycle_test.fields_on+++def _trial_subscription(**over) -> dict:+ return _subscription(+ **{+ "status": "active",+ "metadata": {"trial_enrollment_id": "trial-1", "user_id": "user-1"},+ **over,+ }+ )+++async def _run_converted(trial, coro_factory):+ converted = trial.model_copy(update={"converted_at": datetime.now(timezone.utc)})+ trials = MagicMock(get_subscription_trial=AsyncMock(return_value=converted))+ with patch("backend.notifications.trial.credit_db", return_value=trials):+ return await _run(coro_factory, _User())+++async def test_converting_a_cancel_pending_trial_early_is_not_a_paid_resume(+ trial, fields_on+):+ """Subscribe now on a cancel-pending trial ends the trial and clears its+ cancellation in one update. The trial's conversion notice covers it."""+ calls = await _run_converted(+ trial,+ lambda: lifecycle.on_subscription_updated(+ _trial_subscription(),+ {"cancel_at_period_end": True, "status": "trialing"},+ ),+ )+ calls["claim"].assert_not_awaited()+ calls["notify"].assert_not_awaited()+ fields_on.assert_not_awaited()+++async def test_a_converted_trial_canceled_later_is_a_paid_cancellation(trial):+ calls = await _run_converted(+ trial,+ lambda: lifecycle.on_subscription_updated(+ _trial_subscription(cancel_at_period_end=True, canceled_at=1789100000),+ {"cancel_at_period_end": False},+ ),+ )+ queued = calls["notify"].await_args.args[0]+ assert queued.type is NotificationType.SUBSCRIPTION_CANCELLED+++ "now_pending, previous",+ [+ (True, {"cancel_at_period_end": False, "canceled_at": None}),+ (False, {"cancel_at_period_end": True, "canceled_at": 1789100000}),+ ],+ ids=["cancel", "resume"],+)+async def test_a_trial_era_flip_handled_after_conversion_sends_nothing(+ trial, fields_on, now_pending, previous+):+ """A cancel or resume from the trial, retried or delivered late, lands+ after the person converted. Its payload still says trialing; a paying+ customer must not get a paid "cancelled" or "resumed" email."""+ calls = await _run_converted(+ trial,+ lambda: lifecycle.on_subscription_updated(+ _trial_subscription(+ status="trialing",+ cancel_at_period_end=now_pending,+ canceled_at=1789100000 if now_pending else None,+ ),+ previous,+ ),+ )+ calls["claim"].assert_not_awaited()+ calls["notify"].assert_not_awaited()+ fields_on.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/notifications/templates/_trial_copy.j2 b/autogpt_platform/backend/backend/notifications/templates/_trial_copy.j2index 983b80a055..8f85a59b62 100644--- a/autogpt_platform/backend/backend/notifications/templates/_trial_copy.j2+++ b/autogpt_platform/backend/backend/notifications/templates/_trial_copy.j2@@ -2,5 +2,5 @@Hi {{ user_name }}, {% if kind == 'started' %}your card is set up and your trial is ready.{% elif kind == 'ending' %}your trial ends on {{ ends_label }}.{% elif kind == 'canceled' %}your trial will not convert to a paid plan.{% elif kind == 'resumed' %}your trial cancellation has been removed.{% elif kind == 'converted' %}your trial has ended, your payment is confirmed, and your {{ plan.name }} plan is active.{% elif kind == 'payment_failed' %}we couldn't complete the payment after your trial.{% else %}your trial access has ended.{% endif %} {{ preheader }}{%- endmacro %}{% macro detail() -%}-{% if kind == 'started' %}Pick a real task, connect the accounts it needs, and give AutoGPT a first run. Unless you cancel before {{ ends_label }}, your plan starts automatically at {{ plan.price_display }}. Applicable tax may be added. Trial access is subject to your trial allowance.{% elif kind in ['ending', 'resumed'] %}Applicable tax may be added. Review your plan or cancel in billing settings before {{ ends_label }}.{% elif kind == 'payment_failed' %}Update your card or complete any verification requested by your bank in billing settings.{% elif kind == 'ended' %}Review your plan and payment status in billing settings if you'd like to continue.{% endif %}+{% if kind == 'started' %}Pick a real task, connect the accounts it needs, and give AutoGPT a first run. Unless you cancel before {{ ends_label }}, your plan starts automatically at {{ plan.price_display }}. Applicable tax may be added. Trial access is subject to your trial allowance.{% elif kind in ['ending', 'resumed'] %}Applicable tax may be added. Review your plan or cancel in billing settings before {{ ends_label }}.{% elif kind == 'canceled' %}You keep full access until {{ ends_label }}. Resume your trial any time before then in billing settings.{% elif kind == 'payment_failed' %}Update your card or complete any verification requested by your bank in billing settings.{% elif kind == 'ended' %}Review your plan and payment status in billing settings if you'd like to continue.{% endif %}{%- endmacro %}diff --git a/autogpt_platform/backend/backend/notifications/templates/trial.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/trial.subject.j2index 4b0fedfde1..5bd40d31cd 100644--- a/autogpt_platform/backend/backend/notifications/templates/trial.subject.j2+++ b/autogpt_platform/backend/backend/notifications/templates/trial.subject.j2@@ -3,7 +3,7 @@ Your trial allowance is available until {{ ends_label }}.{% elif kind == 'ending' %}Your AutoGPT trial ends on {{ ends_label }}Unless you cancel before then, your saved card will be charged for your {{ plan.name }} plan at {{ plan.price_display }}.{% elif kind == 'canceled' %}Your AutoGPT trial cancellation is confirmed-You can keep using your remaining trial allowance until {{ ends_label }}.+Your card won't be charged.{% elif kind == 'resumed' %}Your AutoGPT trial will continue into your planYour saved card will be charged for your {{ plan.name }} plan on {{ ends_label }} at {{ plan.price_display }}.{% elif kind == 'converted' %}Your AutoGPT {{ plan.name }} plan is activediff --git a/autogpt_platform/backend/backend/notifications/trial.py b/autogpt_platform/backend/backend/notifications/trial.pyindex f35d023f50..8dda419973 100644--- a/autogpt_platform/backend/backend/notifications/trial.py+++ b/autogpt_platform/backend/backend/notifications/trial.py@@ -19,13 +19,14 @@ from backend.data.notifications import (SubscriptionPlan,TrialUpdateData,)-from backend.data.stripe_client import stripe_call+from backend.data.stripe_client import stripe_call, stripe_list_itemsfrom backend.data.subscription_trial import TrialStatefrom backend.notifications.dedupe import claim_once, release_claimfrom backend.notifications.lifecycle_plan import format_amountfrom backend.notifications.queue import queue_notification_asyncfrom backend.notifications.trial_audience import (join_paying_audience,+ leave_trial_group,queue_trial_audience_change,)from backend.util.posthog_events import PostHogEvent@@ -82,6 +83,9 @@ async def notify_trial(subscription: dict, kind: TrialNoticeKind) -> bool:if not _notice_applies(trial, kind, current):return Trueuser = await user_db().get_user_by_id(user_id)+ if kind == "ended" and await _another_plan_is_live(trial, current):+ await leave_trial_group(user)+ return Truedata = trial_notice_data(trial, kind, user.name or "there")claim = trial_notice_key(trial, kind)data.notice_key = claim@@ -197,8 +201,17 @@ async def on_trial_subscription_updated(subscription: dict, previous: dict) -> bif not user_id:raise ValueError("Trial update has no user identity")trial = await credit_db().get_subscription_trial(user_id)- if trial is None or trial.converted_at is not None:+ if trial is None:return False+ if trial.converted_at is not None:+ # A payload still trialing is a trial-era cancel or resume handled+ # after the conversion. Subscribe now on a cancel-pending trial ends+ # the trial and clears the cancellation in one update. The trial's own+ # notices cover both; only later flips are paid news.+ if subscription.get("status") == "trialing":+ return True+ was_trialing = previous.get("status") == "trialing"+ return was_trialing and "cancel_at_period_end" in previousif "cancel_at_period_end" in previous:kind = "canceled" if trial.cancel_at_period_end else "resumed"await notify_trial(subscription, kind)@@ -257,7 +270,12 @@ def _notice_applies(trial: TrialState, kind: TrialNoticeKind, current: dict) ->and not current.get("cancel_at_period_end"))if kind == "canceled":- return in_trial and bool(current.get("cancel_at_period_end"))+ # It promises access until trial_end, which only a verified card gives.+ return (+ in_trial+ and trial.card_verified_at is not None+ and bool(current.get("cancel_at_period_end"))+ )if kind == "converted":return status == "active" and trial.converted_at is not Noneif kind == "payment_failed":@@ -266,3 +284,20 @@ def _notice_applies(trial: TrialState, kind: TrialNoticeKind, current: dict) ->and trial.converted_at is None)return status in ("canceled", "unpaid", "paused") and trial.converted_at is None+++async def _another_plan_is_live(trial: TrialState, current: dict) -> bool:+ """A trial ended by buying another plan is not news, and its trial_canceled+ status must not overwrite the new plan's. The person still leaves the+ trial group."""+ for status in ("active", "trialing"):+ page = await stripe_call(+ stripe.Subscription.list_async,+ customer=trial.customer_id,+ status=status,+ limit=100,+ )+ async for other in stripe_list_items(page):+ if other.id != current.get("id"):+ return True+ return Falsediff --git a/autogpt_platform/backend/backend/notifications/trial_audience.py b/autogpt_platform/backend/backend/notifications/trial_audience.pyindex 18880233e8..ed1b8b14aa 100644--- a/autogpt_platform/backend/backend/notifications/trial_audience.py+++ b/autogpt_platform/backend/backend/notifications/trial_audience.py@@ -3,7 +3,9 @@Every transition in and out of a trial already produces exactly one trialnotice, deduped by its own claim, so the group change rides on that notice:join on start and on un-cancel, leave on cancel, conversion, failed conversion-and end. The backend owns both edges of this group (see `mailerlite.py`).+and end. A trial ended by buying another plan sends no notice, so it leaves+the group on its own. The backend owns both edges of this group (see+`mailerlite.py`).A conversion is also the customer's first paid subscription, so it joins thepaying audience the way a first checkout does.@@ -62,9 +64,25 @@ async def queue_trial_audience_change(settings: only the notification service holds them."""action = _TRIAL_GROUP_CHANGES.get(kind)- if action is None or not audience_change_allowed(user, action):+ if action is None:+ return+ await _queue_group_change(action, user, _TRIAL_FIELDS[kind](subscription))+++async def leave_trial_group(user: MarketingContact) -> None:+ """The trial ended because another plan was bought: leave the trial group+ without writing any fields, so that plan's status and dates stay.++ No notice or claim rides on it: a repeated removal changes nothing. Raises+ when it cannot be queued, so Stripe retries the event."""+ await _queue_group_change(AudienceAction.REMOVE_TRIAL, user, None)+++async def _queue_group_change(+ action: AudienceAction, user: MarketingContact, fields: Fields | None+) -> None:+ if not audience_change_allowed(user, action):return- fields = _TRIAL_FIELDS[kind](subscription)event = audience_event(action, user.email, user.id, fields)if event is None:returndiff --git a/autogpt_platform/backend/backend/notifications/trial_audience_cancel_test.py b/autogpt_platform/backend/backend/notifications/trial_audience_cancel_test.pynew file mode 100644index 0000000000..39c20527d0--- /dev/null+++ b/autogpt_platform/backend/backend/notifications/trial_audience_cancel_test.py@@ -0,0 +1,151 @@+"""The MailerLite trial group across a scheduled cancellation: each cancel or+resume flip moves the group once, a pending cancellation that runs out leaves+it as trial canceled, a trial ended by buying another plan still leaves the+group without touching that plan's status, and no ending reminder goes out+while it is pending."""++from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock++import pytest++from backend.data.notifications import (+ AudienceAction,+ NotificationResult,+ SubscriberField,+ SubscriptionStatus,+)+from backend.notifications import trial_audience_test+from backend.notifications.trial_audience_test import _notify, _state++trial = trial_audience_test.trial+++def _claims(keys: set[str]) -> AsyncMock:+ """Redis SET NX: each key is claimed once."""++ async def claim(key: str) -> bool:+ fresh = key not in keys+ keys.add(key)+ return fresh++ return AsyncMock(side_effect=claim)+++async def _flip(trial, kind, revision, keys, audience):+ state, raw = _state(+ trial.model_copy(+ update={+ "cancel_at_period_end": kind == "canceled",+ "notification_revision": revision,+ }+ ),+ kind,+ )+ _, notice, _ = await _notify(+ state, raw, kind, audience=audience, claim_once=_claims(keys)+ )+ return notice.await_count+++async def test_a_second_cancel_at_the_same_revision_queues_once(trial):+ keys: set[str] = set()+ audience = AsyncMock(return_value=NotificationResult(success=True))+ sent = [await _flip(trial, "canceled", rev, keys, audience) for rev in (3, 3, 4)]+ assert sent == [1, 0, 1]+ assert [c.args[0].action for c in audience.await_args_list] == [+ AudienceAction.REMOVE_TRIAL,+ AudienceAction.REMOVE_TRIAL,+ ]+ assert keys == {"trial:trial-1:canceled:3", "trial:trial-1:canceled:4"}+++async def test_each_cancel_or_resume_flip_moves_the_group_once(trial):+ """Each flip bumps the revision once, so a replayed webhook for the same+ flip changes nothing and the next flip gets its own notice."""+ keys: set[str] = set()+ audience = AsyncMock(return_value=NotificationResult(success=True))+ flips = [("canceled", 1), ("canceled", 1), ("resumed", 2), ("resumed", 2)]+ sent = [await _flip(trial, kind, rev, keys, audience) for kind, rev in flips]+ assert sent == [1, 0, 1, 0]+ events = [c.args[0] for c in audience.await_args_list]+ assert [(e.action, e.fields[SubscriberField.STATUS]) for e in events] == [+ (AudienceAction.REMOVE_TRIAL, SubscriptionStatus.TRIAL_CANCELED.value),+ (AudienceAction.ADD_TRIAL, SubscriptionStatus.IN_TRIAL.value),+ ]+++async def test_a_cancel_pending_trial_that_runs_out_leaves_the_group_as_trial_canceled(+ trial,+):+ pending = trial.model_copy(+ update={"cancel_at_period_end": True, "status": "canceled"}+ )+ pending, raw = _state(pending, "ended")+ raw["cancel_at_period_end"] = True+ audience = AsyncMock(return_value=NotificationResult(success=True))+ got, notice, _ = await _notify(pending, raw, "ended", audience=audience)+ assert got == [AudienceAction.REMOVE_TRIAL]+ status = audience.await_args.args[0].fields[SubscriberField.STATUS]+ assert status == SubscriptionStatus.TRIAL_CANCELED.value+ notice.assert_awaited_once()+++async def test_no_ending_reminder_while_the_cancellation_is_pending(trial):+ pending, raw = _state(+ trial.model_copy(update={"cancel_at_period_end": True}), "canceled"+ )+ raw["trial_end"] = int((datetime.now(UTC) + timedelta(days=1)).timestamp())+ claim = AsyncMock(return_value=True)+ got, notice, _ = await _notify(pending, raw, "ending", claim_once=claim)+ assert got == []+ notice.assert_not_awaited()+ claim.assert_not_awaited()+++async def _end_under_another_plan(trial, pending: bool, **kwargs):+ ended, raw = _state(+ trial.model_copy(update={"cancel_at_period_end": pending}), "ended"+ )+ raw["cancel_at_period_end"] = pending+ claim = AsyncMock(return_value=True)+ got, notice, release = await _notify(+ ended, raw, "ended", others=("sub_max",), claim_once=claim, **kwargs+ )+ claim.assert_not_awaited()+ notice.assert_not_awaited()+ release.assert_not_awaited()+ return got+++ "pending", [True, False], ids=["cancel-pending", "ended-immediately"]+)+async def test_a_trial_ended_by_another_plan_still_leaves_the_trial_group(+ trial, pending+):+ """Its "ended" notice is not sent and the new plan's status must stay,+ but the person is no longer on a trial. That holds whether the trial was+ set to cancel at its end or (flag off) ended at once."""+ audience = AsyncMock(return_value=NotificationResult(success=True))+ got = await _end_under_another_plan(trial, pending, audience=audience)+ assert got == [AudienceAction.REMOVE_TRIAL]+ assert audience.await_args.args[0].fields == {}+++async def test_an_opted_out_trialist_ended_by_another_plan_queues_nothing(trial):+ got = await _end_under_another_plan(trial, True, opted_out_at=datetime.now(UTC))+ assert got == []+++async def test_a_group_exit_that_cannot_be_queued_fails_so_stripe_retries(trial):+ failing = AsyncMock(return_value=NotificationResult(success=False, message="down"))+ got = await _end_under_another_plan(trial, True, audience=failing, raises=True)+ assert got == [AudienceAction.REMOVE_TRIAL]diff --git a/autogpt_platform/backend/backend/notifications/trial_audience_test.py b/autogpt_platform/backend/backend/notifications/trial_audience_test.pyindex c518faa9be..f385f1fc72 100644--- a/autogpt_platform/backend/backend/notifications/trial_audience_test.py+++ b/autogpt_platform/backend/backend/notifications/trial_audience_test.py@@ -99,6 +99,19 @@ def _state(trial: TrialState, kind: str) -> tuple[TrialState, dict]:return trial, raw+def _stripe(raw: dict, others: tuple[str, ...] = ()) -> AsyncMock:+ """The live subscription, on a customer whose only other live+ subscriptions are `others` (none by default)."""++ async def call(fn, *args, **kwargs):+ if fn == notices.stripe.Subscription.list_async:+ data = [SimpleNamespace(id=sub_id) for sub_id in others]+ return SimpleNamespace(data=data, has_more=False)+ return raw++ return AsyncMock(side_effect=call)++async def _notify(trial,raw,@@ -113,6 +126,8 @@ async def _notify(opted_out_at=None,user=None,timezone="America/Chicago",+ claim_once=None,+ others: tuple[str, ...] = (),):audience = audience or AsyncMock(return_value=NotificationResult(success=True))notice = AsyncMock(return_value=NotificationResult(success=True))@@ -128,7 +143,7 @@ async def _notify(claim_welcome_email=claim_welcome or AsyncMock(return_value=not welcomed),)with (- patch.object(notices, "stripe_call", AsyncMock(return_value=raw)),+ patch.object(notices, "stripe_call", _stripe(raw, others)),patch.object(notices,"credit_db",@@ -138,7 +153,9 @@ async def _notify(),patch.object(notices, "user_db", return_value=users),patch.object(trial_audience, "user_db", return_value=users),- patch.object(notices, "claim_once", AsyncMock(return_value=claimed)),+ patch.object(+ notices, "claim_once", claim_once or AsyncMock(return_value=claimed)+ ),patch.object(notices, "release_claim", AsyncMock()) as release,patch.object(notices, "queue_notification_async", notice),patch.object(trial_audience, "queue_audience_change", audience),diff --git a/autogpt_platform/backend/backend/notifications/trial_cancel_notice_test.py b/autogpt_platform/backend/backend/notifications/trial_cancel_notice_test.pynew file mode 100644index 0000000000..c8067df447--- /dev/null+++ b/autogpt_platform/backend/backend/notifications/trial_cancel_notice_test.py@@ -0,0 +1,163 @@+"""Trial notices around a scheduled cancellation: the canceled email keeps+access until the trial ends, and each cancel or resume flip sends the notice+for the trial's current state, never for one that has already converted."""++from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from prisma.enums import NotificationType++from backend.data.subscription_trial import TrialState+from backend.notifications import trial as notices+from backend.notifications import trial_test+from backend.notifications.renderer import render++trial = trial_test.trial+urls = trial_test.urls+++def test_canceled_notice_keeps_access_until_the_trial_ends(trial, urls):+ data = notices.trial_notice_data(trial, "canceled", "Sam")+ email = render(NotificationType.TRIAL_UPDATE, data, "[email protected]", urls)+ assert email.subject == "Your AutoGPT trial cancellation is confirmed"+ assert email.preheader == "Your card won't be charged."+ line = (+ f"You keep full access until {data.ends_label}. "+ "Resume your trial any time before then in billing settings."+ )+ for body in (email.html, email.text):+ assert line in body+ assert "immediately" not in body+++def test_resumed_notice_copy_is_unchanged(trial, urls):+ data = notices.trial_notice_data(trial, "resumed", "Sam")+ email = render(NotificationType.TRIAL_UPDATE, data, "[email protected]", urls)+ assert email.subject == "Your AutoGPT trial will continue into your plan"+ assert email.preheader == (+ "Your saved card will be charged for your Pro plan on "+ f"{data.ends_label} at $20.00 USD / month."+ )+ assert (+ "Applicable tax may be added. Review your plan or cancel in billing "+ f"settings before {data.ends_label}."+ ) in email.text+ assert "You keep full access" not in email.text+++def _trial_subscription(trial: TrialState, **over) -> dict:+ return {+ "id": trial.subscription_id,+ "customer": trial.customer_id,+ "metadata": {"trial_enrollment_id": trial.id, "user_id": trial.user_id},+ **over,+ }+++async def _on_update(trial: TrialState, previous: dict, **payload):+ with (+ patch.object(+ notices,+ "credit_db",+ return_value=MagicMock(+ get_subscription_trial=AsyncMock(return_value=trial)+ ),+ ),+ patch.object(notices, "notify_trial", AsyncMock(return_value=True)) as notify,+ ):+ handled = await notices.on_trial_subscription_updated(+ _trial_subscription(trial, **payload), previous+ )+ return handled, notify++[email protected]("pending, kind", [(True, "canceled"), (False, "resumed")])+async def test_a_cancel_flip_sends_the_notice_for_the_current_state(+ trial, pending, kind+):+ trial.cancel_at_period_end = pending+ handled, notify = await _on_update(trial, {"cancel_at_period_end": not pending})+ assert handled+ notify.assert_awaited_once_with(_trial_subscription(trial), kind)+++async def test_an_unrelated_trial_update_sends_nothing(trial):+ handled, notify = await _on_update(trial, {"items": {"data": []}})+ assert handled+ notify.assert_not_awaited()+++async def test_converting_early_from_a_pending_cancellation_is_not_a_resume(trial):+ """Subscribe now ends the trial and clears its pending cancellation in one+ update. The conversion notice covers it; no paid "resumed" email."""+ converted = trial.model_copy(update={"converted_at": datetime.now(UTC)})+ handled, notify = await _on_update(+ converted, {"cancel_at_period_end": True, "status": "trialing"}+ )+ assert handled+ notify.assert_not_awaited()+++ "pending, previous",+ [+ (True, {"cancel_at_period_end": False, "canceled_at": None}),+ (False, {"cancel_at_period_end": True, "canceled_at": 1789100000}),+ ],+ ids=["cancel", "resume"],+)+async def test_a_trial_era_flip_handled_after_conversion_is_not_paid_news(+ trial, pending, previous+):+ """A cancel or resume made during the trial, retried or delivered after+ the conversion, still describes the trial: no paid email, no notice."""+ converted = trial.model_copy(update={"converted_at": datetime.now(UTC)})+ handled, notify = await _on_update(+ converted, previous, status="trialing", cancel_at_period_end=pending+ )+ assert handled+ notify.assert_not_awaited()+++ "previous",+ [{"cancel_at_period_end": False}, {"status": "trialing"}, {"items": {}}],+)+async def test_a_converted_trial_is_left_to_the_paid_lifecycle(trial, previous):+ converted = trial.model_copy(update={"converted_at": datetime.now(UTC)})+ handled, notify = await _on_update(converted, previous)+ assert not handled+ notify.assert_not_awaited()++[email protected]("verified", [True, False])+def test_the_canceled_notice_needs_the_card_that_keeps_access(trial, verified):+ """It promises full access until trial_end, which a trial whose card+ stopped verifying no longer has."""+ trial = trial.model_copy(+ update={"card_verified_at": datetime.now(UTC) if verified else None}+ )+ raw = {+ "status": "trialing",+ "trial_end": int((datetime.now(UTC) + timedelta(days=3)).timestamp()),+ "cancel_at_period_end": True,+ }+ assert notices._notice_applies(trial, "canceled", raw) is verified+++def test_an_early_conversion_seen_before_its_invoice_is_not_a_resume(trial):+ """If the conversion's update lands before the trial is marked converted,+ the flip routes to "resumed", which no longer applies: Stripe already+ ended the trial."""+ raw = {+ "status": "active",+ "trial_end": int(datetime.now(UTC).timestamp()),+ "cancel_at_period_end": False,+ }+ assert not notices._notice_applies(trial, "resumed", raw)diff --git a/autogpt_platform/backend/backend/notifications/trial_notice_freshness_test.py b/autogpt_platform/backend/backend/notifications/trial_notice_freshness_test.pyindex 839c072b6a..10ea1fc1b3 100644--- a/autogpt_platform/backend/backend/notifications/trial_notice_freshness_test.py+++ b/autogpt_platform/backend/backend/notifications/trial_notice_freshness_test.py@@ -1,8 +1,10 @@from datetime import UTC, datetime, timedelta+from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+from backend.data.notifications import NotificationResultfrom backend.notifications import trial as noticesfrom backend.notifications import trial_test as fixtures@@ -166,3 +168,101 @@ async def test_delivery_marks_changed_terms_obsolete_without_sending(trial):),):assert await notices.trial_notice_disposition(trial.user_id, data) == "obsolete"+++async def _notify_ended(trial, others: dict[str, list[str]]):+ """`others` maps a Stripe status to the customer's subscription ids in it;+ the list double honours the status filter the way Stripe does."""+ raw = subscription(trial)++ async def stripe_call(fn, *args, **kwargs):+ if fn != notices.stripe.Subscription.list_async:+ return raw+ assert kwargs["customer"] == trial.customer_id+ status = kwargs["status"]+ ids = [+ sub_id+ for key, subs in others.items()+ if status in (key, "all")+ for sub_id in subs+ ]+ return SimpleNamespace(+ data=[SimpleNamespace(id=sub_id) for sub_id in ids], has_more=False+ )++ user = SimpleNamespace(id=trial.user_id, name="Sam", email="[email protected]")+ with (+ patch.object(notices, "stripe_call", AsyncMock(side_effect=stripe_call)),+ patch.object(+ notices,+ "credit_db",+ return_value=MagicMock(+ get_subscription_trial=AsyncMock(return_value=trial)+ ),+ ),+ patch.object(+ notices,+ "user_db",+ return_value=MagicMock(get_user_by_id=AsyncMock(return_value=user)),+ ),+ patch.object(notices, "claim_once", AsyncMock(return_value=True)) as claim,+ patch.object(notices, "queue_trial_audience_change", AsyncMock()) as audience,+ patch.object(notices, "leave_trial_group", AsyncMock()) as leave,+ patch.object(+ notices,+ "queue_notification_async",+ AsyncMock(return_value=NotificationResult(success=True)),+ ) as queue,+ patch.object(notices, "_track_billing_event") as track,+ ):+ handled = await notices.notify_trial(raw, "ended")+ return handled, SimpleNamespace(+ claim=claim, audience=audience, leave=leave, queue=queue, track=track, user=user+ )+++ "others",+ [{"active": ["sub_max"]}, {"trialing": ["sub_other"]}],+ ids=["active-plan", "trialing-plan"],+)+async def test_a_trial_ended_by_buying_another_plan_sends_nothing(trial, others):+ """Buying another plan while cancel-pending ends the trial subscription.+ No "trial ended" email, no trial_canceled overwrite of the new plan's+ MailerLite status, no trial_ended event. The person still leaves the+ MailerLite trial group."""+ trial.status = "canceled"+ trial.cancel_at_period_end = True+ handled, sent = await _notify_ended(trial, others)+ assert handled+ sent.leave.assert_awaited_once_with(sent.user)+ sent.claim.assert_not_awaited()+ sent.audience.assert_not_awaited()+ sent.queue.assert_not_awaited()+ sent.track.assert_not_called()+++ "others",+ [+ {},+ {"active": ["sub_1"], "trialing": ["sub_1"]},+ {"canceled": ["sub_old"], "past_due": ["sub_due"]},+ ],+ ids=["no-other-plan", "only-itself", "none-live"],+)+async def test_a_cancel_pending_trial_reaching_its_end_sends_the_ended_notice(+ trial, others+):+ trial.status = "canceled"+ trial.cancel_at_period_end = True+ handled, sent = await _notify_ended(trial, others)+ assert handled+ sent.leave.assert_not_awaited()+ sent.audience.assert_awaited_once()+ assert sent.audience.await_args.args[0] == "ended"+ sent.queue.assert_awaited_once()+ assert sent.queue.await_args.args[0].data.kind == "ended"+ assert sent.track.call_args.args[0] == "trial_ended"diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsxindex 09b6c9fd86..e31aed2b4f 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx@@ -284,7 +284,11 @@ test("preserves active-trial status and confirmed cancellation", async () => {screen.queryByRole("button", { name: "Start 7-day trial" }),).toBeNull();expect(cancel).not.toHaveBeenCalled();- fireEvent.click(await screen.findByRole("button", { name: "End trial now" }));+ fireEvent.click(+ within(+ await screen.findByRole("dialog", { name: "Cancel your trial?" }),+ ).getByRole("button", { name: "Cancel trial" }),+ );await screen.findByText(/Cancellation confirmed/);expect(cancel).toHaveBeenCalledOnce();expect(screen.getByText("Your trial has ended")).toBeDefined();diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-account-switch.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-account-switch.test.tsxindex 6e492a7059..4e66a119c9 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-account-switch.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-account-switch.test.tsx@@ -1,6 +1,7 @@import {getGetTrialsGetTrialStatusMockHandler200,getPostTrialsCancelTrialMockHandler200,+ getPostTrialsResumeTrialMockHandler200,getPostTrialsStartTrialCheckoutMockHandler200,} from "@/app/api/__generated__/endpoints/trials/trials.msw";import type { TrialCheckoutResponse } from "@/app/api/__generated__/models/trialCheckoutResponse";@@ -13,6 +14,7 @@ import {render,screen,waitFor,+ within,} from "@/tests/integrations/test-utils";import {deferredTrialResponse,@@ -109,7 +111,9 @@ describe("trial account isolation", () => {await screen.findByRole("button", { name: "Cancel trial" }),);fireEvent.click(- await screen.findByRole("button", { name: "End trial now" }),+ within(+ await screen.findByRole("dialog", { name: "Cancel your trial?" }),+ ).getByRole("button", { name: "Cancel trial" }),);await waitFor(() => expect(cancel).toHaveBeenCalledOnce());act(() => setTrialUser("user-b"));@@ -125,4 +129,131 @@ describe("trial account isolation", () => {expect(screen.queryByText(/Cancellation confirmed/)).toBeNull();expect(screen.getByText(/\$30\.00/)).toBeDefined();});++ it("does not open user A's late cancellation popup for user B", async () => {+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(trialForCurrentUser),+ getPostTrialsCancelTrialMockHandler200(() => pending.promise),+ );+ render(<TrialCard />);+ await confirmCancel();+ act(() => setTrialUser("user-b"));+ await screen.findByText(/\$30\.00/);+ pending.resolve(trialResponse({ cancel_at_period_end: true }));+ await waitFor(() =>+ expect(+ screen+ .getByRole("button", { name: "Cancel trial" })+ .hasAttribute("disabled"),+ ).toBe(false),+ );+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(screen.queryByText("Cancellation pending")).toBeNull();+ });++ it("hides user A's open cancellation popup from user B", async () => {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(trialForCurrentUser),+ getPostTrialsCancelTrialMockHandler200(+ trialResponse({+ cancel_at_period_end: true,+ }),+ ),+ );+ render(<TrialCard />);+ await confirmCancel();+ await screen.findByRole("dialog", { name: "Cancellation confirmed" });+ act(() => setTrialUser("user-b"));+ await screen.findByText(/\$30\.00/);+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("does not apply user A's late resume to user B", async () => {+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();+ const resume = vi.fn(() => pending.promise);+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(() =>+ trialResponse({+ cancel_at_period_end: true,+ offer: {+ ...trialOffer,+ unit_amount:+ useAuthStore.getState().user?.id === "user-a" ? 2000 : 3000,+ },+ }),+ ),+ getPostTrialsResumeTrialMockHandler200(resume),+ );+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Resume trial" }),+ );+ await waitFor(() => expect(resume).toHaveBeenCalledOnce());+ act(() => setTrialUser("user-b"));+ await screen.findByText(/\$30 \/ month/);+ pending.resolve(trialResponse());+ await waitFor(() =>+ expect(+ screen+ .getByRole("button", { name: "Resume trial" })+ .hasAttribute("disabled"),+ ).toBe(false),+ );+ expect(screen.getByText("Cancellation pending")).toBeDefined();+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it("does not close user B's popup when user A's late resume lands", async () => {+ const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(() =>+ useAuthStore.getState().user?.id === "user-a"+ ? trialResponse({ cancel_at_period_end: true })+ : trialForCurrentUser(),+ ),+ getPostTrialsResumeTrialMockHandler200(() => pending.promise),+ getPostTrialsCancelTrialMockHandler200(+ trialResponse({ cancel_at_period_end: true }),+ ),+ );+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Resume trial" }),+ );+ act(() => setTrialUser("user-b"));+ await confirmCancel();+ await screen.findByRole("dialog", { name: "Cancellation confirmed" });++ pending.resolve(trialResponse());+ await act(() => new Promise((settle) => setTimeout(settle, 50)));++ expect(+ screen.getByRole("dialog", { name: "Cancellation confirmed" }),+ ).toBeDefined();+ });});++function trialForCurrentUser() {+ return trialResponse({+ offer: {+ ...trialOffer,+ unit_amount: useAuthStore.getState().user?.id === "user-a" ? 2000 : 3000,+ },+ });+}++async function confirmCancel() {+ fireEvent.click(await screen.findByRole("button", { name: "Cancel trial" }));+ const confirm = await screen.findByRole("dialog", {+ name: "Cancel your trial?",+ });+ fireEvent.click(+ within(confirm).getByRole("button", { name: "Cancel trial" }),+ );+ await waitFor(() =>+ expect(+ screen.queryByRole("dialog", { name: "Cancel your trial?" }),+ ).toBeNull(),+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsxindex a108158bda..a54d4ab47b 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx@@ -14,6 +14,7 @@ import {render,screen,waitFor,+ within,} from "@/tests/integrations/test-utils";import {deferredTrialResponse,@@ -31,7 +32,7 @@ afterEach(() => {});describe("trial billing actions", () => {- it("hides trial usage and ends access immediately on cancellation", async () => {+ it("hides trial usage and blocks a second cancel while one runs", async () => {const pending = deferredTrialResponse<ReturnType<typeof trialResponse>>();const cancel = vi.fn(() => pending.promise);server.use(@@ -43,19 +44,17 @@ describe("trial billing actions", () => {expect(screen.queryByRole("progressbar")).toBeNull();expect(screen.queryByText(/trial allowance used/i)).toBeNull();expect(screen.getByText(/Your trial ends.*\$20\.00/)).toBeDefined();- expect(- screen.getByText(/Canceling ends trial access immediately/),- ).toBeDefined();fireEvent.click(button);fireEvent.click(- await screen.findByRole("button", { name: "End trial now" }),+ within(+ await screen.findByRole("dialog", { name: "Cancel your trial?" }),+ ).getByRole("button", { name: "Cancel trial" }),);await waitFor(() => expect(cancel).toHaveBeenCalledOnce());expect(button.hasAttribute("disabled")).toBe(true);fireEvent.click(button);- pending.resolve(trialResponse({ active: false, status: "canceled" }));- expect(await screen.findByText(/Cancellation confirmed/)).toBeDefined();- expect(screen.getByText("Your trial has ended")).toBeDefined();+ pending.resolve(trialResponse({ cancel_at_period_end: true }));+ expect(await screen.findByText("Cancellation pending")).toBeDefined();expect(screen.queryByRole("button", { name: "Cancel trial" })).toBeNull();expect(cancel).toHaveBeenCalledOnce();});@@ -72,7 +71,9 @@ describe("trial billing actions", () => {await screen.findByRole("button", { name: "Cancel trial" }),);fireEvent.click(- await screen.findByRole("button", { name: "End trial now" }),+ within(+ await screen.findByRole("dialog", { name: "Cancel your trial?" }),+ ).getByRole("button", { name: "Cancel trial" }),);expect(await screen.findByRole("alert")).toBeDefined();expect(@@ -83,14 +84,16 @@ describe("trial billing actions", () => {expect(screen.queryByText(/Cancellation confirmed/)).toBeNull();server.use(getPostTrialsCancelTrialMockHandler200(- trialResponse({ active: false, status: "canceled" }),+ trialResponse({ cancel_at_period_end: true }),),);fireEvent.click(screen.getByRole("button", { name: "Cancel trial" }));fireEvent.click(- await screen.findByRole("button", { name: "End trial now" }),+ within(+ await screen.findByRole("dialog", { name: "Cancel your trial?" }),+ ).getByRole("button", { name: "Cancel trial" }),);- await screen.findByText(/Cancellation confirmed/);+ await screen.findByText("Cancellation pending");expect(screen.queryByRole("alert")).toBeNull();});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-confirmation.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-confirmation.test.tsxindex bf057c0b05..769aaaed22 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-confirmation.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-confirmation.test.tsx@@ -21,30 +21,6 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";beforeEach(() => setTrialUser("user-a"));afterEach(() => setTrialUser(null));-it("requires confirmation before irreversibly ending a trial", async () => {- const cancel = vi.fn(() =>- trialResponse({ active: false, status: "canceled" }),- );- server.use(- getGetTrialsGetTrialStatusMockHandler200(trialResponse()),- getPostTrialsCancelTrialMockHandler200(cancel),- );- render(<TrialCard />);- fireEvent.click(await screen.findByRole("button", { name: "Cancel trial" }));- expect(- await screen.findByRole("dialog", { name: "End your trial now?" }),- ).toBeDefined();- expect(cancel).not.toHaveBeenCalled();- expect(screen.getByText(/You cannot restart this trial/)).toBeDefined();- fireEvent.click(screen.getByRole("button", { name: "Keep trial" }));- await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());- expect(cancel).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole("button", { name: "Cancel trial" }));- fireEvent.click(await screen.findByRole("button", { name: "End trial now" }));- await screen.findByText(/Cancellation confirmed/);- expect(cancel).toHaveBeenCalledOnce();-});-it("dismisses confirmation on Escape without canceling", async () => {const cancel = vi.fn(() => trialResponse());server.use(diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-keeps-access.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-keeps-access.test.tsxnew file mode 100644index 0000000000..3bdce3aa08--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-cancel-keeps-access.test.tsx@@ -0,0 +1,180 @@+import {+ getGetTrialsGetTrialStatusMockHandler200,+ getPostTrialsCancelTrialMockHandler200,+} from "@/app/api/__generated__/endpoints/trials/trials.msw";+import { COUNTRIES } from "@/components/molecules/PlanCard/countries";+import { PLANS } from "@/components/molecules/PlanCard/plans";+import { SubscriptionPlans } from "@/components/organisms/SubscriptionPlans/SubscriptionPlans";+import {+ formatTrialEnd,+ formatTrialEndDate,+} from "@/components/organisms/TrialCard/helpers";+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialOffer,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const endsAt = new Date("2030-09-17T15:00:00Z");++beforeEach(() => setTrialUser());+afterEach(() => setTrialUser(null));++describe("cancel confirmation", () => {+ it("promises access until the trial ends and no charge", async () => {+ const cancel = vi.fn(() => trialResponse({ cancel_at_period_end: true }));+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(trialResponse()),+ getPostTrialsCancelTrialMockHandler200(cancel),+ );+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Cancel trial" }),+ );+ const dialog = await screen.findByRole("dialog", {+ name: "Cancel your trial?",+ });+ expect(dialog.textContent).toContain(+ "Your trial won't convert to a paid plan and your card won't be charged.",+ );+ expect(dialog.textContent).toContain(+ `You keep full access until ${formatTrialEnd(endsAt)}, and you can resume your trial any time before then.`,+ );+ expect(within(dialog).getByText(formatTrialEnd(endsAt)).tagName).toBe(+ "STRONG",+ );+ expect(within(dialog).queryByText(/immediately|cannot restart/)).toBeNull();+ fireEvent.click(within(dialog).getByRole("button", { name: "Keep trial" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(cancel).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole("button", { name: "Cancel trial" }));+ const confirm = await screen.findByRole("dialog", {+ name: "Cancel your trial?",+ });+ fireEvent.click(+ within(confirm).getByRole("button", { name: "Cancel trial" }),+ );+ await screen.findByText("Cancellation pending");+ expect(cancel).toHaveBeenCalledOnce();+ });++ it("shows the ended trial when the cancel finds it already over", async () => {+ let ended = false;+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(() =>+ ended+ ? trialResponse({ active: false, status: "canceled" })+ : trialResponse(),+ ),+ http.post("*/api/credits/trial/cancel", () => {+ ended = true;+ return HttpResponse.json(+ { detail: "This trial has ended. Manage the plan in billing." },+ { status: 409 },+ );+ }),+ );+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Cancel trial" }),+ );+ const confirm = await screen.findByRole("dialog", {+ name: "Cancel your trial?",+ });+ fireEvent.click(+ within(confirm).getByRole("button", { name: "Cancel trial" }),+ );+ expect((await screen.findByRole("alert")).textContent).toContain(+ "This trial has ended. Manage the plan in billing.",+ );+ expect(await screen.findByText("Your trial has ended")).toBeDefined();+ expect(screen.queryByRole("button", { name: "Cancel trial" })).toBeNull();+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("drops the ends-immediately warning from the active trial", async () => {+ server.use(getGetTrialsGetTrialStatusMockHandler200(trialResponse()));+ render(<TrialCard />);+ await screen.findByRole("button", { name: "Cancel trial" });+ expect(screen.getByText(/Your trial ends.*\$20\.00/)).toBeDefined();+ expect(screen.queryByText(/immediately/)).toBeNull();+ });+});++describe("cancel-pending trial card", () => {+ it("shows the pending cancellation and a resume action", async () => {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(+ trialResponse({ cancel_at_period_end: true }),+ ),+ );+ render(<TrialCard />);+ expect(await screen.findByText("Cancellation pending")).toBeDefined();+ expect(screen.getByRole("heading", { name: "Your trial" })).toBeDefined();+ const card = screen.getByRole("region", { name: "AutoGPT trial" });+ expect(card.textContent).toContain(+ `Cancellation confirmed. Your trial will not convert to a paid plan and your card won't be charged. Trial access ends ${formatTrialEnd(endsAt)}.`,+ );+ expect(card.textContent).toContain(+ `Resume to keep the trial and start Pro on ${formatTrialEndDate(endsAt)} at $20 / month, plus applicable tax.`,+ );+ expect(screen.getByRole("button", { name: "Resume trial" })).toBeDefined();+ expect(screen.queryByRole("button", { name: "Cancel trial" })).toBeNull();+ expect(screen.queryByText(/immediately/)).toBeNull();+ expect(screen.queryByRole("dialog")).toBeNull();+ });+});++describe("trial terms before the trial starts", () => {+ it("states the cancel terms on the offer", async () => {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(+ trialResponse({ eligible: true, active: false, status: null }),+ ),+ );+ render(<TrialCard />);+ await screen.findByRole("button", { name: /start 7-day trial/i });+ expect(+ screen.getByText(+ "Trial usage is limited. If you cancel, you keep access until the trial ends. You can manage your plan in billing.",+ ),+ ).toBeDefined();+ });++ it("states the cancel terms in trial details", async () => {+ render(+ <SubscriptionPlans+ plans={PLANS}+ country={COUNTRIES[0]}+ billing="monthly"+ onBillingChange={vi.fn()}+ trialOffer={trialOffer}+ onStartTrial={vi.fn()}+ onSelectPlan={vi.fn()}+ isUpdatingTier={false}+ isStartingTrial={false}+ trialError={null}+ />,+ );+ const pro = within(screen.getByRole("region", { name: "Pro plan" }));+ fireEvent.click(pro.getByRole("button", { name: "Trial details" }));+ const details = await screen.findByRole("dialog");+ expect(+ within(details).getByText(+ "Trial usage is limited. If you cancel, you keep access until the trial ends. You can manage or cancel your plan in billing.",+ ),+ ).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-canceled-popup.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-canceled-popup.test.tsxnew file mode 100644index 0000000000..07d2fff608--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-canceled-popup.test.tsx@@ -0,0 +1,296 @@+import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";+import {+ getGetTrialsGetTrialStatusMockHandler200,+ getPostTrialsCancelTrialMockHandler200,+} from "@/app/api/__generated__/endpoints/trials/trials.msw";+import {+ formatTrialEnd,+ formatTrialEndDate,+ formatTrialEndTime,+} from "@/components/organisms/TrialCard/helpers";+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import {+ deferredTrialResponse,+ setTrialUser,+ trialOffer,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mockPush = vi.hoisted(() => vi.fn());+vi.mock("next/navigation", () => ({+ useRouter: () => ({+ push: mockPush,+ replace: vi.fn(),+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+ }),+ usePathname: () => "/settings/billing",+ useSearchParams: () => new URLSearchParams(),+ useParams: () => ({}),+}));++const posthog = vi.hoisted(() => ({ capture: vi.fn() }));+vi.mock("@posthog/react", () => ({+ usePostHog: () => posthog,+ useFeatureFlagVariantKey: () => undefined,+}));++const HOUR = 60 * 60 * 1000;+const DAY = 24 * HOUR;+const endsAt = new Date("2030-09-17T15:00:00Z");++function active(ends = endsAt) {+ return trialResponse({ ends_at: ends });+}++function cancelPending(ends = endsAt) {+ return trialResponse({+ cancel_at_period_end: true,+ ends_at: ends,+ });+}++function mockCancelFlow(ends = endsAt) {+ const cancel = vi.fn(() => cancelPending(ends));+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(active(ends)),+ getPostTrialsCancelTrialMockHandler200(cancel),+ );+ return cancel;+}++function SubscriptionStatusObserver() {+ useGetSubscriptionStatus();+ return null;+}++async function cancelThroughConfirmation() {+ fireEvent.click(await screen.findByRole("button", { name: "Cancel trial" }));+ const confirm = await screen.findByRole("dialog", {+ name: "Cancel your trial?",+ });+ fireEvent.click(+ within(confirm).getByRole("button", { name: "Cancel trial" }),+ );+ return screen.findByRole("dialog", { name: "Cancellation confirmed" });+}++beforeEach(() => {+ setTrialUser();+ mockPush.mockClear();+ posthog.capture.mockClear();+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date(endsAt.getTime() - 5 * DAY));+});+afterEach(() => {+ vi.useRealTimers();+ setTrialUser(null);+});++describe("post-cancel popup", () => {+ it("opens once after the cancel and never again on a remount", async () => {+ mockCancelFlow();+ const { unmount } = render(<TrialCard />);+ const popup = await cancelThroughConfirmation();+ expect(popup.textContent).toContain(+ `Your card won't be charged. You still have 5 days of full access, until ${formatTrialEnd(endsAt)}. Nothing changes until then.`,+ );+ expect(within(popup).getByText("5 days").tagName).toBe("STRONG");+ expect(within(popup).getByText("Worth doing before then")).toBeDefined();+ expect(+ within(popup).getByText("Put an Expert on a schedule"),+ ).toBeDefined();+ expect(within(popup).getByText("Your work stays")).toBeDefined();+ expect(+ within(popup).getByText(+ `Pro is $20 / month, cancel anytime. Resume your trial instead and your plan starts ${formatTrialEndDate(endsAt)}.`,+ ),+ ).toBeDefined();+ expect(posthog.capture).toHaveBeenCalledWith("trial_cancel_popup_viewed", {+ days_left: 5,+ });++ fireEvent.click(within(popup).getByRole("button", { name: "Close" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(screen.getByText("Cancellation pending")).toBeDefined();++ unmount();+ server.use(getGetTrialsGetTrialStatusMockHandler200(cancelPending()));+ render(<TrialCard />);+ await screen.findByText("Cancellation pending");+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(+ posthog.capture.mock.calls.filter(+ ([event]) => event === "trial_cancel_popup_viewed",+ ),+ ).toHaveLength(1);+ });++ it("opens without waiting for the plan status refresh", async () => {+ mockCancelFlow();+ const planStatus = deferredTrialResponse<void>();+ server.use(+ http.get("*/api/credits/subscription", async () => {+ await planStatus.promise;+ return HttpResponse.json({ tier: "TRIAL", monthly_cost: 0 });+ }),+ );+ render(+ <>+ <TrialCard />+ <SubscriptionStatusObserver />+ </>,+ );+ const popup = await cancelThroughConfirmation();+ expect(popup).toBeDefined();+ expect(posthog.capture).toHaveBeenCalledWith("trial_cancel_popup_viewed", {+ days_left: 5,+ });+ planStatus.resolve();+ });++ it("closes on Escape and leaves the trial cancel-pending", async () => {+ mockCancelFlow();+ render(<TrialCard />);+ const popup = await cancelThroughConfirmation();+ fireEvent.keyDown(popup, { key: "Escape" });+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(screen.getByRole("button", { name: "Resume trial" })).toBeDefined();+ });++ it("does not open when the cancel finds the trial already over", async () => {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(trialResponse()),+ getPostTrialsCancelTrialMockHandler200(+ trialResponse({ active: false, status: "canceled" }),+ ),+ );+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Cancel trial" }),+ );+ fireEvent.click(+ within(+ await screen.findByRole("dialog", { name: "Cancel your trial?" }),+ ).getByRole("button", { name: "Cancel trial" }),+ );+ await screen.findByText("Your trial has ended");+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(posthog.capture).not.toHaveBeenCalledWith(+ "trial_cancel_popup_viewed",+ expect.anything(),+ );+ });++ it.each(["billing", "onboarding"] as const)(+ "sends Subscribe now from the %s card to billing and closes",+ async (returnTo) => {+ mockCancelFlow();+ render(<TrialCard returnTo={returnTo} />);+ const popup = await cancelThroughConfirmation();+ fireEvent.click(+ within(popup).getByRole("button", { name: "Subscribe now" }),+ );+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(mockPush).toHaveBeenCalledExactlyOnceWith("/settings/billing");+ expect(posthog.capture).toHaveBeenCalledWith(+ "trial_subscribe_now_clicked",+ { days_left: 5 },+ );+ },+ );+});++describe("time left in the popup", () => {+ it.each([+ [5 * DAY, "5 days", 5],+ [DAY, "1 day", 1],+ [DAY + HOUR, "2 days", 2],+ ])("reads %ims as %s", async (left, label, daysLeft) => {+ vi.setSystemTime(new Date(endsAt.getTime() - left));+ mockCancelFlow();+ render(<TrialCard />);+ const popup = await cancelThroughConfirmation();+ expect(popup.textContent).toContain(+ `You still have ${label} of full access, until ${formatTrialEnd(endsAt)}.`,+ );+ expect(posthog.capture).toHaveBeenCalledWith("trial_cancel_popup_viewed", {+ days_left: daysLeft,+ });+ });++ it.each([+ ["today", new Date(2030, 8, 17, 11, 10), new Date(2030, 8, 17, 14, 10)],+ ["tomorrow", new Date(2030, 8, 16, 22, 0), new Date(2030, 8, 17, 1, 0)],+ ])(+ "names the clock time %s when under a day is left",+ async (day, now, ends) => {+ vi.setSystemTime(now);+ mockCancelFlow(ends);+ render(<TrialCard />);+ const popup = await cancelThroughConfirmation();+ expect(popup.textContent).toContain(+ `You still have full access until ${formatTrialEndTime(ends)} ${day}. Nothing changes until then.`,+ );+ expect(popup.textContent).not.toMatch(/\bdays?\b of full access/);+ expect(+ within(popup).getByText(+ `Pro is $20 / month, cancel anytime. Resume your trial instead and your plan starts ${day}.`,+ ),+ ).toBeDefined();+ expect(posthog.capture).toHaveBeenCalledWith(+ "trial_cancel_popup_viewed",+ {+ days_left: 1,+ },+ );+ },+ );+});++describe("popup prices", () => {+ it("keeps the cents of a price that has them", async () => {+ mockCancelFlow();+ server.use(+ getPostTrialsCancelTrialMockHandler200(+ trialResponse({+ cancel_at_period_end: true,+ offer: { ...trialOffer, unit_amount: 1999 },+ }),+ ),+ );+ render(<TrialCard />);+ const popup = await cancelThroughConfirmation();+ expect(popup.textContent).toContain(+ "Pro is $19.99 / month, cancel anytime.",+ );+ });+});++describe("popup after the end has passed", () => {+ it("says access has ended instead of naming a time today", async () => {+ vi.setSystemTime(new Date(endsAt.getTime() + 5 * 60 * 1000));+ mockCancelFlow();+ render(<TrialCard />);+ const popup = await cancelThroughConfirmation();+ expect(popup.textContent).toContain(+ "Your card won't be charged. Your trial access has ended.",+ );+ expect(popup.textContent).not.toMatch(/today|Nothing changes/);+ expect(+ within(popup).getByText("Pro is $20 / month, cancel anytime."),+ ).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-checkout-return.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-checkout-return.test.tsxnew file mode 100644index 0000000000..5cad2e449b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-checkout-return.test.tsx@@ -0,0 +1,115 @@+import { act, render, screen } from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import SettingsBillingPage from "../page";+import {+ cancelPending,+ mockBilling,+ trialSubscription,+} from "./trial-plan-fixtures";++const mockSearchParams = vi.hoisted(() => ({+ current: new URLSearchParams(),+}));+vi.mock("next/navigation", async (importOriginal) => ({+ ...(await importOriginal<typeof import("next/navigation")>()),+ useSearchParams: () => mockSearchParams.current,+ useRouter: () => ({+ push: vi.fn(),+ replace: vi.fn(),+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+ }),+ usePathname: () => "/settings/billing",+ useParams: () => ({}),+}));++const FINISHING = "Finishing your new plan…";++function advance(ms: number) {+ return act(() => vi.advanceTimersByTimeAsync(ms));+}++beforeEach(() => {+ setTrialUser();+ vi.useFakeTimers({ shouldAdvanceTime: true });+ mockSearchParams.current = new URLSearchParams({+ subscription: "success",+ session_id: "cs_test_max",+ plan: "MAX",+ cycle: "monthly",+ });+});+afterEach(() => {+ vi.useRealTimers();+ setTrialUser(null);+ mockSearchParams.current = new URLSearchParams();+});++describe("returning from a plan Checkout while the trial is cancel-pending", () => {+ it("offers no second purchase until the new plan replaces the trial", async () => {+ const { state, hits } = mockBilling();+ render(<SettingsBillingPage />);+ expect(await screen.findByText(FINISHING)).toBeDefined();+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Upgrade to Max" })).toBeNull();++ state.trial = trialResponse({+ ...cancelPending,+ active: false,+ status: "canceled",+ });+ state.subscription = { ...trialSubscription, tier: "MAX" };+ await advance(2_000);++ expect(await screen.findByText("Active")).toBeDefined();+ expect(screen.getByText("Max")).toBeDefined();+ expect(screen.queryByText(FINISHING)).toBeNull();+ expect(screen.queryByText("Cancellation pending")).toBeNull();+ expect(screen.queryByText("Your trial has ended")).toBeNull();+ const settled = { ...hits };+ await advance(10_000);+ expect(hits.trial).toBe(settled.trial);+ expect(hits.subscription).toBe(settled.subscription);+ });++ it("offers the plan choices again when the plan takes too long", async () => {+ const { hits } = mockBilling();+ render(<SettingsBillingPage />);+ await screen.findByText(FINISHING);+ await advance(10_000);+ expect(hits.subscription).toBeGreaterThan(3);+ expect(hits.trial).toBeGreaterThan(3);++ await advance(25_000);+ expect(+ await screen.findByRole("region", { name: "Plan choices" }),+ ).toBeDefined();+ expect(screen.queryByText(FINISHING)).toBeNull();+ const settled = { ...hits };+ await advance(10_000);+ expect(hits.subscription).toBe(settled.subscription);+ expect(hits.trial).toBe(settled.trial);+ });+});++describe("returning from a plan Checkout without a trial", () => {+ it("does not keep checking the plan", async () => {+ const { state, hits } = mockBilling(+ trialResponse({ active: false, status: "canceled" }),+ );+ state.subscription = { ...trialSubscription, tier: "PRO" };+ render(<SettingsBillingPage />);+ expect(await screen.findByText("Active")).toBeDefined();+ const settled = { ...hits };+ await advance(10_000);+ expect(hits.subscription).toBe(settled.subscription);+ expect(hits.trial).toBe(settled.trial);+ expect(screen.queryByText(FINISHING)).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-choices.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-choices.test.tsxnew file mode 100644index 0000000000..1332b9f9c1--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-choices.test.tsx@@ -0,0 +1,181 @@+import { server } from "@/mocks/mock-server";+import {+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import {+ deferredTrialResponse,+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import SettingsBillingPage from "../page";+import {+ cancelPending,+ mockBilling,+ trialSubscription,+ yearlyOffer,+} from "./trial-plan-fixtures";++const analytics = vi.hoisted(() => ({+ trackPaywallViewed: vi.fn(),+}));+vi.mock(+ "@/services/analytics/monetization-analytics",+ async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/services/analytics/monetization-analytics")+ >()),+ ...analytics,+ }),+);++beforeEach(() => setTrialUser());+afterEach(() => {+ setTrialUser(null);+ analytics.trackPaywallViewed.mockReset();+ vi.restoreAllMocks();+});++describe("plan choices while a trial cancellation is pending", () => {+ it("prices the trial's plan and the next tier up from the status data", async () => {+ mockBilling();+ render(<SettingsBillingPage />);+ const choices = await screen.findByRole("region", {+ name: "Plan choices",+ });+ const [own, upgrade] = within(choices).getAllByRole("listitem");+ expect(within(own).getByText("Pro")).toBeDefined();+ expect(+ within(own).getByText("$20").classList.contains("sentry-unmask"),+ ).toBe(false);+ expect(within(own).getByText("/ month")).toBeDefined();+ expect(+ within(own).getByText(+ "Starts today. Your trial ends and the plan takes over.",+ ),+ ).toBeDefined();+ expect(+ within(own).getByRole("button", { name: "Subscribe to Pro" }),+ ).toBeDefined();+ expect(within(upgrade).getByText("Max")).toBeDefined();+ expect(within(upgrade).getByText("$320")).toBeDefined();+ expect(within(upgrade).getByText("/ month")).toBeDefined();+ expect(+ within(upgrade).getByText(+ "8.5x the usage of Pro for people who run a lot.",+ ),+ ).toBeDefined();+ expect(+ within(upgrade).getByRole("button", { name: "Upgrade to Max" }),+ ).toBeDefined();+ expect(analytics.trackPaywallViewed).toHaveBeenCalledWith("billing");+ });++ it("prices both plans on the trial's yearly cycle", async () => {+ mockBilling(trialResponse({ ...cancelPending, offer: yearlyOffer }));+ render(<SettingsBillingPage />);+ const choices = await screen.findByRole("region", {+ name: "Plan choices",+ });+ const [own, upgrade] = within(choices).getAllByRole("listitem");+ expect(within(own).getByText("$510")).toBeDefined();+ expect(within(own).getByText("/ year")).toBeDefined();+ expect(within(upgrade).getByText("$3,264")).toBeDefined();+ expect(within(upgrade).getByText("/ year")).toBeDefined();+ });++ it("keeps the cents of prices that have them", async () => {+ const { state } = mockBilling(+ trialResponse({+ ...cancelPending,+ offer: { ...yearlyOffer, billing_cycle: "monthly", unit_amount: 1999 },+ }),+ );+ state.subscription = {+ ...trialSubscription,+ tier_costs: { PRO: 1999, MAX: 32050 },+ };+ render(<SettingsBillingPage />);+ const choices = await screen.findByRole("region", {+ name: "Plan choices",+ });+ const [own, upgrade] = within(choices).getAllByRole("listitem");+ expect(within(own).getByText("$19.99")).toBeDefined();+ expect(within(upgrade).getByText("$320.50")).toBeDefined();+ });++ it("leaves out a next tier with no price on the trial's cycle", async () => {+ const { state } = mockBilling(+ trialResponse({ ...cancelPending, offer: yearlyOffer }),+ );+ state.subscription = { ...trialSubscription, tier_costs_yearly: {} };+ render(<SettingsBillingPage />);+ expect(+ await screen.findByRole("button", { name: "Subscribe to Pro" }),+ ).toBeDefined();+ expect(screen.queryByRole("button", { name: "Upgrade to Max" })).toBeNull();+ });++ it("leaves out a next tier whose price came back as 0", async () => {+ const { state } = mockBilling();+ state.subscription = {+ ...trialSubscription,+ tier_costs: { PRO: 5000, MAX: 0 },+ };+ render(<SettingsBillingPage />);+ expect(+ await screen.findByRole("button", { name: "Subscribe to Pro" }),+ ).toBeDefined();+ expect(screen.queryByRole("button", { name: "Upgrade to Max" })).toBeNull();+ expect(screen.queryByText("$0")).toBeNull();+ });++ it("falls back to plain copy when usage multipliers are missing", async () => {+ const { state } = mockBilling();+ state.subscription = { ...trialSubscription, tier_multipliers: {} };+ render(<SettingsBillingPage />);+ expect(+ await screen.findByText("More usage than Pro for people who run a lot."),+ ).toBeDefined();+ });++ it("shows nothing until plan prices load", async () => {+ const prices = deferredTrialResponse<void>();+ const { hits } = mockBilling();+ server.use(+ http.get("*/api/credits/subscription", async () => {+ hits.subscription += 1;+ await prices.promise;+ return HttpResponse.json(trialSubscription);+ }),+ );+ render(<SettingsBillingPage />);+ await waitFor(() => expect(hits.subscription).toBeGreaterThan(0));+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+ prices.resolve();+ expect(+ await screen.findByRole("region", { name: "Plan choices" }),+ ).toBeDefined();+ });++ it("shows nothing when plan prices fail to load", async () => {+ const { hits } = mockBilling();+ server.use(+ http.get("*/api/credits/subscription", () => {+ hits.subscription += 1;+ return HttpResponse.json({ detail: "unavailable" }, { status: 500 });+ }),+ );+ render(<SettingsBillingPage />);+ await waitFor(() => expect(hits.subscription).toBeGreaterThan(0));+ await new Promise((settle) => setTimeout(settle, 50));+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+ expect(+ screen.queryByRole("button", { name: "Subscribe to Pro" }),+ ).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-fixtures.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-fixtures.tsnew file mode 100644index 0000000000..35878af10a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-fixtures.ts@@ -0,0 +1,90 @@+import { getGetTrialsGetTrialStatusMockHandler200 } from "@/app/api/__generated__/endpoints/trials/trials.msw";+import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";+import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { server } from "@/mocks/mock-server";+import { fireEvent, screen } from "@/tests/integrations/test-utils";+import { trialOffer, trialResponse } from "@/tests/integrations/trial-fixtures";+import { http, HttpResponse } from "msw";+import { vi } from "vitest";++export const cancelPending = {+ cancel_at_period_end: true,+};++export const trialSubscription: SubscriptionStatusResponse = {+ tier: "TRIAL",+ monthly_cost: 0,+ proration_credit_cents: 0,+ has_active_stripe_subscription: true,+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ tier_multipliers: { PRO: 1, MAX: 8.5 },+};++export const yearlyOffer: TrialOfferResponse = {+ ...trialOffer,+ billing_cycle: "yearly",+ unit_amount: 51000,+};++export function returnURLs(plan: string, cycle: string) {+ const page = `${window.location.origin}${window.location.pathname}`;+ return {+ success_url: `${page}?subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${plan}&cycle=${cycle}`,+ cancel_url: `${page}?subscription=cancelled`,+ };+}++export function mockBilling(trial = trialResponse(cancelPending)) {+ const state = { trial, subscription: trialSubscription };+ const hits = { trial: 0, subscription: 0, invoices: 0 };+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(() => {+ hits.trial += 1;+ return state.trial;+ }),+ http.get("*/api/credits/subscription", () => {+ hits.subscription += 1;+ return HttpResponse.json(state.subscription);+ }),+ http.get("*/api/credits/invoices", () => {+ hits.invoices += 1;+ return HttpResponse.json([]);+ }),+ );+ return { state, hits };+}++export function mockPricePerUser() {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(() =>+ trialResponse({+ ...cancelPending,+ offer: {+ ...trialOffer,+ unit_amount:+ useAuthStore.getState().user?.id === "user-b" ? 3000 : 2000,+ },+ }),+ ),+ );+}++export function mockPlanRequest(respond: () => Response) {+ const body = vi.fn();+ server.use(+ http.post("*/api/credits/subscription", async ({ request }) => {+ body(await request.json());+ return respond();+ }),+ );+ return body;+}++export async function openConfirmation() {+ fireEvent.click(+ await screen.findByRole("button", { name: "Subscribe to Pro" }),+ );+ return screen.findByRole("dialog", { name: "Start Pro today?" });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-subscribe.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-subscribe.test.tsxnew file mode 100644index 0000000000..c088c82909--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-subscribe.test.tsx@@ -0,0 +1,283 @@+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import {+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import SettingsBillingPage from "../page";+import {+ cancelPending,+ mockBilling,+ mockPlanRequest,+ mockPricePerUser,+ openConfirmation,+ returnURLs,+ trialSubscription,+ yearlyOffer,+} from "./trial-plan-fixtures";++const toast = vi.hoisted(() => vi.fn());+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/components/molecules/Toast/use-toast")+ >()),+ toast,+}));++const analytics = vi.hoisted(() => ({+ trackPaywallViewed: vi.fn(),+ trackPlanSelected: vi.fn(),+}));+vi.mock(+ "@/services/analytics/monetization-analytics",+ async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/services/analytics/monetization-analytics")+ >()),+ ...analytics,+ }),+);++beforeEach(() => setTrialUser());+afterEach(() => {+ setTrialUser(null);+ toast.mockReset();+ analytics.trackPaywallViewed.mockReset();+ analytics.trackPlanSelected.mockReset();+ vi.restoreAllMocks();+});++describe("subscribing to the trial's plan", () => {+ it("charges today only after confirming, then refreshes trial and plan", async () => {+ const { state, hits } = mockBilling();+ const body = mockPlanRequest(() => {+ state.trial = trialResponse({ ...cancelPending, converted: true });+ state.subscription = { ...trialSubscription, tier: "PRO" };+ return HttpResponse.json({ ...state.subscription, url: "" });+ });+ render(<SettingsBillingPage />);+ const dialog = await openConfirmation();+ const charge = within(dialog).getByText(+ "Your trial ends now and your saved card is charged $20 / month, plus applicable tax.",+ );+ expect(charge.classList.contains("sentry-unmask")).toBe(false);+ expect(body).not.toHaveBeenCalled();+ expect(analytics.trackPlanSelected).toHaveBeenCalledWith({+ subscription_tier: "PRO",+ billing_cycle: "monthly",+ surface: "billing",+ });+ const before = { ...hits };++ fireEvent.click(+ within(dialog).getByRole("button", { name: "Subscribe to Pro" }),+ );++ await waitFor(() => expect(body).toHaveBeenCalledOnce());+ expect(body).toHaveBeenCalledWith({+ tier: "PRO",+ billing_cycle: "monthly",+ surface: "billing",+ ...returnURLs("PRO", "monthly"),+ });+ await waitFor(() => expect(hits.trial).toBeGreaterThan(before.trial));+ await waitFor(() =>+ expect(hits.subscription).toBeGreaterThan(before.subscription),+ );+ await waitFor(() => expect(hits.invoices).toBeGreaterThan(before.invoices));+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({ title: "You're on Pro" }),+ );+ await waitFor(() =>+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull(),+ );+ });++ it("sends the trial's own cycle for a yearly trial", async () => {+ mockBilling(trialResponse({ ...cancelPending, offer: yearlyOffer }));+ const body = mockPlanRequest(() =>+ HttpResponse.json({ ...trialSubscription, url: "" }),+ );+ render(<SettingsBillingPage />);+ const dialog = await openConfirmation();+ expect(+ within(dialog).getByText(+ "Your trial ends now and your saved card is charged $510 / year, plus applicable tax.",+ ),+ ).toBeDefined();+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Subscribe to Pro" }),+ );+ await waitFor(() =>+ expect(body).toHaveBeenCalledWith({+ tier: "PRO",+ billing_cycle: "yearly",+ surface: "billing",+ ...returnURLs("PRO", "yearly"),+ }),+ );+ });++ it("keeps the cents of a price that has them", async () => {+ mockBilling(+ trialResponse({+ ...cancelPending,+ offer: { ...yearlyOffer, billing_cycle: "monthly", unit_amount: 1999 },+ }),+ );+ render(<SettingsBillingPage />);+ const dialog = await openConfirmation();+ expect(+ within(dialog).getByText(+ "Your trial ends now and your saved card is charged $19.99 / month, plus applicable tax.",+ ),+ ).toBeDefined();+ });++ it("keeps the trial without a request when the person backs out", async () => {+ mockBilling();+ const body = mockPlanRequest(() =>+ HttpResponse.json({ ...trialSubscription, url: "" }),+ );+ render(<SettingsBillingPage />);+ const dialog = await openConfirmation();+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Keep my trial" }),+ );+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(body).not.toHaveBeenCalled();+ expect(+ screen.getByRole("button", { name: "Subscribe to Pro" }),+ ).toBeDefined();+ });++ it("shows why the charge failed and keeps the choices usable", async () => {+ mockBilling();+ const body = mockPlanRequest(() =>+ HttpResponse.json({ detail: "Your card was declined." }, { status: 402 }),+ );+ render(<SettingsBillingPage />);+ const dialog = await openConfirmation();+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Subscribe to Pro" }),+ );++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title: "Unable to start Pro",+ description: "Your card was declined.",+ variant: "destructive",+ }),+ );+ expect(body).toHaveBeenCalledOnce();+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(+ screen+ .getByRole("button", { name: "Subscribe to Pro" })+ .hasAttribute("disabled"),+ ).toBe(false);+ });++ it.each([409, 402, 422, 502])(+ "refreshes the trial and plan after a %i refusal",+ async (status) => {+ const { state, hits } = mockBilling();+ mockPlanRequest(() => {+ state.trial = trialResponse();+ return HttpResponse.json(+ { detail: "Your accepted plan starts after your trial." },+ { status },+ );+ });+ render(<SettingsBillingPage />);+ const dialog = await openConfirmation();+ const before = { ...hits };+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Subscribe to Pro" }),+ );++ await waitFor(() => expect(hits.trial).toBeGreaterThan(before.trial));+ await waitFor(() =>+ expect(hits.subscription).toBeGreaterThan(before.subscription),+ );+ expect(+ await screen.findByRole("button", { name: "Cancel trial" }),+ ).toBeDefined();+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+ expect(toast).toHaveBeenCalledWith({+ title: "Unable to start Pro",+ description: "Your accepted plan starts after your trial.",+ variant: "destructive",+ });+ },+ );++ it("never charges from a page whose plan changed elsewhere", async () => {+ const { state } = mockBilling();+ const body = mockPlanRequest(() =>+ HttpResponse.json({ ...trialSubscription, url: "" }),+ );+ render(<SettingsBillingPage />);+ const dialog = await openConfirmation();+ state.subscription = { ...trialSubscription, tier: "PRO" };++ fireEvent.click(+ within(dialog).getByRole("button", { name: "Subscribe to Pro" }),+ );++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title: "Your plan changed",+ description: "Review your current plan below.",+ }),+ );+ expect(body).not.toHaveBeenCalled();+ });++ it("does not announce a plan the server has not started yet", async () => {+ mockBilling();+ mockPlanRequest(() => HttpResponse.json({ ...trialSubscription, url: "" }));+ render(<SettingsBillingPage />);+ const dialog = await openConfirmation();++ fireEvent.click(+ within(dialog).getByRole("button", { name: "Subscribe to Pro" }),+ );++ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Payment received" }),+ ),+ );+ expect(toast).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "You're on Pro" }),+ );+ });++ it("does not show user B the confirmation user A opened", async () => {+ setTrialUser("user-a");+ mockBilling();+ mockPricePerUser();+ render(<SettingsBillingPage />);+ await screen.findByText("$20");+ act(() => setTrialUser("user-b"));+ await screen.findByText("$30");+ act(() => setTrialUser("user-a"));+ await screen.findByText("$20");++ await openConfirmation();+ act(() => setTrialUser("user-b"));++ await screen.findByText("$30");+ expect(screen.queryByRole("dialog")).toBeNull();+ });+});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.tsxnew file mode 100644index 0000000000..e355b59097--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-upgrade.test.tsx@@ -0,0 +1,223 @@+import { server } from "@/mocks/mock-server";+import {+ installGtagShim,+ removeGtagShim,+} from "@/tests/integrations/gtag-shim";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import {+ deferredTrialResponse,+ setTrialUser,+ trialOffer,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import SettingsBillingPage from "../page";+import {+ cancelPending,+ mockBilling,+ mockPlanRequest,+ mockPricePerUser,+ returnURLs,+ trialSubscription,+ yearlyOffer,+} from "./trial-plan-fixtures";++const toast = vi.hoisted(() => vi.fn());+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/components/molecules/Toast/use-toast")+ >()),+ toast,+}));++const analytics = vi.hoisted(() => ({+ trackPaywallViewed: vi.fn(),+ trackPlanSelected: vi.fn(),+}));+vi.mock(+ "@/services/analytics/monetization-analytics",+ async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@/services/analytics/monetization-analytics")+ >()),+ ...analytics,+ }),+);++const checkoutURL = "https://checkout.stripe.com/c/pay/cs_max";++function stubNavigation() {+ return vi.spyOn(window.location, "assign").mockImplementation(() => {});+}++beforeEach(() => setTrialUser());+afterEach(() => {+ setTrialUser(null);+ 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],+ ] as const)(+ "opens Stripe Checkout for the next tier on the %s cycle",+ async (cycle, offer) => {+ const assign = stubNavigation();+ mockBilling(trialResponse({ ...cancelPending, offer }));+ const body = mockPlanRequest(() =>+ HttpResponse.json({ ...trialSubscription, url: checkoutURL }),+ );+ render(<SettingsBillingPage />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Upgrade to Max" }),+ );++ await waitFor(() => expect(assign).toHaveBeenCalledWith(checkoutURL));+ expect(body).toHaveBeenCalledWith({+ tier: "MAX",+ billing_cycle: cycle,+ surface: "billing",+ ...returnURLs("MAX", cycle),+ });+ expect(analytics.trackPlanSelected).toHaveBeenCalledWith({+ subscription_tier: "MAX",+ billing_cycle: cycle,+ surface: "billing",+ });+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(toast).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();+ mockBilling();+ mockPlanRequest(() =>+ HttpResponse.json({ ...trialSubscription, url: checkoutURL }),+ );+ 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),+ },+ ]),+ );+ expect(upgrade.hasAttribute("disabled")).toBe(true);+ await waitFor(() => expect(assign).toHaveBeenCalledWith(checkoutURL));+ });++ it("frees the choices after handing off, so a page restored from history works", async () => {+ const assign = stubNavigation();+ mockBilling();+ mockPlanRequest(() =>+ HttpResponse.json({ ...trialSubscription, url: checkoutURL }),+ );+ render(<SettingsBillingPage />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Upgrade to Max" }),+ );++ await waitFor(() => expect(assign).toHaveBeenCalledOnce());+ await waitFor(() =>+ expect(+ screen+ .getByRole("button", { name: "Upgrade to Max" })+ .hasAttribute("disabled"),+ ).toBe(false),+ );+ expect(+ screen+ .getByRole("button", { name: "Subscribe to Pro" })+ .hasAttribute("disabled"),+ ).toBe(false);+ });++ it("shows why Checkout could not start", async () => {+ const assign = stubNavigation();+ mockBilling();+ mockPlanRequest(() =>+ HttpResponse.json(+ { detail: "Stripe is unavailable. Please retry." },+ { status: 502 },+ ),+ );+ render(<SettingsBillingPage />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Upgrade to Max" }),+ );+ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ title: "Unable to start Max",+ description: "Stripe is unavailable. Please retry.",+ variant: "destructive",+ }),+ );+ expect(assign).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(+ screen+ .getByRole("button", { name: "Upgrade to Max" })+ .hasAttribute("disabled"),+ ).toBe(false),+ );+ });++ it("does not send user B to the Checkout user A started", async () => {+ const assign = stubNavigation();+ setTrialUser("user-a");+ mockBilling();+ mockPricePerUser();+ const checkout = 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",+ });+ }),+ );+ render(<SettingsBillingPage />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Upgrade to Max" }),+ );+ await waitFor(() => expect(sent).toHaveBeenCalledOnce());++ act(() => setTrialUser("user-b"));+ await screen.findByText("$30");+ checkout.resolve();+ await act(() => new Promise((settle) => setTimeout(settle, 50)));++ expect(assign).not.toHaveBeenCalled();+ expect(toast).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsxindex 17fb4589a6..1f9c43c7d8 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-plan-visibility.test.tsx@@ -54,3 +54,106 @@ it("shows the trial as the current plan during an active trial", async () => {expect(screen.getByText("Your plan")).toBeDefined();expect(screen.queryByRole("button", { name: "Get Pro" })).toBeNull();});++const trialSubscription = {+ tier: "TRIAL",+ monthly_cost: 0,+ proration_credit_cents: 0,+ has_active_stripe_subscription: true,+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_multipliers: { PRO: 1, MAX: 8.5 },+};++function mockBilling(trial: ReturnType<typeof trialResponse>, tier: string) {+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(trial),+ http.get("*/api/credits/subscription", () =>+ HttpResponse.json({ ...trialSubscription, tier }),+ ),+ http.get("*/api/credits/invoices", () => HttpResponse.json([])),+ );+}++it("offers plan choices while a trial cancellation is pending", async () => {+ mockBilling(trialResponse({ cancel_at_period_end: true }), "TRIAL");+ render(<SettingsBillingPage />);+ expect(+ await screen.findByRole("button", { name: "Subscribe to Pro" }),+ ).toBeDefined();+ expect(screen.getByRole("button", { name: "Upgrade to Max" })).toBeDefined();+ expect(screen.queryByRole("button", { name: "Get Pro" })).toBeNull();+});++it("offers no plan choices during a trial that will convert", async () => {+ mockBilling(trialResponse({ cancel_at_period_end: false }), "TRIAL");+ render(<SettingsBillingPage />);+ await screen.findByRole("button", { name: "Cancel trial" });+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Subscribe to Pro" })).toBeNull();+});++it("offers no plan choices once a cancel-pending trial has converted", async () => {+ mockBilling(+ trialResponse({+ cancel_at_period_end: true,+ converted: true,+ }),+ "PRO",+ );+ render(<SettingsBillingPage />);+ await screen.findByRole("button", { name: "Upgrade to Max" });+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Subscribe to Pro" })).toBeNull();+});++it("offers no plan choices once a cancel-pending trial has ended", async () => {+ mockBilling(+ trialResponse({+ active: false,+ status: "canceled",+ cancel_at_period_end: true,+ }),+ "NO_TIER",+ );+ render(<SettingsBillingPage />);+ await screen.findByRole("button", { name: "Get Pro" });+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Subscribe to Pro" })).toBeNull();+});++it("shows a plan bought during a cancel-pending trial the cleanup has not ended", async () => {+ mockBilling(trialResponse({ cancel_at_period_end: true }), "MAX");+ render(<SettingsBillingPage />);+ expect(await screen.findByText("Active")).toBeDefined();+ expect(screen.getAllByText("Your plan")).toHaveLength(1);+ expect(screen.queryByRole("button", { name: "Resume trial" })).toBeNull();+ expect(screen.queryByRole("region", { name: "AutoGPT trial" })).toBeNull();+ expect(screen.queryByRole("region", { name: "Plan choices" })).toBeNull();+});++it("keeps a trial that will convert as the plan whatever tier is reported", async () => {+ mockBilling(trialResponse({ cancel_at_period_end: false }), "MAX");+ render(<SettingsBillingPage />);+ await screen.findByRole("button", { name: "Cancel trial" });+ expect(screen.getAllByText("Your plan")).toHaveLength(1);+ expect(screen.queryByText("Active")).toBeNull();+});++it.each(["PRO", "MAX"])(+ "drops the ended trial once a %s plan has replaced it",+ async (tier) => {+ mockBilling(+ trialResponse({+ active: false,+ status: "canceled",+ cancel_at_period_end: true,+ }),+ tier,+ );+ render(<SettingsBillingPage />);+ expect(await screen.findByText("Active")).toBeDefined();+ expect(screen.queryByText("Your trial has ended")).toBeNull();+ expect(screen.queryByRole("region", { name: "AutoGPT trial" })).toBeNull();+ expect(screen.getAllByText("Your plan")).toHaveLength(1);+ },+);diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-resume.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-resume.test.tsxnew file mode 100644index 0000000000..a8cbc91186--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-resume.test.tsx@@ -0,0 +1,165 @@+import {+ getGetTrialsGetTrialStatusMockHandler200,+ getPostTrialsCancelTrialMockHandler200,+ getPostTrialsResumeTrialMockHandler200,+} from "@/app/api/__generated__/endpoints/trials/trials.msw";+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@/tests/integrations/test-utils";+import {+ deferredTrialResponse,+ setTrialUser,+ trialResponse,+} from "@/tests/integrations/trial-fixtures";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const posthog = vi.hoisted(() => ({ capture: vi.fn() }));+vi.mock("@posthog/react", () => ({+ usePostHog: () => posthog,+ useFeatureFlagVariantKey: () => undefined,+}));++const DAY = 24 * 60 * 60 * 1000;+const endsAt = new Date("2030-09-17T15:00:00Z");+const active = trialResponse();+const cancelPending = trialResponse({+ cancel_at_period_end: true,+});++beforeEach(() => {+ setTrialUser();+ posthog.capture.mockClear();+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date(endsAt.getTime() - 5 * DAY));+});+afterEach(() => {+ vi.useRealTimers();+ setTrialUser(null);+});++async function openCanceledPopup() {+ fireEvent.click(await screen.findByRole("button", { name: "Cancel trial" }));+ const confirm = await screen.findByRole("dialog", {+ name: "Cancel your trial?",+ });+ fireEvent.click(+ within(confirm).getByRole("button", { name: "Cancel trial" }),+ );+ return screen.findByRole("dialog", { name: "Cancellation confirmed" });+}++async function expectNormalActiveTrial() {+ expect(+ await screen.findByRole("button", { name: "Cancel trial" }),+ ).toBeDefined();+ expect(screen.getByText(/Your trial ends.*\$20\.00/)).toBeDefined();+ expect(screen.queryByText("Cancellation pending")).toBeNull();+ expect(screen.queryByRole("button", { name: "Resume trial" })).toBeNull();+}++describe("resuming a cancel-pending trial", () => {+ it("resumes from the popup, closes it and restores the active trial", async () => {+ const pending = deferredTrialResponse<typeof active>();+ const resume = vi.fn(() => pending.promise);+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(active),+ getPostTrialsCancelTrialMockHandler200(cancelPending),+ getPostTrialsResumeTrialMockHandler200(resume),+ );+ render(<TrialCard />);+ const popup = await openCanceledPopup();+ const button = within(popup).getByRole("button", { name: "Resume trial" });+ fireEvent.click(button);+ await waitFor(() => expect(resume).toHaveBeenCalledOnce());+ expect(button.hasAttribute("disabled")).toBe(true);+ fireEvent.click(button);+ pending.resolve(active);+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ await expectNormalActiveTrial();+ expect(resume).toHaveBeenCalledOnce();+ expect(+ posthog.capture.mock.calls.filter(+ ([event]) => event === "trial_resume_clicked",+ ),+ ).toEqual([["trial_resume_clicked", { days_left: 5 }]]);+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it("resumes from the cancel-pending card", async () => {+ const resume = vi.fn(() => active);+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(cancelPending),+ getPostTrialsResumeTrialMockHandler200(resume),+ );+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Resume trial" }),+ );+ await expectNormalActiveTrial();+ expect(resume).toHaveBeenCalledOnce();+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("reports a failed resume, closes the popup and refetches the status", async () => {+ const status = vi.fn(() => active);+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(status),+ getPostTrialsCancelTrialMockHandler200(cancelPending),+ http.post("*/api/credits/trial/resume", () =>+ HttpResponse.json({ detail: "Stripe is unavailable" }, { status: 502 }),+ ),+ );+ render(<TrialCard />);+ const popup = await openCanceledPopup();+ expect(status).toHaveBeenCalledOnce();+ status.mockImplementation(() => cancelPending);+ fireEvent.click(+ within(popup).getByRole("button", { name: "Resume trial" }),+ );+ expect((await screen.findByRole("alert")).textContent).toContain(+ "Stripe is unavailable",+ );+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(status).toHaveBeenCalledTimes(2);+ expect(+ screen+ .getByRole("button", { name: "Resume trial" })+ .hasAttribute("disabled"),+ ).toBe(false);+ expect(screen.getByText("Cancellation pending")).toBeDefined();+ });++ it("keeps the trial card when the refetch after a failed resume fails too", async () => {+ let limited = false;+ server.use(+ http.get("*/api/credits/trial", () =>+ limited+ ? HttpResponse.json({ detail: "Too many requests" }, { status: 429 })+ : HttpResponse.json(cancelPending),+ ),+ http.post("*/api/credits/trial/resume", () => {+ limited = true;+ return HttpResponse.json(+ { detail: "Too many requests" },+ { status: 429 },+ );+ }),+ );+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Resume trial" }),+ );+ expect((await screen.findByRole("alert")).textContent).toContain(+ "Too many requests",+ );+ expect(screen.getByText("Cancellation pending")).toBeDefined();+ expect(screen.getByRole("button", { name: "Resume trial" })).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SubscriptionTab.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SubscriptionTab.tsxindex ce6c69fa16..1d3938c5b1 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SubscriptionTab.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/SubscriptionTab.tsx@@ -1,20 +1,37 @@"use client";+import { Text } from "@/components/atoms/Text/Text";+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";+import { TrialCheckoutConfirmation } from "@/components/organisms/TrialCard/TrialCheckoutConfirmation";+import { AutopilotUsageCard } from "./AutopilotUsageCard/AutopilotUsageCard";import { InvoicesCard } from "./InvoicesCard/InvoicesCard";import { PaymentMethodCard } from "./PaymentMethodCard/PaymentMethodCard";+import { TrialPlanChoices } from "./TrialPlanChoices/TrialPlanChoices";+import { useSubscriptionTab } from "./useSubscriptionTab";import { YourPlanCard } from "./YourPlanCard/YourPlanCard";-import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";-import { TrialCheckoutConfirmation } from "@/components/organisms/TrialCard/TrialCheckoutConfirmation";-import { useTrialStatus } from "@/services/trials/useTrialStatus";-export function SubscriptionTab() {- const { data: trial, isLoading } = useTrialStatus();- const showPlan = !isLoading && (!trial?.active || trial.converted);+interface Props {+ isPlanCheckoutReturn?: boolean;+}++export function SubscriptionTab({ isPlanCheckoutReturn = false }: Props) {+ const { showPlan, showTrialCard, planChoicesOffer, isConfirmingPlan } =+ useSubscriptionTab(isPlanCheckoutReturn);return (<div className="flex flex-col gap-6"><TrialCheckoutConfirmation />- <TrialCard />+ <div className="flex flex-col gap-3 empty:hidden">+ {showTrialCard ? <TrialCard /> : null}+ {isConfirmingPlan ? (+ <Text variant="small" tone="secondary" role="status" className="px-4">+ Finishing your new plan…+ </Text>+ ) : null}+ {planChoicesOffer ? (+ <TrialPlanChoices offer={planChoicesOffer} />+ ) : null}+ </div>{showPlan ? <YourPlanCard index={0} /> : null}<AutopilotUsageCard index={1} /><PaymentMethodCard index={2} />diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/ConfirmTrialPlanDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/ConfirmTrialPlanDialog.tsxnew file mode 100644index 0000000000..a5bba31412--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/ConfirmTrialPlanDialog.tsx@@ -0,0 +1,54 @@+import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { Dialog } from "@/components/molecules/Dialog/Dialog";++interface Props {+ isOpen: boolean;+ planLabel: string;+ price: string;+ isSaving: boolean;+ onConfirm: () => void;+ onClose: () => void;+}++export function ConfirmTrialPlanDialog({+ isOpen,+ planLabel,+ price,+ isSaving,+ onConfirm,+ onClose,+}: Props) {+ return (+ <Dialog+ title={`Start ${planLabel} today?`}+ styling={{ maxWidth: "28rem", minWidth: "auto" }}+ controlled={{+ isOpen,+ set: (open) => {+ if (!open) onClose();+ },+ }}+ >+ <Dialog.Content>+ <Text variant="body" unmask={false}>+ Your trial ends now and your saved card is charged {price}, plus+ applicable tax.+ </Text>+ <Dialog.Footer>+ <Button variant="outline" onClick={onClose} disabled={isSaving}>+ Keep my trial+ </Button>+ <Button+ variant="primary"+ onClick={onConfirm}+ disabled={isSaving}+ loading={isSaving}+ >+ Subscribe to {planLabel}+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/PlanChoice.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/PlanChoice.tsxnew file mode 100644index 0000000000..be474387b8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/PlanChoice.tsx@@ -0,0 +1,58 @@+import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";++import type { PlanChoiceDetails } from "./helpers";++interface Props {+ plan: PlanChoiceDetails;+ actionLabel: string;+ variant: "primary" | "outline";+ isLoading: boolean;+ isDisabled: boolean;+ onSelect: () => void;+}++export function PlanChoice({+ plan,+ actionLabel,+ variant,+ isLoading,+ isDisabled,+ onSelect,+}: Props) {+ return (+ <li className="flex flex-col gap-3 rounded-[18px] border border-zinc-200 bg-white p-5 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">+ <Text variant="body-medium" as="h3" className="text-textBlack">+ {plan.label}+ </Text>+ <div className="flex flex-col gap-1">+ <p className="flex items-baseline gap-1.5">+ <Text+ variant="h4"+ as="span"+ unmask={false}+ className="text-textBlack"+ >+ {plan.amount}+ </Text>+ <Text variant="small" as="span" tone="muted">+ / {plan.cadence}+ </Text>+ </p>+ <Text variant="small" tone="secondary">+ {plan.description}+ </Text>+ </div>+ <Button+ variant={variant}+ size="small"+ className="mt-auto w-full"+ onClick={onSelect}+ disabled={isDisabled}+ loading={isLoading}+ >+ {actionLabel}+ </Button>+ </li>+ );+}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.tsxnew file mode 100644index 0000000000..df949e57a5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/TrialPlanChoices.tsx@@ -0,0 +1,62 @@+"use client";++import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";++import { ConfirmTrialPlanDialog } from "./ConfirmTrialPlanDialog";+import { PlanChoice } from "./PlanChoice";+import { useTrialPlanChoices } from "./useTrialPlanChoices";++interface Props {+ offer: TrialOfferResponse;+}++export function TrialPlanChoices({ offer }: Props) {+ const {+ isVisible,+ ownPlan,+ upgradePlan,+ ownPrice,+ requestedTier,+ isConfirmOpen,+ onSelectOwnPlan,+ onConfirmOwnPlan,+ onCloseConfirm,+ onSelectUpgradePlan,+ } = useTrialPlanChoices(offer);++ if (!isVisible) return null;+ const isBusy = requestedTier !== null;++ return (+ <section aria-label="Plan choices" className="flex flex-col gap-3">+ <ul className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <PlanChoice+ plan={ownPlan}+ actionLabel={`Subscribe to ${ownPlan.label}`}+ variant="primary"+ isLoading={requestedTier === ownPlan.tier}+ isDisabled={isBusy}+ onSelect={onSelectOwnPlan}+ />+ {upgradePlan ? (+ <PlanChoice+ plan={upgradePlan}+ actionLabel={`Upgrade to ${upgradePlan.label}`}+ variant="outline"+ isLoading={requestedTier === upgradePlan.tier}+ isDisabled={isBusy}+ onSelect={onSelectUpgradePlan}+ />+ ) : null}+ </ul>+ <ConfirmTrialPlanDialog+ isOpen={isConfirmOpen}+ planLabel={ownPlan.label}+ price={ownPrice}+ isSaving={requestedTier === ownPlan.tier}+ onConfirm={onConfirmOwnPlan}+ onClose={onCloseConfirm}+ />+ </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.tsnew file mode 100644index 0000000000..e4ecf2af47--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/helpers.ts@@ -0,0 +1,126 @@+import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";+import type { SubscriptionTierRequest } from "@/app/api/__generated__/models/subscriptionTierRequest";+import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import {+ formatPlanAmount,+ formatWholeMoney,+ trialPlanLabels,+} from "@/components/organisms/TrialCard/helpers";++import { getCheckoutReturnURLs } from "../helpers";++type PlanTier = TrialOfferResponse["tier"];++// Team (BUSINESS) is contact-sales, so it is never offered as a self-serve+// step up from a trial.+const SELF_SERVE_TIERS: readonly PlanTier[] = ["PRO", "MAX"];++export interface PlanChoiceDetails {+ tier: PlanTier;+ label: string;+ amount: string;+ cadence: "month" | "year";+ description: string;+ cents?: number;+}++export function getCancelPendingOffer(trial: TrialStatusResponse | undefined) {+ if (!trial?.offer || !trial.active || trial.converted) return null;+ return trial.cancel_at_period_end ? trial.offer : null;+}++export function getOwnPlanChoice(offer: TrialOfferResponse): PlanChoiceDetails {+ return {+ tier: offer.tier,+ label: trialPlanLabels[offer.tier],+ amount: formatPlanAmount(offer),+ cadence: getCadence(offer),+ description: "Starts today. Your trial ends and the plan takes over.",+ };+}++export function getUpgradePlanChoice(+ offer: TrialOfferResponse,+ subscription: SubscriptionStatusResponse,+): PlanChoiceDetails | null {+ const tier = getNextSelfServeTier(offer.tier);+ if (!tier) return null;+ const costs =+ offer.billing_cycle === "yearly"+ ? subscription.tier_costs_yearly+ : subscription.tier_costs;+ const cents = costs?.[tier];+ // The backend sends 0 when the price is unknown or has no such cycle.+ if (!cents) return null;+ return {+ tier,+ label: trialPlanLabels[tier],+ amount: formatWholeMoney(cents / 100, "usd"),+ cadence: getCadence(offer),+ description: describeUpgrade(+ offer.tier,+ tier,+ subscription.tier_multipliers,+ ),+ cents,+ };+}++// 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(+ plan: PlanChoiceDetails,+ tier: SubscriptionStatusResponse["tier"] | undefined,+) {+ if (tier === plan.tier)+ return {+ title: `You're on ${plan.label}`,+ description: "Your trial has ended and your plan starts today.",+ };+ return {+ title: "Payment received",+ description:+ "Your plan is still being set up. This page updates when it's ready.",+ };+}++export function buildPlanRequest(+ plan: PlanChoiceDetails,+ cycle: TrialOfferResponse["billing_cycle"],+): SubscriptionTierRequest {+ const { successURL, cancelURL } = getCheckoutReturnURLs({+ tier: plan.tier,+ cycle,+ });+ return {+ tier: plan.tier,+ billing_cycle: cycle,+ success_url: successURL,+ cancel_url: cancelURL,+ surface: "billing",+ };+}++function getNextSelfServeTier(tier: PlanTier) {+ const index = SELF_SERVE_TIERS.indexOf(tier);+ if (index === -1) return null;+ return SELF_SERVE_TIERS[index + 1] ?? null;+}++function describeUpgrade(+ own: PlanTier,+ upgrade: PlanTier,+ multipliers: Record<string, number> | undefined,+) {+ const ownLabel = trialPlanLabels[own];+ const ratio = (multipliers?.[upgrade] ?? 0) / (multipliers?.[own] ?? 0);+ if (!Number.isFinite(ratio) || ratio <= 1)+ return `More usage than ${ownLabel} for people who run a lot.`;+ const multiple = String(Math.round(ratio * 10) / 10);+ return `${multiple}x the usage of ${ownLabel} for people who run a lot.`;+}++function getCadence(offer: TrialOfferResponse) {+ return offer.billing_cycle === "yearly" ? "year" : "month";+}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.tsnew file mode 100644index 0000000000..2ff5a70542--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanChoices.ts@@ -0,0 +1,79 @@+"use client";++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,+ trackPlanSelected,+} from "@/services/analytics/monetization-analytics";++import {+ getOwnPlanChoice,+ getUpgradePlanChoice,+ type PlanChoiceDetails,+} from "./helpers";+import { useTrialPlanRequest } from "./useTrialPlanRequest";++export function useTrialPlanChoices(offer: TrialOfferResponse) {+ const userID = useAuthStore((state) => state.user?.id);+ const subscription = useGetSubscriptionStatus({+ query: {+ select: (res) =>+ res.status === 200+ ? (res.data as SubscriptionStatusResponse)+ : undefined,+ },+ });+ const { requestedTier, requestPlan } = useTrialPlanRequest(offer);+ const [confirmFor, setConfirmFor] = useState<string | 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.+ const isVisible = subscription.data?.tier === "TRIAL";+ const ownPlan = getOwnPlanChoice(offer);+ const upgradePlan = subscription.data+ ? getUpgradePlanChoice(offer, subscription.data)+ : null;++ useEffect(() => {+ if (isVisible) trackPaywallViewed("billing");+ }, [isVisible]);++ function trackSelection(plan: PlanChoiceDetails) {+ trackPlanSelected({+ subscription_tier: plan.tier,+ billing_cycle: offer.billing_cycle,+ surface: "billing",+ });+ }++ async function confirmOwnPlan() {+ const isLeaving = await requestPlan(ownPlan);+ if (!isLeaving) setConfirmFor(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),+ onSelectUpgradePlan: () => {+ if (!upgradePlan) return;+ trackSelection(upgradePlan);+ void requestPlan(upgradePlan);+ },+ };+}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.tsnew file mode 100644index 0000000000..766dabd6ce--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/TrialPlanChoices/useTrialPlanRequest.ts@@ -0,0 +1,119 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { useState } from "react";++import {+ getGetSubscriptionStatusQueryKey,+ getGetV1ListStripeInvoicesQueryKey,+ type getSubscriptionStatusResponse,+ useUpdateSubscriptionTier,+} from "@/app/api/__generated__/endpoints/credits/credits";+import { getGetTrialsGetTrialStatusQueryKey } from "@/app/api/__generated__/endpoints/trials/trials";+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 {+ buildPlanRequest,+ describePlanResult,+ type PlanChoiceDetails,+} from "./helpers";++export function useTrialPlanRequest(offer: TrialOfferResponse) {+ const userID = useAuthStore((state) => state.user?.id);+ const queryClient = useQueryClient();+ const { mutateAsync: updateTier } = useUpdateSubscriptionTier();+ const [requestedTier, setRequestedTier] = useState<+ PlanChoiceDetails["tier"] | null+ >(null);++ async function requestPlan(plan: PlanChoiceDetails) {+ if (!userID || requestedTier) return false;+ setRequestedTier(plan.tier);+ try {+ return 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);+ }+ }++ async function submitPlan(plan: PlanChoiceDetails, requestUserID: string) {+ try {+ // A plan changed in another tab would turn this into a plain plan+ // change, charged without the confirmation this page shows.+ if (!(await isStillOnTrial())) {+ toast({+ title: "Your plan changed",+ description: "Review your current plan below.",+ });+ await refreshBilling();+ return false;+ }+ 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;+ }+ const tier = response.status === 200 ? response.data.tier : undefined;+ toast(describePlanResult(plan, tier));+ await refreshBilling();+ } catch (error) {+ if (useAuthStore.getState().user?.id !== requestUserID) return false;+ // A toast, not an inline alert: the refresh below usually unmounts these+ // choices (the trial was resumed or ended elsewhere).+ toast({+ title: `Unable to start ${plan.label}`,+ description:+ error instanceof Error ? error.message : "Please try again.",+ variant: "destructive",+ });+ await refreshBilling();+ }+ return false;+ }++ async function isStillOnTrial() {+ const queryKey = getGetSubscriptionStatusQueryKey();+ await queryClient.refetchQueries({ queryKey, exact: true });+ const response =+ queryClient.getQueryData<getSubscriptionStatusResponse>(queryKey);+ return readTier(response) === "TRIAL";+ }++ async function refreshBilling() {+ await Promise.all(+ [+ getGetTrialsGetTrialStatusQueryKey(),+ getGetSubscriptionStatusQueryKey(),+ getGetV1ListStripeInvoicesQueryKey(),+ ].map((queryKey) => queryClient.invalidateQueries({ queryKey })),+ );+ }++ 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,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.tsindex 1ac0ed7274..f0c29bb51e 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts@@ -25,6 +25,7 @@ import {} from "@/services/analytics/monetization-analytics";import { formatCents, formatShortDate } from "../../../helpers";+import { getCheckoutReturnURLs } from "../helpers";const PLAN_LABEL: Record<string, string> = {NO_TIER: "No active subscription",@@ -238,16 +239,13 @@ export function useYourPlanCard() {billingCycle?: SubscriptionTierRequestBillingCycle,) {const cycle = billingCycle ?? "monthly";- // Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page- // report the subscription to Google Ads.- const successUrl = `${window.location.origin}${window.location.pathname}?subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${tier}&cycle=${cycle}`;- const cancelUrl = `${window.location.origin}${window.location.pathname}?subscription=cancelled`;+ const { successURL, cancelURL } = getCheckoutReturnURLs({ tier, cycle });try {const result = await updateTier({data: {tier,- success_url: successUrl,- cancel_url: cancelUrl,+ success_url: successURL,+ cancel_url: cancelURL,...(billingCycle ? { billing_cycle: billingCycle } : {}),surface: "billing",},diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/helpers.tsnew file mode 100644index 0000000000..efb5a1f220--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/helpers.ts@@ -0,0 +1,35 @@+import type { getSubscriptionStatusResponse } from "@/app/api/__generated__/endpoints/credits/credits";+import type { SubscriptionStatusResponseTier } from "@/app/api/__generated__/models/subscriptionStatusResponseTier";+import type { SubscriptionTierRequestBillingCycle } from "@/app/api/__generated__/models/subscriptionTierRequestBillingCycle";+import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";++interface CheckoutReturnArgs {+ tier: SubscriptionTierRequestTier;+ cycle: SubscriptionTierRequestBillingCycle;+}++// Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page+// report the subscription to Google Ads.+export function getCheckoutReturnURLs({ tier, cycle }: CheckoutReturnArgs) {+ const page = `${window.location.origin}${window.location.pathname}`;+ return {+ successURL: `${page}?subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${tier}&cycle=${cycle}`,+ cancelURL: `${page}?subscription=cancelled`,+ };+}++const PAID_TIERS: readonly SubscriptionStatusResponseTier[] = [+ "BASIC",+ "PRO",+ "MAX",+ "BUSINESS",+ "ENTERPRISE",+];++export function isPaidTier(tier: SubscriptionStatusResponseTier | undefined) {+ return tier !== undefined && PAID_TIERS.includes(tier);+}++export function readTier(response: getSubscriptionStatusResponse | undefined) {+ return response?.status === 200 ? response.data.tier : undefined;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/usePlanCheckoutReturn.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/usePlanCheckoutReturn.tsnew file mode 100644index 0000000000..30464f2ea4--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/usePlanCheckoutReturn.ts@@ -0,0 +1,45 @@+"use client";++import { useEffect, useState } from "react";++import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { useTrialStatus } from "@/services/trials/useTrialStatus";++import { readTier } from "./helpers";++const POLL_MS = 2_000;+const GIVE_UP_MS = 30_000;++// Stripe returns the person before the webhook ends the trial and sets the new+// plan, so a plan bought during a cancel-pending trial is checked for until it+// lands, and no second purchase is offered meanwhile.+export function usePlanCheckoutReturn(isCheckoutReturn: boolean) {+ const [hasGivenUp, setHasGivenUp] = useState(false);+ const isWatching = isCheckoutReturn && !hasGivenUp;+ const tier = useGetSubscriptionStatus({+ query: {+ select: readTier,+ refetchInterval: (query) =>+ isWatching && readTier(query.state.data) === "TRIAL" ? POLL_MS : false,+ },+ });+ useTrialStatus({+ refetchInterval: (trial) =>+ isWatching && isCancelPending(trial) ? POLL_MS : false,+ });++ useEffect(() => {+ if (!isCheckoutReturn) return;+ const timer = setTimeout(() => setHasGivenUp(true), GIVE_UP_MS);+ return () => clearTimeout(timer);+ }, [isCheckoutReturn]);++ return {+ isConfirmingPlan: isWatching && (tier.isPending || tier.data === "TRIAL"),+ };+}++function isCancelPending(trial: TrialStatusResponse | undefined) {+ return Boolean(trial?.active && trial.cancel_at_period_end);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/useSubscriptionTab.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/useSubscriptionTab.tsnew file mode 100644index 0000000000..ed9b167090--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/useSubscriptionTab.ts@@ -0,0 +1,36 @@+"use client";++import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";+import { useTrialStatus } from "@/services/trials/useTrialStatus";++import { isPaidTier, readTier } from "./helpers";+import { getCancelPendingOffer } from "./TrialPlanChoices/helpers";+import { usePlanCheckoutReturn } from "./usePlanCheckoutReturn";++export function useSubscriptionTab(isPlanCheckoutReturn: boolean) {+ const { data: trial, isLoading } = useTrialStatus();+ const tier = useGetSubscriptionStatus({ query: { select: readTier } });+ const { isConfirmingPlan } = usePlanCheckoutReturn(isPlanCheckoutReturn);+ // An ended trial that a paid plan replaced is history, not the plan; it+ // waits for the tier so it never flashes above the plan card.+ const isEndedTrial = Boolean(trial && !trial.eligible && !trial.active);+ const hasPaidPlan = isPaidTier(tier.data);+ const isReplaced = tier.isPending || hasPaidPlan;+ // A plan bought during a cancel-pending trial is the plan even while the+ // trial row still reads active (its stale-subscription cleanup failed).+ const isSupersededTrial = Boolean(+ trial?.active &&+ trial.cancel_at_period_end &&+ !trial.converted &&+ hasPaidPlan,+ );+ const cancelPendingOffer = getCancelPendingOffer(trial);++ return {+ showPlan:+ !isLoading && (!trial?.active || trial.converted || isSupersededTrial),+ showTrialCard: !(isEndedTrial && isReplaced) && !isSupersededTrial,+ planChoicesOffer: isConfirmingPlan ? null : cancelPendingOffer,+ isConfirmingPlan: Boolean(cancelPendingOffer) && isConfirmingPlan,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsxindex b7d5ec16d1..0ef58f229c 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx@@ -16,6 +16,7 @@ import {getGetSubscriptionStatusQueryKey,usePatchV1FulfillCheckoutSession,} from "@/app/api/__generated__/endpoints/credits/credits";+import { getGetTrialsGetTrialStatusQueryKey } from "@/app/api/__generated__/endpoints/trials/trials";import {trackCheckoutAbandoned,@@ -54,6 +55,10 @@ export default function SettingsBillingPage() {const [activeTab, setActiveTab] = useState<BillingTab>(() =>resolveInitialTab(searchParams),);+ // Read once: the redirect handler below drops the query string.+ const [isPlanCheckoutReturn] = useState(+ () => subscriptionStatus === "success",+ );function handleTabChange(value: string) {if (isBillingTab(value)) setActiveTab(value);@@ -110,6 +115,9 @@ export default function SettingsBillingPage() {queryClient.invalidateQueries({queryKey: getGetSubscriptionStatusQueryKey(),});+ queryClient.invalidateQueries({+ queryKey: getGetTrialsGetTrialStatusQueryKey(),+ });} else if (subscriptionStatus === "cancelled") {trackCheckoutAbandoned({checkout_kind: "subscription",@@ -149,7 +157,7 @@ export default function SettingsBillingPage() {</TabsLineList><TabsLineContent value="subscription">- <SubscriptionTab />+ <SubscriptionTab isPlanCheckoutReturn={isPlanCheckoutReturn} /></TabsLineContent><TabsLineContent value="automation-credits">diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 2e197f6148..b2f690f754 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -6148,6 +6148,31 @@"security": [{ "HTTPBearerJWT": [] }]}},+ "/api/credits/trial/resume": {+ "post": {+ "tags": ["trials"],+ "summary": "Resume Trial",+ "operationId": "postTrialsResumeTrial",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/TrialStatusResponse" }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "409": {+ "description": "No live cancel-pending trial to resume, another plan is active, or the trial is already being updated"+ },+ "502": { "description": "Stripe update temporarily unavailable" }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },"/api/credits/{transaction_key}/refund": {"post": {"tags": ["v1", "credits"],diff --git a/autogpt_platform/frontend/src/components/organisms/SubscriptionPlans/components/PlanDetailsDialog/components/TrialDetails.tsx b/autogpt_platform/frontend/src/components/organisms/SubscriptionPlans/components/PlanDetailsDialog/components/TrialDetails.tsxindex 032e76615d..0ef847d48b 100644--- a/autogpt_platform/frontend/src/components/organisms/SubscriptionPlans/components/PlanDetailsDialog/components/TrialDetails.tsx+++ b/autogpt_platform/frontend/src/components/organisms/SubscriptionPlans/components/PlanDetailsDialog/components/TrialDetails.tsx@@ -37,8 +37,8 @@ export function TrialDetails({ offer }: Props) {cancel before it ends.</Text><Text variant="body" tone="secondary">- Trial usage is limited. Canceling ends trial access immediately. You can- manage or cancel your plan in billing.+ Trial usage is limited. If you cancel, you keep access until the trial+ ends. You can manage or cancel your plan in billing.</Text></div>);diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/CancelTrialDialog.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/CancelTrialDialog.tsxindex 7533e52d68..b84aaf28ed 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/CancelTrialDialog.tsx+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/CancelTrialDialog.tsx@@ -1,14 +1,17 @@import { useState } from "react";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { formatTrialEnd } from "./helpers";interface Props {+ trial: TrialStatusResponse;isCanceling: boolean;onCancel: () => void;}-export function CancelTrialDialog({ isCanceling, onCancel }: Props) {+export function CancelTrialDialog({ trial, isCanceling, onCancel }: Props) {const [isOpen, setIsOpen] = useState(false);function confirmCancellation() {@@ -18,8 +21,8 @@ export function CancelTrialDialog({ isCanceling, onCancel }: Props) {return (<Dialog- title="End your trial now?"- styling={{ maxWidth: "440px" }}+ title="Cancel your trial?"+ styling={{ maxWidth: "28rem", minWidth: "auto" }}controlled={{ isOpen, set: setIsOpen }}><Dialog.Trigger>@@ -33,20 +36,29 @@ export function CancelTrialDialog({ isCanceling, onCancel }: Props) {</Button></Dialog.Trigger><Dialog.Content>- <Text variant="body">- Your trial access will end immediately and your trial will not convert- to a paid plan. You cannot restart this trial.- </Text>+ <div className="flex flex-col gap-3">+ <Text variant="body" className="!text-zinc-800">+ Your trial won't convert to a paid plan and your card+ won't be charged.+ </Text>+ <Text variant="body" unmask={false} className="!text-zinc-800">+ You keep full access until{" "}+ <strong className="font-semibold">+ {formatTrialEnd(trial.ends_at)}+ </strong>+ , and you can resume your trial any time before then.+ </Text>+ </div><Dialog.Footer><Button variant="outline" onClick={() => setIsOpen(false)}>Keep trial</Button><Button- variant="destructive"+ variant="primary"onClick={confirmCancellation}disabled={isCanceling}>- End trial now+ Cancel trial</Button></Dialog.Footer></Dialog.Content>diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCancelPending.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCancelPending.tsxnew file mode 100644index 0000000000..4e6758629c--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCancelPending.tsx@@ -0,0 +1,63 @@+import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import {+ formatPlanPrice,+ formatTrialEnd,+ formatTrialEndDate,+ trialPlanLabels,+} from "./helpers";+import { TrialTitle } from "./TrialTitle/TrialTitle";++interface Props {+ trial: TrialStatusResponse;+ offer: TrialOfferResponse;+ isResuming: boolean;+ onResume: () => void;+}++export function TrialCancelPending({+ trial,+ offer,+ isResuming,+ onResume,+}: Props) {+ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <TrialTitle>Your trial</TrialTitle>+ <span className="inline-flex items-center gap-1.5 rounded-full bg-zinc-100 px-2 py-0.5 text-xs text-zinc-700">+ <span aria-hidden className="size-1.5 rounded-full bg-zinc-400" />+ Cancellation pending+ </span>+ </div>+ <Text variant="body" unmask={false} className="!text-zinc-800">+ Cancellation confirmed. Your trial will not convert to a paid plan and+ your card won't be charged. Trial access ends{" "}+ <strong className="font-semibold">+ {formatTrialEnd(trial.ends_at)}+ </strong>+ .+ </Text>+ {trial.ends_at ? (+ <Text variant="small" unmask={false} className="!text-zinc-500">+ Resume to keep the trial and start {trialPlanLabels[offer.tier]} on{" "}+ {formatTrialEndDate(trial.ends_at)} at {formatPlanPrice(offer)}, plus+ applicable tax.+ </Text>+ ) : null}+ <div className="mt-1">+ <Button+ variant="secondary"+ size="small"+ loading={isResuming}+ disabled={isResuming}+ onClick={onResume}+ >+ Resume trial+ </Button>+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/TrialCanceledDialog.stories.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/TrialCanceledDialog.stories.tsxnew file mode 100644index 0000000000..ef6cc3e103--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/TrialCanceledDialog.stories.tsx@@ -0,0 +1,50 @@+import type { Meta, StoryObj } from "@storybook/nextjs";+import { TrialCanceledDialog } from "./TrialCanceledDialog";++const DAY_MS = 24 * 60 * 60 * 1000;++const meta = {+ title: "Organisms/TrialCanceledDialog",+ component: TrialCanceledDialog,+ args: {+ trial: {+ active: true,+ status: "trialing",+ ends_at: new Date(Date.now() + 5 * DAY_MS),+ cancel_at_period_end: true,+ offer: {+ token: "a".repeat(64),+ version: "storybook-trial",+ duration_days: 7,+ tier: "PRO",+ billing_cycle: "monthly",+ unit_amount: 5000,+ currency: "usd",+ onboarding_credit_amount: 300,+ },+ },+ isOpen: true,+ isResuming: false,+ onResume: function onResume() {},+ onSubscribe: function onSubscribe() {},+ onClose: function onClose() {},+ },+} satisfies Meta<typeof TrialCanceledDialog>;++export default meta;+type Story = StoryObj<typeof meta>;++export const DaysLeft: Story = {};++export const UnderADay: Story = {+ args: {+ trial: {+ ...meta.args.trial,+ ends_at: new Date(Date.now() + 3 * 60 * 60 * 1000),+ },+ },+};++export const Resuming: Story = {+ args: { isResuming: true },+};diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/TrialCanceledDialog.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/TrialCanceledDialog.tsxnew file mode 100644index 0000000000..f6d28b9e65--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/TrialCanceledDialog.tsx@@ -0,0 +1,61 @@+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { TrialTimeLeft } from "./components/TrialTimeLeft";+import { WorthDoingPanel } from "./components/WorthDoingPanel";++interface Props {+ trial: TrialStatusResponse;+ isOpen: boolean;+ isResuming: boolean;+ onResume: () => void;+ onSubscribe: () => void;+ onClose: () => void;+}++export function TrialCanceledDialog({+ trial,+ isOpen,+ isResuming,+ onResume,+ onSubscribe,+ onClose,+}: Props) {+ if (!trial.offer) return null;+ return (+ <Dialog+ title="Cancellation confirmed"+ styling={{ maxWidth: "29rem", minWidth: "auto" }}+ controlled={{+ isOpen,+ set: (open) => {+ if (!open) onClose();+ },+ }}+ >+ <Dialog.Content>+ <div className="flex flex-col gap-4">+ <Text variant="body" unmask={false} className="!text-zinc-800">+ Your card won't be charged.{" "}+ <TrialTimeLeft endsAt={trial.ends_at} />+ </Text>+ <WorthDoingPanel offer={trial.offer} endsAt={trial.ends_at} />+ </div>+ <Dialog.Footer>+ <Button+ variant="outline"+ onClick={onResume}+ loading={isResuming}+ disabled={isResuming}+ >+ Resume trial+ </Button>+ <Button variant="primary" onClick={onSubscribe}>+ Subscribe now+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/components/TrialTimeLeft.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/components/TrialTimeLeft.tsxnew file mode 100644index 0000000000..b09dc4e882--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/components/TrialTimeLeft.tsx@@ -0,0 +1,41 @@+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import {+ describeTrialTimeLeft,+ formatTrialDays,+ formatTrialEnd,+} from "../../helpers";++interface Props {+ endsAt: TrialStatusResponse["ends_at"];+}++export function TrialTimeLeft({ endsAt }: Props) {+ if (!endsAt)+ return (+ <>+ You still have full access until your trial ends. Nothing changes until+ then.+ </>+ );+ const left = describeTrialTimeLeft(endsAt);+ if (left.kind === "ended") return <>Your trial access has ended.</>;+ if (left.kind !== "days")+ return (+ <>+ You still have full access until{" "}+ <strong className="font-semibold">+ {left.time} {left.kind}+ </strong>+ . Nothing changes until then.+ </>+ );+ return (+ <>+ You still have{" "}+ <strong className="font-semibold">{formatTrialDays(left.days)}</strong> of+ full access, until{" "}+ <strong className="font-semibold">{formatTrialEnd(endsAt)}</strong>.+ Nothing changes until then.+ </>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/components/WorthDoingPanel.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/components/WorthDoingPanel.tsxnew file mode 100644index 0000000000..748a3d8316--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCanceledDialog/components/WorthDoingPanel.tsx@@ -0,0 +1,75 @@+import {+ Clock01Icon,+ DollarSignIcon,+ Note01Icon,+} from "@hugeicons/core-free-icons";+import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import {+ describeTrialTimeLeft,+ formatPlanPrice,+ formatTrialEndDate,+ trialPlanLabels,+} from "../../helpers";++interface Props {+ offer: TrialOfferResponse;+ endsAt: Date | string | null | undefined;+}++export function WorthDoingPanel({ offer, endsAt }: Props) {+ const planStart = describePlanStart(endsAt);+ const resumeNote = planStart+ ? ` Resume your trial instead and your plan starts ${planStart}.`+ : "";+ const rows = [+ {+ icon: Clock01Icon,+ title: "Put an Expert on a schedule",+ body: 'Say "do this every Monday at 8am" to any Expert. It runs while you\'re away and the result is waiting on Home.',+ },+ {+ icon: Note01Icon,+ title: "Your work stays",+ body: "Chats, Experts and schedules stay on your account. Subscribe later and you pick up where you left off.",+ },+ {+ icon: DollarSignIcon,+ title: "Subscribe any time",+ body: `${trialPlanLabels[offer.tier]} is ${formatPlanPrice(offer)}, cancel anytime.${resumeNote}`,+ },+ ];++ return (+ <div className="rounded-xl border border-zinc-200 bg-zinc-50 px-4 pt-3">+ <Text variant="eyebrow" as="h3">+ Worth doing before then+ </Text>+ <ul className="divide-y divide-zinc-200">+ {rows.map((row) => (+ <li key={row.title} className="flex gap-3 py-3">+ <span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-violet-100">+ <Icon icon={row.icon} size={14} className="text-violet-700" />+ </span>+ <div className="flex min-w-0 flex-col gap-0.5">+ <Text variant="body-medium" className="!text-zinc-900">+ {row.title}+ </Text>+ <Text variant="small" unmask={false} className="!text-zinc-600">+ {row.body}+ </Text>+ </div>+ </li>+ ))}+ </ul>+ </div>+ );+}++function describePlanStart(endsAt: Props["endsAt"]) {+ if (!endsAt) return null;+ const left = describeTrialTimeLeft(endsAt);+ if (left.kind === "ended") return null;+ return left.kind === "days" ? formatTrialEndDate(endsAt) : left.kind;+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsxindex 4673e5a1f3..5388ac2949 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx@@ -4,6 +4,7 @@ import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { Text } from "@/components/atoms/Text/Text";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";import { cn } from "@/lib/utils";+import { TrialCanceledDialog } from "./TrialCanceledDialog/TrialCanceledDialog";import { TrialOffer } from "./TrialOffer";import { TrialStatus } from "./TrialStatus";import { useTrialCard } from "./useTrialCard";@@ -30,8 +31,13 @@ export function TrialCardContent({retry,isStarting,isCanceling,+ isResuming,startTrial,cancelTrial,+ resumeTrial,+ showCanceledDialog,+ dismissCanceledDialog,+ subscribeNow,} = controller;const isBilling = returnTo === "billing";if (isLoading)@@ -65,6 +71,8 @@ export function TrialCardContent({trial={trial}isCanceling={isCanceling}onCancel={cancelTrial}+ isResuming={isResuming}+ onResume={resumeTrial}/>)}{error ? (@@ -72,6 +80,14 @@ export function TrialCardContent({{error}</p>) : null}+ <TrialCanceledDialog+ trial={trial}+ isOpen={showCanceledDialog}+ isResuming={isResuming}+ onResume={resumeTrial}+ onSubscribe={subscribeNow}+ onClose={dismissCanceledDialog}+ /></>);if (isBilling)diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsxindex dfbedeeddb..a92eadd149 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx@@ -31,8 +31,8 @@ export function TrialOffer({ trial, isStarting, onStart }: Props) {before the trial ends.</Text><Text variant="small" className="!text-zinc-500">- Trial usage is limited. Canceling ends trial access immediately. You- can manage your plan in billing.+ Trial usage is limited. If you cancel, you keep access until the trial+ ends. You can manage your plan in billing.</Text></div><Buttondiff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.stories.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.stories.tsxindex 25c9b86bb9..e6356af7f8 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.stories.tsx+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.stories.tsx@@ -23,6 +23,8 @@ const meta = {},isCanceling: false,onCancel: function onCancel() {},+ isResuming: false,+ onResume: function onResume() {},},} satisfies Meta<typeof TrialStatus>;@@ -31,6 +33,15 @@ type Story = StoryObj<typeof meta>;export const Active: Story = {};+export const CancelPending: Story = {+ args: {+ trial: {+ ...meta.args.trial,+ cancel_at_period_end: true,+ },+ },+};+export const Canceled: Story = {args: {trial: { ...meta.args.trial, active: false, status: "canceled" },diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsxindex 11c3725e4b..65ede83fdf 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialStatus.tsx@@ -2,6 +2,7 @@ import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStimport { Text } from "@/components/atoms/Text/Text";import { CancelTrialDialog } from "./CancelTrialDialog";import { formatTrialEnd, formatTrialPrice } from "./helpers";+import { TrialCancelPending } from "./TrialCancelPending";import { TrialRejection } from "./TrialRejection";import { TrialTitle } from "./TrialTitle/TrialTitle";@@ -9,12 +10,29 @@ interface Props {trial: TrialStatusResponse;isCanceling: boolean;onCancel: () => void;+ isResuming: boolean;+ onResume: () => void;}-export function TrialStatus({ trial, isCanceling, onCancel }: Props) {+export function TrialStatus({+ trial,+ isCanceling,+ onCancel,+ isResuming,+ onResume,+}: Props) {if (!trial.offer) return null;if (trial.status === "canceled" && trial.rejection_reason)return <TrialRejection reason={trial.rejection_reason} />;+ if (trial.active && trial.cancel_at_period_end)+ return (+ <TrialCancelPending+ trial={trial}+ offer={trial.offer}+ isResuming={isResuming}+ onResume={onResume}+ />+ );const end = formatTrialEnd(trial.ends_at);return (<div className="flex flex-col gap-3">@@ -30,14 +48,13 @@ export function TrialStatus({ trial, isCanceling, onCancel }: Props) {? `Your trial ends ${end}. Your saved card will then be charged ${formatTrialPrice(trial.offer)}, plus applicable tax.`: "Paid access requires a successful payment. Review your payment method and plan below."}</Text>- {trial.active ? (- <Text variant="small" className="!text-zinc-500">- Canceling ends trial access immediately.- </Text>- ) : null}{trial.active && !trial.cancel_at_period_end ? (<div className="mt-1">- <CancelTrialDialog isCanceling={isCanceling} onCancel={onCancel} />+ <CancelTrialDialog+ trial={trial}+ isCanceling={isCanceling}+ onCancel={onCancel}+ /></div>) : null}</div>diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/__tests__/helpers.test.tsnew file mode 100644index 0000000000..6c33c2a1cd--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/__tests__/helpers.test.ts@@ -0,0 +1,93 @@+import { afterEach, describe, expect, it } from "vitest";+import {+ describeTrialTimeLeft,+ formatTrialDays,+ formatTrialEndTime,+ getTrialDaysLeft,+} from "../helpers";++// Deleting TZ leaves Node on the last zone set, so restore the zone by name.+const realTimeZone =+ process.env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone;+afterEach(() => {+ process.env.TZ = realTimeZone;+});++const HOUR = 60 * 60 * 1000;+const DAY = 24 * HOUR;+const end = new Date("2030-09-17T15:00:00Z");++describe("getTrialDaysLeft", () => {+ it.each([+ [5 * DAY, 5],+ [4 * DAY + 1, 5],+ [DAY, 1],+ [3 * HOUR, 1],+ [0, 0],+ [-HOUR, 0],+ ])("rounds %ims left up to %i days", (left, days) => {+ expect(getTrialDaysLeft(end, end.getTime() - left)).toBe(days);+ });++ it("counts no days without an end", () => {+ expect(getTrialDaysLeft(null)).toBe(0);+ });+});++describe("formatTrialDays", () => {+ it.each([+ [1, "1 day"],+ [2, "2 days"],+ [5, "5 days"],+ ])("reads %i as %s", (days, label) => {+ expect(formatTrialDays(days)).toBe(label);+ });+});++describe("describeTrialTimeLeft", () => {+ it.each([+ [5 * DAY, 5],+ [DAY, 1],+ [DAY + HOUR, 2],+ ])("counts whole days when %ims are left", (left, days) => {+ expect(describeTrialTimeLeft(end, new Date(end.getTime() - left))).toEqual({+ kind: "days",+ days,+ });+ });++ it("reads under a day on the same local date as today", () => {+ const localEnd = new Date(2030, 8, 17, 14, 10);+ expect(+ describeTrialTimeLeft(localEnd, new Date(2030, 8, 17, 11, 10)),+ ).toEqual({ kind: "today", time: formatTrialEndTime(localEnd) });+ });++ it("reads under a day past local midnight as tomorrow", () => {+ const localEnd = new Date(2030, 8, 17, 1, 0);+ expect(+ describeTrialTimeLeft(localEnd, new Date(2030, 8, 16, 22, 0)),+ ).toEqual({ kind: "tomorrow", time: formatTrialEndTime(localEnd) });+ });++ it("dates an end under a day away that falls two calendar days out", () => {+ process.env.TZ = "America/New_York";+ const now = new Date(2026, 2, 7, 23, 30);+ const localEnd = new Date(2026, 2, 9, 0, 10);+ expect(localEnd.getTime() - now.getTime()).toBeLessThan(DAY);+ expect(describeTrialTimeLeft(localEnd, now)).toEqual({+ kind: "days",+ days: 1,+ });+ });++ it.each([+ ["earlier the same day", new Date(2030, 8, 17, 14, 0)],+ ["just before midnight", new Date(2030, 8, 16, 23, 58)],+ ["right now", new Date(2030, 8, 17, 15, 0)],+ ])("never reads an end %s as today", (_, localEnd) => {+ expect(+ describeTrialTimeLeft(localEnd, new Date(2030, 8, 17, 15, 0)),+ ).toEqual({ kind: "ended" });+ });+});diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.tsindex b8356d34fb..859f5863d2 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts@@ -11,7 +11,29 @@ export function formatTrialPrice(offer: TrialOfferResponse) {const amount = currencyFormatter(offer.currency).format(getTrialChargeAmount(offer),);- return `${amount} / ${offer.billing_cycle === "yearly" ? "year" : "month"}`;+ return `${amount} / ${getTrialCadence(offer)}`;+}++// The cancel-pending screens drop the cents of a whole price ("$50 / month")+// and keep them otherwise ("$19.99 / month").+export function formatPlanPrice(offer: TrialOfferResponse) {+ return `${formatPlanAmount(offer)} / ${getTrialCadence(offer)}`;+}++export function formatPlanAmount(offer: TrialOfferResponse) {+ return formatWholeMoney(getTrialChargeAmount(offer), offer.currency);+}++export function formatWholeMoney(amount: number, currency: string) {+ return new Intl.NumberFormat("en-US", {+ style: "currency",+ currency,+ trailingZeroDisplay: "stripIfInteger",+ }).format(amount);+}++function getTrialCadence(offer: TrialOfferResponse) {+ return offer.billing_cycle === "yearly" ? "year" : "month";}// What Stripe charges per billing cycle once the trial ends, in major units.@@ -34,3 +56,52 @@ export function formatTrialEnd(value: Date | string | null | undefined) {timeStyle: "short",});}++export function formatTrialEndDate(value: Date | string) {+ return new Date(value).toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ });+}++export function formatTrialEndTime(value: Date | string) {+ return new Date(value).toLocaleTimeString(undefined, { timeStyle: "short" });+}++const DAY_MS = 24 * 60 * 60 * 1000;++export function getTrialDaysLeft(+ endsAt: Date | string | null | undefined,+ now = Date.now(),+) {+ if (!endsAt) return 0;+ return Math.max(0, Math.ceil((new Date(endsAt).getTime() - now) / DAY_MS));+}++export function formatTrialDays(days: number) {+ return `${days} ${days === 1 ? "day" : "days"}`;+}++// Under a day the count would always read "1 day", so name the clock time,+// but only for today or tomorrow: a DST day can put an end under 24 hours+// away two dates out, and that keeps the dated form.+export function describeTrialTimeLeft(endsAt: Date | string, now = new Date()) {+ const end = new Date(endsAt);+ const left = end.getTime() - now.getTime();+ if (left <= 0) return { kind: "ended" as const };+ const day = left < DAY_MS ? getNearDay(end, now) : null;+ if (day) return { kind: day, time: formatTrialEndTime(end) };+ return {+ kind: "days" as const,+ days: getTrialDaysLeft(end, now.getTime()),+ };+}++function getNearDay(end: Date, now: Date) {+ const tomorrow = new Date(now);+ tomorrow.setDate(now.getDate() + 1);+ if (end.toDateString() === now.toDateString()) return "today" as const;+ if (end.toDateString() === tomorrow.toDateString())+ return "tomorrow" as const;+ return null;+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCanceledDialog.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCanceledDialog.tsnew file mode 100644index 0000000000..02a146c078--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCanceledDialog.ts@@ -0,0 +1,50 @@+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { TrialEvent } from "@/services/analytics/posthog-events";+import { usePostHog } from "@posthog/react";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { getTrialDaysLeft } from "./helpers";++type EndsAt = TrialStatusResponse["ends_at"];++interface Args {+ userID: string | undefined;+ endsAt: EndsAt;+}++interface OpenArgs {+ ownerID: string;+ endsAt: EndsAt;+}++export function useTrialCanceledDialog({ userID, endsAt }: Args) {+ const posthog = usePostHog();+ const router = useRouter();+ // Opened by this tab's own cancel, never by server state, so a reload or+ // another account never shows it.+ const [openFor, setOpenFor] = useState<string | null>(null);++ function openDialog(args: OpenArgs) {+ setOpenFor(args.ownerID);+ posthog?.capture(TrialEvent.TRIAL_CANCEL_POPUP_VIEWED, {+ days_left: getTrialDaysLeft(args.endsAt),+ });+ }++ function subscribeNow() {+ posthog?.capture(TrialEvent.TRIAL_SUBSCRIBE_NOW_CLICKED, {+ days_left: getTrialDaysLeft(endsAt),+ });+ setOpenFor(null);+ router.push("/settings/billing");+ }++ return {+ isOpen: openFor !== null && openFor === userID,+ openDialog,+ closeDialog: () => setOpenFor(null),+ closeDialogFor: (ownerID: string) =>+ setOpenFor((current) => (current === ownerID ? null : current)),+ subscribeNow,+ };+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCancellation.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCancellation.tsnew file mode 100644index 0000000000..1c4f1b8090--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCancellation.ts@@ -0,0 +1,93 @@+import {+ usePostTrialsCancelTrial,+ usePostTrialsResumeTrial,+} from "@/app/api/__generated__/endpoints/trials/trials";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { TrialEvent } from "@/services/analytics/posthog-events";+import { updateTrialStatusCache } from "@/services/trials/updateTrialStatusCache";+import type { useTrialStatus } from "@/services/trials/useTrialStatus";+import { useQueryClient } from "@tanstack/react-query";+import { usePostHog } from "@posthog/react";+import { getTrialDaysLeft } from "./helpers";+import { useTrialCanceledDialog } from "./useTrialCanceledDialog";+import type { useTrialFailure } from "./useTrialFailure";++const CANCEL_FAILED = "Unable to cancel your trial.";+const RESUME_FAILED = "Unable to resume your trial.";++interface Args {+ userID: string | undefined;+ query: ReturnType<typeof useTrialStatus>;+ failure: ReturnType<typeof useTrialFailure>;+}++export function useTrialCancellation({ userID, query, failure }: Args) {+ const queryClient = useQueryClient();+ const posthog = usePostHog();+ const dialog = useTrialCanceledDialog({+ userID,+ endsAt: query.data?.ends_at,+ });+ const { mutateAsync: cancel, isPending: isCanceling } =+ usePostTrialsCancelTrial();+ const { mutateAsync: resume, isPending: isResuming } =+ usePostTrialsResumeTrial();++ async function cancelTrial() {+ if (!userID || isCanceling) return;+ failure.clearFailure();+ try {+ const response = await cancel();+ if (useAuthStore.getState().user?.id !== userID) return;+ if (response.status !== 200) throw new Error(CANCEL_FAILED);+ const trial = response.data;+ await updateTrialStatusCache({+ queryClient,+ userID,+ response,+ onApplied: () => {+ if (isCancelPending(trial))+ dialog.openDialog({ ownerID: userID, endsAt: trial.ends_at });+ },+ });+ } catch (error) {+ failure.reportFailure({ userID, error, fallback: CANCEL_FAILED });+ await query.refetch();+ }+ }++ async function resumeTrial() {+ if (!userID || isResuming) return;+ posthog?.capture(TrialEvent.TRIAL_RESUME_CLICKED, {+ days_left: getTrialDaysLeft(query.data?.ends_at),+ });+ failure.clearFailure();+ try {+ const response = await resume();+ if (useAuthStore.getState().user?.id !== userID) return;+ if (response.status !== 200) throw new Error(RESUME_FAILED);+ await updateTrialStatusCache({ queryClient, userID, response });+ } catch (error) {+ failure.reportFailure({ userID, error, fallback: RESUME_FAILED });+ await query.refetch();+ } finally {+ // Only this account's popup: another account may have opened its own.+ dialog.closeDialogFor(userID);+ }+ }++ return {+ isCanceling,+ isResuming,+ cancelTrial,+ resumeTrial,+ showCanceledDialog: dialog.isOpen,+ dismissCanceledDialog: dialog.closeDialog,+ subscribeNow: dialog.subscribeNow,+ };+}++function isCancelPending(trial: TrialStatusResponse) {+ return Boolean(trial.active && trial.cancel_at_period_end);+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.tsindex 58f074b1a8..1f6f8c0e6e 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts@@ -1,62 +1,40 @@-import {- usePostTrialsCancelTrial,- usePostTrialsStartTrialCheckout,-} from "@/app/api/__generated__/endpoints/trials/trials";+import { usePostTrialsStartTrialCheckout } from "@/app/api/__generated__/endpoints/trials/trials";import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";import { trackAdsConversionBeforeNavigation } from "@/services/analytics/google-ads";import { markTrialCheckoutStarted } from "@/services/analytics/monetization-analytics";-import { TrialEvent } from "@/services/analytics/posthog-events";import { useTrialStatus } from "@/services/trials/useTrialStatus";-import { updateTrialStatusCache } from "@/services/trials/updateTrialStatusCache";-import { useQueryClient } from "@tanstack/react-query";-import { usePostHog } from "@posthog/react";-import { useEffect, useRef, useState } from "react";+import { useState } from "react";import { getTrialChargeAmount } from "./helpers";+import { useTrialCancellation } from "./useTrialCancellation";+import { useTrialFailure } from "./useTrialFailure";+import { useTrialOfferViewed } from "./useTrialOfferViewed";++const CHECKOUT_FAILED = "Unable to start trial checkout.";export function useTrialCard(returnTo: "onboarding" | "billing") {const userID = useAuthStore((state) => state.user?.id);- const queryClient = useQueryClient();- const posthog = usePostHog();- const seenOffer = useRef<string | null>(null);- const [failure, setFailure] = useState<{- userID: string;- message: string;- } | null>(null);const query = useTrialStatus();+ const failure = useTrialFailure(userID);+ const cancellation = useTrialCancellation({ userID, query, failure });const { mutateAsync: checkout, isPending: isCheckoutPending } =usePostTrialsStartTrialCheckout();// The mutation settles before the redirect, while the conversion is still// going out; the button must stay busy until the page actually leaves.const [isCheckingOut, setIsCheckingOut] = useState(false);const isStarting = isCheckoutPending || isCheckingOut;- const { mutateAsync: cancel, isPending: isCanceling } =- usePostTrialsCancelTrial();const offer = query.data?.eligible ? query.data.offer : null;-- useEffect(() => {- if (!offer || !userID) return;- const identity = `${userID}:${offer.token}`;- if (seenOffer.current === identity) return;- seenOffer.current = identity;- posthog?.capture(TrialEvent.TRIAL_OFFER_VIEWED, {- trial_offer_version: offer.version,- subscription_tier: offer.tier,- trial_duration_days: offer.duration_days,- surface: returnTo,- });- }, [offer, userID, posthog, returnTo]);+ useTrialOfferViewed({ offer, userID, surface: returnTo });async function startTrial() {if (!offer || !userID || isStarting) return;- setFailure(null);+ failure.clearFailure();setIsCheckingOut(true);try {const response = await checkout({data: { offer_token: offer.token, return_to: returnTo },});if (useAuthStore.getState().user?.id !== userID) return;- if (response.status !== 200)- throw new Error("Unable to start trial checkout.");+ if (response.status !== 200) throw new Error(CHECKOUT_FAILED);markTrialCheckoutStarted(returnTo);await trackAdsConversionBeforeNavigation("begin_checkout", {value: getTrialChargeAmount(offer),@@ -64,49 +42,23 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {});window.location.assign(response.data.url);} catch (error) {- setFailure({- userID,- message:- error instanceof Error- ? error.message- : "Unable to start trial checkout.",- });+ failure.reportFailure({ userID, error, fallback: CHECKOUT_FAILED });await query.refetch();} finally {setIsCheckingOut(false);}}- async function cancelTrial() {- if (!userID || isCanceling) return;- setFailure(null);- try {- const response = await cancel();- if (useAuthStore.getState().user?.id !== userID) return;- if (response.status !== 200)- throw new Error("Unable to cancel your trial.");- await updateTrialStatusCache({ queryClient, userID, response });- } catch (error) {- setFailure({- userID,- message:- error instanceof Error- ? error.message- : "Unable to cancel your trial.",- });- }- }-return {userID,trial: query.data,isLoading: Boolean(userID) && query.isLoading,- error: failure && failure.userID === userID ? failure.message : null,- queryError: query.isError,+ error: failure.error,+ // A failed refetch keeps the cached trial on screen, with its actions.+ queryError: query.isError && !query.data,retry: () => query.refetch(),isStarting,- isCanceling,startTrial,- cancelTrial,+ ...cancellation,};}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialFailure.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialFailure.tsnew file mode 100644index 0000000000..02c2226842--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialFailure.ts@@ -0,0 +1,29 @@+import { useState } from "react";++interface Failure {+ userID: string;+ message: string;+}++interface ReportArgs {+ userID: string;+ error: unknown;+ fallback: string;+}++export function useTrialFailure(userID: string | undefined) {+ const [failure, setFailure] = useState<Failure | null>(null);++ function reportFailure({ userID, error, fallback }: ReportArgs) {+ setFailure({+ userID,+ message: error instanceof Error ? error.message : fallback,+ });+ }++ return {+ error: failure && failure.userID === userID ? failure.message : null,+ clearFailure: () => setFailure(null),+ reportFailure,+ };+}diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialOfferViewed.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialOfferViewed.tsnew file mode 100644index 0000000000..114953b4cf--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialOfferViewed.ts@@ -0,0 +1,28 @@+import type { TrialOfferResponse } from "@/app/api/__generated__/models/trialOfferResponse";+import { TrialEvent } from "@/services/analytics/posthog-events";+import { usePostHog } from "@posthog/react";+import { useEffect, useRef } from "react";++interface Args {+ offer: TrialOfferResponse | null | undefined;+ userID: string | undefined;+ surface: "onboarding" | "billing";+}++export function useTrialOfferViewed({ offer, userID, surface }: Args) {+ const posthog = usePostHog();+ const seenOffer = useRef<string | null>(null);++ useEffect(() => {+ if (!offer || !userID) return;+ const identity = `${userID}:${offer.token}`;+ if (seenOffer.current === identity) return;+ seenOffer.current = identity;+ posthog?.capture(TrialEvent.TRIAL_OFFER_VIEWED, {+ trial_offer_version: offer.version,+ subscription_tier: offer.tier,+ trial_duration_days: offer.duration_days,+ surface,+ });+ }, [offer, userID, posthog, surface]);+}diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.tsindex 56e0e4ed16..9d0952b5c2 100644--- a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts@@ -57,7 +57,10 @@ const LIVE_EVENT_NAMES = ["tour_scenario_started","tour_started","transcription_failed",+ "trial_cancel_popup_viewed","trial_offer_viewed",+ "trial_resume_clicked",+ "trial_subscribe_now_clicked","voice_mode_error","voice_mode_permission_denied","voice_mode_started",diff --git a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts b/autogpt_platform/frontend/src/services/analytics/posthog-events.tsindex 692764f65b..0e8262d999 100644--- a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts+++ b/autogpt_platform/frontend/src/services/analytics/posthog-events.ts@@ -149,6 +149,9 @@ export const CredentialConnectionFailureEvent = {export const TrialEvent = {TRIAL_OFFER_VIEWED: "trial_offer_viewed",+ TRIAL_CANCEL_POPUP_VIEWED: "trial_cancel_popup_viewed",+ TRIAL_RESUME_CLICKED: "trial_resume_clicked",+ TRIAL_SUBSCRIBE_NOW_CLICKED: "trial_subscribe_now_clicked",} as const;export const TourEvent = {diff --git a/autogpt_platform/frontend/src/services/trials/updateTrialStatusCache.ts b/autogpt_platform/frontend/src/services/trials/updateTrialStatusCache.tsindex 4fcda74cb1..047c7234b7 100644--- a/autogpt_platform/frontend/src/services/trials/updateTrialStatusCache.ts+++ b/autogpt_platform/frontend/src/services/trials/updateTrialStatusCache.ts@@ -6,19 +6,24 @@ import {import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";import type { QueryClient } from "@tanstack/react-query";+// onApplied runs as soon as the trial status is written, before the slower+// plan status refresh, so UI tied to the new trial state shows with it.export async function updateTrialStatusCache({queryClient,userID,response,+ onApplied,}: {queryClient: QueryClient;userID: string;response: getTrialsGetTrialStatusResponseSuccess;+ onApplied?: () => void;}) {const queryKey = [...getGetTrialsGetTrialStatusQueryKey(), userID];await queryClient.cancelQueries({ queryKey, exact: true });if (useAuthStore.getState().user?.id !== userID) return false;queryClient.setQueryData(queryKey, response);+ onApplied?.();await queryClient.invalidateQueries({queryKey: getGetSubscriptionStatusQueryKey(),});diff --git a/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts b/autogpt_platform/frontend/src/services/trials/useTrialStatus.tsindex 468d2f1b08..089546fb0a 100644--- a/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts+++ b/autogpt_platform/frontend/src/services/trials/useTrialStatus.ts@@ -1,11 +1,17 @@import {getGetTrialsGetTrialStatusQueryKey,+ type getTrialsGetTrialStatusResponse,useGetTrialsGetTrialStatus,} from "@/app/api/__generated__/endpoints/trials/trials";+import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+type TrialRefetchInterval =+ | number+ | ((trial: TrialStatusResponse | undefined) => number | false);+interface Options {- refetchInterval?: number;+ refetchInterval?: TrialRefetchInterval;}export function useTrialStatus({ refetchInterval }: Options = {}) {@@ -15,9 +21,15 @@ export function useTrialStatus({ refetchInterval }: Options = {}) {queryKey: [...getGetTrialsGetTrialStatusQueryKey(), userID],enabled: Boolean(userID),retry: false,- refetchInterval,- select: (response) =>- response.status === 200 ? response.data : undefined,+ refetchInterval:+ typeof refetchInterval === "function"+ ? (query) => refetchInterval(readTrial(query.state.data))+ : refetchInterval,+ select: readTrial,},});}++function readTrial(response: getTrialsGetTrialStatusResponse | undefined) {+ return response?.status === 200 ? response.data : undefined;+}diff --git a/docs/engineering/tracking-plan.md b/docs/engineering/tracking-plan.mdindex dfca9566ed..1ceb1cd6c1 100644--- a/docs/engineering/tracking-plan.md+++ b/docs/engineering/tracking-plan.md@@ -246,18 +246,21 @@ differently.| `checkout_started` | backend | live | `checkout_kind` (`subscription`, `top_up`, `trial`), `subscription_tier`, `billing_cycle`, `surface` (sent by the client; unset for the low-credit top-up dialog and the legacy `/profile/credits` page), `$feature/<experiment>` for every recorded experiment arm | A Stripe Checkout session is created and its URL returned (subscription, credit top-up or trial card setup). A paid plan changed in place opens no Checkout and sends nothing. || `checkout_abandoned` | browser | live | `checkout_kind`, `surface` | The user returns from Stripe Checkout without paying (the cancel URL: `subscription=cancelled`, `topup=cancel`, `trial=cancelled`, or the paywall modal's `paywall_checkout=cancelled` marker). Browser-sent: Stripe only reports the expiry a day later. A trial abandonment is sent once per tab per surface until the next trial checkout starts, so a refresh on the cancel URL does not count twice but a second real abandonment does. || `trial_offer_viewed` | browser | live | `trial_offer_version`, `subscription_tier`, `trial_duration_days`, `surface` | A trial offer card is shown. |+| `trial_cancel_popup_viewed` | browser | live | `days_left` (whole days of trial access left, rounded up; `1` under a day) | The "Cancellation confirmed" popup opens, once, right after a cancel that sets the trial to cancel at its end, so trial access continues until then. A reload never reopens it. |+| `trial_resume_clicked` | browser | live | `days_left` | Resume trial is clicked on a trial set to cancel at its end, in the popup or on the trial card. Sent on the click; `trial_resumed` (backend) confirms it took effect. |+| `trial_subscribe_now_clicked` | browser | live | `days_left` | Subscribe now is clicked in the cancellation popup. It opens Billing. There, the trial's own plan converts the trial at once on the saved card (`trial_converted`, no `checkout_started`); any other plan, or a card that asks for authentication, goes through Stripe Checkout (`checkout_started`), which ends the trial without a `trial_ended`. || `trial_started` | backend | live | `trial_id`, `trial_offer_version`, `subscription_tier`, `billing_cycle`, `trial_duration_days` | The trial starts. Like every trial lifecycle event, it is sent only when its notification email is queued. || `trial_ending` | backend | live | as above | The reminder window opens. |-| `trial_canceled` | backend | live | as above | The trial is set to cancel. |-| `trial_resumed` | backend | live | as above | A cancelled trial is resumed. |+| `trial_canceled` | backend | live | as above | The trial is set to cancel at its end: the cancellation is scheduled, trial access continues until the end date, and the card is not charged. |+| `trial_resumed` | backend | live | as above | A trial set to cancel is resumed before its end date, so it converts to paid at its end as first agreed. || `payment_failed` | backend | live | as above | The conversion charge fails. || `trial_converted` | backend | live | as above | The trial converts to paid. |-| `trial_ended` | backend | live | as above | The trial ends without converting. |+| `trial_ended` | backend | live | as above | The trial ends without converting. Not sent when the trial subscription ends because another plan was bought while the trial was set to cancel; that plan's `checkout_started` and `payment_succeeded` cover it. || `subscription_changed` | backend | live | `change_type: upgrade`, `previous_subscription_tier`, `subscription_tier`, `billing_cycle` | A paid tier upgrade takes effect. Downgrades and cancellations are not sent here yet. || `payment_succeeded` | backend | live | `subscription_tier`, `billing_cycle`, `amount_cents` (the invoice's `amount_paid`), `currency` | A subscription invoice is paid. Deduplicated on the invoice id: Stripe delivers both `invoice.payment_succeeded` and `invoice_payment.paid` for one invoice, and redelivers either, so revenue is counted once. || `topup_completed` | backend | live | `amount_credits`, `top_up_type`, `amount_cents` (the Checkout total or the auto top-up charge), `currency` | Credits are bought. || `subscription_cancellation_scheduled` | backend | live | `subscription_tier` | A paid plan is set to cancel at period end. |-| `subscription_ended` | backend | live | `subscription_tier`, `billing_cycle`, `reason` (Stripe `cancellation_details.reason`: `cancellation_requested`, `payment_failed`, `payment_disputed`; `payment_failed` too when our own payment-failure handler cancelled the subscription because the balance could not cover a failed renewal, which Stripe would stamp `cancellation_requested`) | A paid subscription ends (Stripe `customer.subscription.deleted`), once per subscription, alongside the ended email. A trial that ends unconverted is `trial_ended` instead. |+| `subscription_ended` | backend | live | `subscription_tier`, `billing_cycle`, `reason` (Stripe `cancellation_details.reason`: `cancellation_requested`, `payment_failed`, `payment_disputed`; `payment_failed` too when our own payment-failure handler cancelled the subscription because the balance could not cover a failed renewal, which Stripe would stamp `cancellation_requested`) | A paid subscription ends (Stripe `customer.subscription.deleted`), once per subscription, alongside the ended email. A trial that ends unconverted is `trial_ended` instead; a trial ended by buying another plan sends neither. || `subscription_tier_reconciled` | backend | live | `direction`, `previous_subscription_tier`, `subscription_tier`, `via` | Ops signal: Stripe and the stored tier disagreed. Not a user action; keep out of funnels. |The paywall funnel in PostHog is `paywall_viewed` → `plan_selected` →@@ -315,7 +318,7 @@ replaying events.| Property | Value || --- | --- |-| `subscription_status` | `signed`, `in_trial`, `trial_canceled`, `subscribed`, `subscription_canceled` (set to cancel, active until the period ends), `payment_failed` (a renewal or the first charge after a trial failed; Stripe is retrying), `subscription_ended`. Worked out from the current user, trial and Stripe state, never from the last event received. |+| `subscription_status` | `signed`, `in_trial`, `trial_canceled` (a trial set to cancel, which keeps access until its end and goes back to `in_trial` on resume, or a trial that ended unconverted), `subscribed`, `subscription_canceled` (set to cancel, active until the period ends), `payment_failed` (a renewal or the first charge after a trial failed; Stripe is retrying), `subscription_ended`. Worked out from the current user, trial and Stripe state, never from the last event received. || `signup_at` | When the user row was created. || `trial_started_at` | When the trial started. || `subscription_started_at` | Start of the current or last paid subscription; for a converted trial, the conversion. |