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): yearly Stripe billing — pricing + frontend hookup (#13004)
Zamil Majdye4362a0f3b45
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.pyindex aad1bbab5c..1c611d86cc 100644--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py@@ -66,6 +66,15 @@ _DEFAULT_TIER_PRICES: dict[SubscriptionTier, str | None] = {SubscriptionTier.MAX: "price_max",SubscriptionTier.BUSINESS: None, # Reserved: Business card hidden by default.}+# Distinct yearly stubs so a routing bug leaking the wrong cycle into a Stripe+# call surfaces as an assertion diff rather than silently passing because both+# cycles share the same stub price.+_DEFAULT_TIER_PRICES_YEARLY: dict[SubscriptionTier, str | None] = {+ SubscriptionTier.BASIC: None,+ SubscriptionTier.PRO: "price_pro_yearly",+ SubscriptionTier.MAX: "price_max_yearly",+ SubscriptionTier.BUSINESS: None,+}@pytest.fixture(autouse=True)@@ -79,7 +88,11 @@ def _stub_subscription_status_lookups(mocker: pytest_mock.MockFixture) -> None:helpers. Individual tests can override via their own mocker.patch call."""- async def default_price_id(tier: SubscriptionTier) -> str | None:+ async def default_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if billing_cycle == "yearly":+ return _DEFAULT_TIER_PRICES_YEARLY.get(tier)return _DEFAULT_TIER_PRICES.get(tier)mocker.patch(@@ -93,13 +106,31 @@ def _stub_subscription_status_lookups(mocker: pytest_mock.MockFixture) -> None:)# Default tier-multiplier resolver to the backend defaults so the endpoint# never reaches LaunchDarkly during tests. Individual tests override for- # LD-override scenarios.+ # LD-override scenarios. get_tier_multipliers returns a string-keyed dict+ # (per its docstring) so we mirror that shape here — passing the+ # enum-keyed _DEFAULT_TIER_MULTIPLIERS directly would silently mismatch+ # the real lookup and let bugs through.from backend.copilot.rate_limit import _DEFAULT_TIER_MULTIPLIERSmocker.patch("backend.api.features.v1.get_tier_multipliers",new_callable=AsyncMock,- return_value=dict(_DEFAULT_TIER_MULTIPLIERS),+ return_value={t.value: v for t, v in _DEFAULT_TIER_MULTIPLIERS.items()},+ )+ # Default billing-cycle resolver to None (treated as monthly) so existing+ # tests don't have to opt into the yearly-aware code path.+ mocker.patch(+ "backend.api.features.v1.get_user_billing_cycle",+ new_callable=AsyncMock,+ return_value=None,+ )+ # Default to a non-None period_end so same-tier short-circuit tests still+ # fire (they assume an active Stripe subscription). Tests that exercise+ # the admin-granted "no Stripe sub" fall-through override this to None.+ mocker.patch(+ "backend.api.features.v1.get_active_subscription_period_end",+ new_callable=AsyncMock,+ return_value=1_900_000_000,)@@ -161,7 +192,9 @@ def test_get_subscription_status_pro("price_business": 14999,}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return prices.get(tier)async def mock_stripe_price_amount(price_id: str) -> int:@@ -222,15 +255,17 @@ def test_get_subscription_status_tier_multipliers_ld_override()# LD says PRO is 7.5× (instead of the 5× default); other tiers unchanged.+ # Keys are tier enum string values to match get_tier_multipliers'+ # documented return shape (dict[str, float]).mocker.patch("backend.api.features.v1.get_tier_multipliers",new_callable=AsyncMock,return_value={- SubscriptionTier.BASIC: 1.0,- SubscriptionTier.PRO: 7.5,- SubscriptionTier.MAX: 20.0,- SubscriptionTier.BUSINESS: 60.0,- SubscriptionTier.ENTERPRISE: 60.0,+ "BASIC": 1.0,+ "PRO": 7.5,+ "MAX": 20.0,+ "BUSINESS": 60.0,+ "ENTERPRISE": 60.0,},)@@ -292,7 +327,9 @@ def test_get_subscription_status_stripe_error_falls_back_to_zero(mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.PRO- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return "price_pro" if tier == SubscriptionTier.PRO else Noneasync def mock_stripe_price_amount_none(price_id: str) -> None:@@ -552,6 +589,180 @@ def test_update_subscription_tier_creates_checkout(assert response.json()["url"] == "https://checkout.stripe.com/pay/cs_test_abc"+def test_update_subscription_tier_forwards_yearly_billing_cycle(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """billing_cycle=yearly is forwarded to modify + checkout helpers and the+ target_price_id lookup so the 422 fail-closed branch fires correctly when+ yearly is unconfigured for the tier."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.BASIC++ async def mock_feature_enabled(*args, **kwargs):+ return True++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ mocker.patch(+ "backend.api.features.v1.is_feature_enabled",+ side_effect=mock_feature_enabled,+ )+ modify_mock = mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=True,+ )+ mocker.patch(+ "backend.api.features.v1._get_stripe_price_amount",+ new_callable=AsyncMock,+ return_value=1999,+ )+ price_lookup_calls: list[tuple] = []++ async def price_lookup(tier: SubscriptionTier, billing_cycle: str = "monthly"):+ price_lookup_calls.append((tier, billing_cycle))+ return "price_pro_yearly"++ mocker.patch(+ "backend.api.features.v1.get_subscription_price_id",+ side_effect=price_lookup,+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "PRO",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ "billing_cycle": "yearly",+ },+ )++ assert response.status_code == 200+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.PRO, "yearly")+ assert (SubscriptionTier.PRO, "yearly") in price_lookup_calls+++def test_update_subscription_tier_yearly_unconfigured_returns_422(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """When yearly price is not configured for the tier, the route fails closed+ with a 422 instead of silently using the monthly price."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.BASIC++ async def mock_feature_enabled(*args, **kwargs):+ return True++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ mocker.patch(+ "backend.api.features.v1.is_feature_enabled",+ side_effect=mock_feature_enabled,+ )+ mocker.patch(+ "backend.api.features.v1._get_stripe_price_amount",+ new_callable=AsyncMock,+ return_value=1999,+ )++ async def price_lookup(tier: SubscriptionTier, billing_cycle: str = "monthly"):+ if billing_cycle == "yearly":+ return None+ return "price_pro_monthly"++ mocker.patch(+ "backend.api.features.v1.get_subscription_price_id",+ side_effect=price_lookup,+ )+ modify_mock = mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "PRO",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ "billing_cycle": "yearly",+ },+ )++ assert response.status_code == 422+ modify_mock.assert_not_awaited()+++def test_update_subscription_tier_creates_checkout_with_yearly_billing(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """When no active sub, create_subscription_checkout receives billing_cycle=yearly."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.BASIC++ async def mock_feature_enabled(*args, **kwargs):+ return True++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ mocker.patch(+ "backend.api.features.v1.is_feature_enabled",+ side_effect=mock_feature_enabled,+ )+ mocker.patch(+ "backend.api.features.v1._get_stripe_price_amount",+ new_callable=AsyncMock,+ return_value=1999,+ )++ async def price_lookup(tier: SubscriptionTier, billing_cycle: str = "monthly"):+ return "price_pro_yearly"++ mocker.patch(+ "backend.api.features.v1.get_subscription_price_id",+ side_effect=price_lookup,+ )+ mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=False,+ )+ checkout_mock = mocker.patch(+ "backend.api.features.v1.create_subscription_checkout",+ new_callable=AsyncMock,+ return_value="https://checkout.stripe.com/pay/cs_test_yearly",+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "PRO",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ "billing_cycle": "yearly",+ },+ )++ assert response.status_code == 200+ checkout_mock.assert_awaited_once()+ kwargs = checkout_mock.await_args.kwargs+ assert kwargs["billing_cycle"] == "yearly"+ assert kwargs["tier"] == SubscriptionTier.PRO++def test_update_subscription_tier_rejects_open_redirect(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,@@ -941,7 +1152,9 @@ def test_update_subscription_tier_paid_to_paid_modifies_subscription(mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.PRO- async def price_id_with_business(tier: SubscriptionTier) -> str | None:+ async def price_id_with_business(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return {**_DEFAULT_TIER_PRICES,SubscriptionTier.BUSINESS: "price_business",@@ -982,7 +1195,9 @@ def test_update_subscription_tier_paid_to_paid_modifies_subscription(assert response.status_code == 200assert response.json()["url"] == ""- modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.BUSINESS)+ modify_mock.assert_awaited_once_with(+ TEST_USER_ID, SubscriptionTier.BUSINESS, "monthly"+ )checkout_mock.assert_not_awaited()@@ -1025,7 +1240,7 @@ def test_update_subscription_tier_max_checkout(assert response.status_code == 200assert response.json()["url"] == ""- modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.MAX)+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.MAX, "monthly")checkout_mock.assert_not_awaited()@@ -1079,7 +1294,7 @@ def test_update_subscription_tier_no_active_sub_falls_through_to_checkout(assert response.status_code == 200assert response.json()["url"] == "https://checkout.stripe.com/pay/cs_test_no_sub"- modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.MAX)+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.MAX, "monthly")# No DB-flip — payment must be collected via Checkout regardless of direction.set_tier_mock.assert_not_awaited()checkout_mock.assert_awaited_once()@@ -1094,7 +1309,9 @@ def test_update_subscription_tier_priced_basic_no_sub_falls_through_to_checkout(mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.BASIC- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return {SubscriptionTier.BASIC: "price_basic",SubscriptionTier.PRO: "price_pro",@@ -1149,7 +1366,7 @@ def test_update_subscription_tier_priced_basic_no_sub_falls_through_to_checkout(set_tier_mock.assert_not_awaited()checkout_mock.assert_awaited_once()# modify is still called first; returning False just means "no active sub".- modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.PRO)+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.PRO, "monthly")def test_update_subscription_tier_target_without_ld_price_returns_422(@@ -1166,7 +1383,9 @@ def test_update_subscription_tier_target_without_ld_price_returns_422(mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.BASIC- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return None # Neither BASIC nor PRO have an LD price.mocker.patch(@@ -1250,7 +1469,7 @@ def test_update_subscription_tier_pro_to_max_card_declined_returns_402(assert response.status_code == 402assert "card was declined" in response.json()["detail"].lower()- modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.MAX)+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.MAX, "monthly")def test_update_subscription_tier_pro_to_max_authentication_required_returns_402(@@ -1300,6 +1519,54 @@ def test_update_subscription_tier_pro_to_max_authentication_required_returns_402assert "card was declined" not in detail+def test_update_subscription_tier_pro_to_max_subscription_payment_intent_requires_action_returns_402(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """Subscription.modify under error_if_incomplete raises CardError with+ code='subscription_payment_intent_requires_action' (not the raw+ authentication_required from PaymentIntent.confirm). The SCA branch must+ cover both codes, otherwise the user gets the generic "card was declined"+ copy and would re-enter a card that's already fine."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.PRO++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ mocker.patch(+ "backend.api.features.v1.is_feature_enabled",+ new_callable=AsyncMock,+ return_value=True,+ )+ mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ side_effect=stripe.CardError(+ "Payment for this subscription requires additional user action"+ " before it can be completed successfully.",+ param=None,+ code="subscription_payment_intent_requires_action",+ ),+ )++ 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,@@ -1354,7 +1621,9 @@ def test_update_subscription_tier_paid_to_paid_stripe_error_returns_502(mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.PRO- async def price_id_with_business(tier: SubscriptionTier) -> str | None:+ async def price_id_with_business(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return {**_DEFAULT_TIER_PRICES,SubscriptionTier.BUSINESS: "price_business",@@ -1448,7 +1717,9 @@ def test_get_subscription_status_includes_pending_tier(effective_at = dt.datetime(2030, 1, 1, tzinfo=dt.timezone.utc)- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return Nonemocker.patch(@@ -1468,7 +1739,7 @@ def test_get_subscription_status_includes_pending_tier(mocker.patch("backend.api.features.v1.get_pending_subscription_change",new_callable=AsyncMock,- return_value=(SubscriptionTier.PRO, effective_at),+ return_value=(SubscriptionTier.PRO, effective_at, "monthly"),)response = client.get("/credits/subscription")@@ -1477,6 +1748,7 @@ def test_get_subscription_status_includes_pending_tier(data = response.json()assert data["pending_tier"] == "PRO"assert data["pending_tier_effective_at"] is not None+ assert data["pending_billing_cycle"] == "monthly"def test_get_subscription_status_no_pending_tier(@@ -1524,7 +1796,9 @@ def test_update_subscription_tier_downgrade_paid_to_paid_schedules(mock_user = Mock()mock_user.subscription_tier = SubscriptionTier.BUSINESS- async def price_id_with_business(tier: SubscriptionTier) -> str | None:+ async def price_id_with_business(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return {**_DEFAULT_TIER_PRICES,SubscriptionTier.BUSINESS: "price_business",@@ -1565,7 +1839,7 @@ def test_update_subscription_tier_downgrade_paid_to_paid_schedules(assert response.status_code == 200assert response.json()["url"] == ""- modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.PRO)+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.PRO, "monthly")checkout_mock.assert_not_awaited()@@ -1638,3 +1912,300 @@ def test_stripe_webhook_ignores_subscription_schedule_updated(assert response.status_code == 200sync_mock.assert_not_awaited()+++def test_get_subscription_status_yearly_only_tier_visible(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """When LD configures only the yearly price for a tier, the row must still+ appear in tier_costs (with monthly cost 0) and the yearly cost surfaces+ via tier_costs_yearly so the frontend can render it."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.PRO++ async def price_lookup(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ # PRO has only a yearly price configured; MAX has both; others none.+ if tier == SubscriptionTier.PRO and billing_cycle == "yearly":+ return "price_pro_yearly"+ if tier == SubscriptionTier.MAX and billing_cycle == "monthly":+ return "price_max_monthly"+ if tier == SubscriptionTier.MAX and billing_cycle == "yearly":+ return "price_max_yearly"+ return None++ amounts = {+ "price_pro_yearly": 19_999,+ "price_max_monthly": 4999,+ "price_max_yearly": 49_999,+ }++ async def stripe_amount(price_id: str) -> int:+ return amounts.get(price_id, 0)++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ mocker.patch(+ "backend.api.features.v1.get_subscription_price_id",+ side_effect=price_lookup,+ )+ mocker.patch(+ "backend.api.features.v1._get_stripe_price_amount",+ side_effect=stripe_amount,+ )+ mocker.patch(+ "backend.api.features.v1.get_user_billing_cycle",+ new_callable=AsyncMock,+ return_value="yearly",+ )++ response = client.get("/credits/subscription")++ assert response.status_code == 200+ data = response.json()+ # PRO row still visible despite no monthly price.+ assert "PRO" in data["tier_costs"]+ assert data["tier_costs"]["PRO"] == 0+ assert data["tier_costs_yearly"]["PRO"] == 19_999+ # MAX has both cycles.+ assert data["tier_costs"]["MAX"] == 4999+ assert data["tier_costs_yearly"]["MAX"] == 49_999+ # User is on yearly Pro → monthly_cost reflects the yearly price.+ assert data["billing_cycle"] == "yearly"+ assert data["monthly_cost"] == 19_999+++def test_get_subscription_status_yearly_user_both_cycles_uses_yearly_cost(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """When LD has both monthly and yearly prices and the user is on yearly,+ monthly_cost in the response reflects the yearly price (the user's actual+ cost), not the monthly equivalent."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.PRO++ async def price_lookup(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if tier == SubscriptionTier.PRO:+ return (+ "price_pro_yearly" if billing_cycle == "yearly" else "price_pro_monthly"+ )+ return None++ amounts = {+ "price_pro_monthly": 1999,+ "price_pro_yearly": 19_999,+ }++ async def stripe_amount(price_id: str) -> int:+ return amounts.get(price_id, 0)++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ mocker.patch(+ "backend.api.features.v1.get_subscription_price_id",+ side_effect=price_lookup,+ )+ mocker.patch(+ "backend.api.features.v1._get_stripe_price_amount",+ side_effect=stripe_amount,+ )+ mocker.patch(+ "backend.api.features.v1.get_user_billing_cycle",+ new_callable=AsyncMock,+ return_value="yearly",+ )++ response = client.get("/credits/subscription")++ assert response.status_code == 200+ data = response.json()+ assert data["billing_cycle"] == "yearly"+ assert data["tier_costs"]["PRO"] == 1999+ assert data["tier_costs_yearly"]["PRO"] == 19_999+ # User pays the yearly price — surface it via monthly_cost so the UI shows+ # the user's real recurring cost rather than the unrelated monthly equivalent.+ assert data["monthly_cost"] == 19_999+++def test_update_subscription_tier_same_tier_cycle_change_routes_to_modify(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """A monthly Pro user posting {tier:'PRO', billing_cycle:'yearly'} must+ NOT short-circuit through release_pending_subscription_schedule — that+ would no-op the cycle change. Route through modify_stripe_subscription_for_tier+ so Stripe swaps to the yearly price."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.PRO++ async def price_lookup(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if tier == SubscriptionTier.PRO:+ return (+ "price_pro_yearly" if billing_cycle == "yearly" else "price_pro_monthly"+ )+ return None++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ mocker.patch(+ "backend.api.features.v1.is_feature_enabled",+ new_callable=AsyncMock,+ return_value=True,+ )+ mocker.patch(+ "backend.api.features.v1.get_subscription_price_id",+ side_effect=price_lookup,+ )+ # User is currently on monthly Pro.+ mocker.patch(+ "backend.api.features.v1.get_user_billing_cycle",+ new_callable=AsyncMock,+ return_value="monthly",+ )+ release_mock = mocker.patch(+ "backend.api.features.v1.release_pending_subscription_schedule",+ new_callable=AsyncMock,+ )+ modify_mock = mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=True,+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "PRO",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ "billing_cycle": "yearly",+ },+ )++ assert response.status_code == 200+ release_mock.assert_not_awaited()+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.PRO, "yearly")+++def test_update_subscription_tier_same_tier_same_cycle_still_releases_pending(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """A yearly Pro user posting {tier:'PRO', billing_cycle:'yearly'} keeps the+ "stay on my current tier + cycle" semantics — release any pending change."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.PRO++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ mocker.patch(+ "backend.api.features.v1.get_user_billing_cycle",+ new_callable=AsyncMock,+ return_value="yearly",+ )+ release_mock = mocker.patch(+ "backend.api.features.v1.release_pending_subscription_schedule",+ new_callable=AsyncMock,+ return_value=True,+ )+ modify_mock = mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "PRO",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ "billing_cycle": "yearly",+ },+ )++ assert response.status_code == 200+ release_mock.assert_awaited_once_with(TEST_USER_ID)+ modify_mock.assert_not_awaited()+++def test_update_subscription_tier_same_tier_no_stripe_sub_falls_through_to_checkout(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+) -> None:+ """Admin-granted tier (DB tier set, no active Stripe subscription) posting+ their *current* tier must fall through to the Checkout flow, not short-+ circuit through release_pending_subscription_schedule. Otherwise "start+ paying for my current tier" silently no-ops for these users.+ """+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.PRO++ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ # No active Stripe subscription — period_end is None.+ mocker.patch(+ "backend.api.features.v1.get_active_subscription_period_end",+ new_callable=AsyncMock,+ return_value=None,+ )+ mocker.patch(+ "backend.api.features.v1.is_feature_enabled",+ new_callable=AsyncMock,+ return_value=True,+ )+ release_mock = mocker.patch(+ "backend.api.features.v1.release_pending_subscription_schedule",+ new_callable=AsyncMock,+ )+ # Admin-granted user has no active Stripe sub, so the modify path returns+ # False (no sub to mutate). Mock explicitly so the test doesn't reach the+ # real backend.data.credit.modify_stripe_subscription_for_tier (which+ # would try to read from Prisma + call Stripe).+ modify_mock = mocker.patch(+ "backend.api.features.v1.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=False,+ )+ checkout_mock = mocker.patch(+ "backend.api.features.v1.create_subscription_checkout",+ new_callable=AsyncMock,+ return_value="https://checkout.example.com/sess_admingranted",+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "PRO",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ },+ )++ assert response.status_code == 200+ data = response.json()+ assert data["url"] == "https://checkout.example.com/sess_admingranted"+ release_mock.assert_not_awaited()+ modify_mock.assert_awaited_once()+ checkout_mock.assert_awaited_once()diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex 03e835d8c5..f8ad87fa22 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -63,6 +63,7 @@ from backend.data.credit import (get_pending_subscription_change,get_proration_credit_cents,get_subscription_price_id,+ get_user_billing_cycle,get_user_credit_model,handle_subscription_payment_failure,handle_subscription_payment_success,@@ -705,12 +706,30 @@ class SubscriptionTierRequest(BaseModel):tier: Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]success_url: str = ""cancel_url: str = ""+ billing_cycle: Literal["monthly", "yearly"] = "monthly"class SubscriptionStatusResponse(BaseModel):tier: Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS", "ENTERPRISE"]monthly_cost: int # amount in cents (Stripe convention)- tier_costs: dict[str, int] # tier name -> amount in cents+ tier_costs: dict[str, int] # tier name -> monthly amount in cents+ tier_costs_yearly: dict[str, int] = Field(+ default_factory=dict,+ description=(+ "Tier → yearly amount in cents. Populated only for tiers with a"+ " yearly Stripe price configured in LaunchDarkly. Empty for"+ " monthly-only configurations."+ ),+ )+ billing_cycle: Literal["monthly", "yearly"] = Field(+ default="monthly",+ description=(+ "Billing cycle of the user's active Stripe subscription. Defaults"+ " to ``monthly`` for users without an active sub. ``monthly_cost``"+ " above reflects this cycle's actual price (so a yearly subscriber"+ " sees their yearly amount, not the monthly equivalent)."+ ),+ )tier_multipliers: dict[str, float] = Field(default_factory=dict,description=(@@ -739,6 +758,17 @@ class SubscriptionStatusResponse(BaseModel):)pending_tier: Optional[Literal["NO_TIER", "BASIC", "PRO", "MAX", "BUSINESS"]] = Nonepending_tier_effective_at: Optional[datetime] = None+ pending_billing_cycle: Optional[Literal["monthly", "yearly"]] = Field(+ default=None,+ description=(+ "Billing cycle of the queued change, when resolvable. Set alongside"+ " ``pending_tier`` for tier downgrades and same-tier cycle"+ " switches (yearly→monthly). The frontend uses this to differentiate"+ " a cycle-only schedule (``pending_tier == current tier``) from a"+ " real tier downgrade so the UI copy can describe the actual"+ " change. ``None`` for cancellations and unconfigured legacy prices."+ ),+ )url: str = Field(default="",description=(@@ -833,19 +863,39 @@ async def get_subscription_status(SubscriptionTier.MAX,SubscriptionTier.BUSINESS,]- price_ids = await asyncio.gather(- *[get_subscription_price_id(t) for t in priceable_tiers]+ monthly_price_ids, yearly_price_ids = await asyncio.gather(+ asyncio.gather(+ *[get_subscription_price_id(t, "monthly") for t in priceable_tiers]+ ),+ asyncio.gather(+ *[get_subscription_price_id(t, "yearly") for t in priceable_tiers]+ ),)async def _cost(pid: str | None) -> int:return (await _get_stripe_price_amount(pid) or 0) if pid else 0- costs = await asyncio.gather(*[_cost(pid) for pid in price_ids])+ monthly_costs, yearly_costs = await asyncio.gather(+ asyncio.gather(*[_cost(pid) for pid in monthly_price_ids]),+ asyncio.gather(*[_cost(pid) for pid in yearly_price_ids]),+ )+ # Row visibility: include a tier if EITHER cycle is configured. Monthly+ # cost falls back to 0 when only yearly is configured so the frontend can+ # still render the card and surface yearly via ``tier_costs_yearly``.tier_costs: dict[str, int] = {}- for t, pid, cost in zip(priceable_tiers, price_ids, costs):- if pid:- tier_costs[t.value] = cost+ tier_costs_yearly: dict[str, int] = {}+ for t, m_pid, y_pid, m_cost, y_cost in zip(+ priceable_tiers,+ monthly_price_ids,+ yearly_price_ids,+ monthly_costs,+ yearly_costs,+ ):+ if m_pid or y_pid:+ tier_costs[t.value] = m_cost if m_pid else 0+ if y_pid:+ tier_costs_yearly[t.value] = y_cost# Expose the effective rate-limit multipliers alongside prices so the# frontend can render "Nx rate limits" relative to the lowest visible@@ -853,13 +903,20 @@ async def get_subscription_status(# that land in ``tier_costs`` — rows hidden at the price layer must stay# hidden in the multiplier layer too.multipliers = await get_tier_multipliers()+ # get_tier_multipliers() keys by tier string value (see its docstring),+ # so the lookup must use t.value — passing the enum t silently misses+ # every tier and falls back to 1.0, ignoring LD-configured multipliers.tier_multipliers: dict[str, float] = {- t.value: multipliers.get(t, 1.0)+ t.value: multipliers.get(t.value, 1.0)for t in priceable_tiersif t.value in tier_costs}- current_monthly_cost = tier_costs.get(tier.value, 0)+ user_cycle = await get_user_billing_cycle(user_id) or "monthly"+ if user_cycle == "yearly":+ current_monthly_cost = tier_costs_yearly.get(tier.value, 0)+ else:+ current_monthly_cost = tier_costs.get(tier.value, 0)proration_credit, current_period_end = await asyncio.gather(get_proration_credit_cents(user_id, current_monthly_cost),get_active_subscription_period_end(user_id),@@ -883,13 +940,15 @@ async def get_subscription_status(tier=tier.value,monthly_cost=current_monthly_cost,tier_costs=tier_costs,+ tier_costs_yearly=tier_costs_yearly,+ billing_cycle=user_cycle,tier_multipliers=tier_multipliers,proration_credit_cents=proration_credit,has_active_stripe_subscription=current_period_end is not None,current_period_end=current_period_end,)if pending is not None:- pending_tier_enum, pending_effective_at = pending+ pending_tier_enum, pending_effective_at, pending_cycle = pendingif pending_tier_enum in (SubscriptionTier.NO_TIER,SubscriptionTier.BASIC,@@ -899,6 +958,7 @@ async def get_subscription_status():response.pending_tier = pending_tier_enum.valueresponse.pending_tier_effective_at = pending_effective_at+ response.pending_billing_cycle = pending_cyclereturn response@@ -926,12 +986,29 @@ async def update_subscription_tier(detail="ENTERPRISE subscription changes must be managed by an administrator",)- # Same-tier request = "stay on my current tier" = cancel any pending- # scheduled change (paid→paid downgrade or paid→BASIC cancel). This is the- # collapsed behaviour that replaces the old /credits/subscription/cancel-pending- # route. Safe when no pending change exists: release_pending_subscription_schedule- # returns False and we simply return the current status.- if (user.subscription_tier or SubscriptionTier.NO_TIER) == tier:+ # Same-tier + same-cycle request = "stay on my current tier" = cancel any+ # pending scheduled change (paid→paid downgrade or paid→BASIC cancel). This+ # replaces the old /credits/subscription/cancel-pending route. Safe when no+ # pending change exists: release_pending_subscription_schedule returns+ # False and we simply return the current status.+ #+ # Same-tier-DIFFERENT-cycle (monthly Pro → yearly Pro, or vice versa) must+ # fall through to modify_stripe_subscription_for_tier so Stripe swaps the+ # price ID for the cycle the user actually requested.+ #+ # Gate the short-circuit on an actual active/trialing Stripe subscription:+ # 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+ 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+ )+ if (+ current_tier == tier+ and current_cycle == request.billing_cycle+ and has_active_stripe_subscription+ ):try:await release_pending_subscription_schedule(user_id)except stripe.StripeError as e:@@ -953,7 +1030,7 @@ async def update_subscription_tier(Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False)- target_price_id = await get_subscription_price_id(tier)+ target_price_id = await get_subscription_price_id(tier, request.billing_cycle)# Cancel: target NO_TIER. Schedule Stripe cancellation at period end;# cancel_at_period_end=True lets the webhook flip the DB tier. No active@@ -998,7 +1075,9 @@ 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)+ modified = await modify_stripe_subscription_for_tier(+ user_id, tier, request.billing_cycle+ )if modified:return await get_subscription_status(user_id)except ValueError as e:@@ -1006,9 +1085,15 @@ async def update_subscription_tier(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. authentication_required means the card is fine but the- # bank wants 3DS — different message so the user doesn't try a new card.- if e.code == "authentication_required":+ # 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",+ }:logger.warning("SCA required on subscription upgrade for user %s: %s", user_id, e)@@ -1143,6 +1228,7 @@ async def update_subscription_tier(tier=tier,success_url=request.success_url,cancel_url=request.cancel_url,+ billing_cycle=request.billing_cycle,)except ValueError as e:raise HTTPException(status_code=422, detail=str(e))@@ -1243,6 +1329,27 @@ async def stripe_webhook(request: Request):if event_type == "invoice.payment_failed":await handle_subscription_payment_failure(data_object)+ # New Stripe API (≥2025-04-01) split the per-payment events off the Invoice+ # resource. data.object is an InvoicePayment, not an Invoice, so we hydrate+ # the underlying Invoice before delegating to the existing handlers.+ if event_type in ("invoice_payment.paid", "invoice_payment.payment_failed"):+ invoice_id = data_object.get("invoice")+ if invoice_id:+ try:+ invoice = await run_in_threadpool(stripe.Invoice.retrieve, invoice_id)+ except stripe.StripeError:+ logger.exception(+ "stripe_webhook: %s could not retrieve invoice %s; skipping",+ event_type,+ invoice_id,+ )+ return Response(status_code=200)+ invoice_payload = cast(dict, invoice)+ if event_type == "invoice_payment.paid":+ await handle_subscription_payment_success(invoice_payload)+ else:+ await handle_subscription_payment_failure(invoice_payload)+# `handle_dispute` and `deduct_credits` expect Stripe SDK typed objects# (Dispute/Refund). The Stripe webhook payload's `data.object` is a# StripeObject (a dict subclass) carrying that runtime shape, so we castdiff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.pyindex 759a8f6ec2..96eae3192a 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py@@ -998,7 +998,12 @@ async def _warn_if_stripe_subscription_drifts(current_price_id = price if isinstance(price, str) else price.id# Inside the try/except: an LD SDK failure here must not turn a# best-effort diagnostic into a 500 after the DB write committed.- expected_price_id = await get_subscription_price_id(new_tier)+ # Match either cycle so a yearly subscriber on the right tier doesn't+ # spuriously trigger the drift warning.+ expected_monthly, expected_yearly = await asyncio.gather(+ get_subscription_price_id(new_tier, "monthly"),+ get_subscription_price_id(new_tier, "yearly"),+ )except Exception:logger.debug("_warn_if_stripe_subscription_drifts: drift lookup failed for"@@ -1007,19 +1012,20 @@ async def _warn_if_stripe_subscription_drifts(exc_info=True,)return- if expected_price_id is not None and expected_price_id == current_price_id:+ if current_price_id and current_price_id in (expected_monthly, expected_yearly):returnlogger.warning("Admin tier override will drift from Stripe: user=%s admin_tier=%s"- " stripe_sub=%s stripe_price=%s expected_price=%s — the next"- " customer.subscription.updated webhook will reconcile the DB tier"- " back to whatever Stripe has; cancel or modify the Stripe subscription"- " if you intended the admin override to stick.",+ " stripe_sub=%s stripe_price=%s expected_prices=(monthly=%s, yearly=%s)"+ " — the next customer.subscription.updated webhook will reconcile the"+ " DB tier back to whatever Stripe has; cancel or modify the Stripe"+ " subscription if you intended the admin override to stick.",user_id,new_tier.value,sub.id,current_price_id,- expected_price_id,+ expected_monthly,+ expected_yearly,)diff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.pyindex 0bbf64a131..c9390a3efd 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py@@ -2040,6 +2040,100 @@ class TestWorkspaceStorageLimits:assert result == 250 * 1024 * 1024+# _warn_if_stripe_subscription_drifts — yearly billing+# ---------------------------------------------------------------------------+++class TestWarnIfStripeSubscriptionDriftsYearly:+ @pytest.mark.asyncio+ async def test_yearly_subscription_does_not_log_drift(self, caplog):+ """A user on the yearly price for their admin-set tier must NOT trigger+ a drift warning — the drift check now matches either monthly OR yearly."""+ from backend.copilot.rate_limit import _warn_if_stripe_subscription_drifts++ mock_user = MagicMock()+ mock_user.stripe_customer_id = "cus_yearly"++ mock_sub = MagicMock()+ mock_sub.id = "sub_yearly"+ mock_sub["items"].data = [MagicMock(price=MagicMock(id="price_pro_yearly"))]++ async def price_lookup(tier, billing_cycle="monthly"):+ if tier == SubscriptionTier.PRO and billing_cycle == "monthly":+ return "price_pro_monthly"+ if tier == SubscriptionTier.PRO and billing_cycle == "yearly":+ return "price_pro_yearly"+ return None++ with (+ patch(+ "backend.copilot.rate_limit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ ),+ patch(+ "backend.data.credit._get_active_subscription",+ new_callable=AsyncMock,+ return_value=mock_sub,+ ),+ patch(+ "backend.data.credit.get_subscription_price_id",+ side_effect=price_lookup,+ ),+ ):+ with caplog.at_level("WARNING", logger="backend.copilot.rate_limit"):+ await _warn_if_stripe_subscription_drifts(_USER, SubscriptionTier.PRO)++ drift_records = [+ r for r in caplog.records if "will drift from Stripe" in r.getMessage()+ ]+ assert drift_records == []++ @pytest.mark.asyncio+ async def test_genuine_drift_still_logs(self, caplog):+ """When the Stripe price doesn't match either monthly or yearly for the+ admin-set tier, the drift warning still fires."""+ from backend.copilot.rate_limit import _warn_if_stripe_subscription_drifts++ mock_user = MagicMock()+ mock_user.stripe_customer_id = "cus_drift"++ mock_sub = MagicMock()+ mock_sub.id = "sub_drift"+ mock_sub["items"].data = [MagicMock(price=MagicMock(id="price_max_yearly"))]++ async def price_lookup(tier, billing_cycle="monthly"):+ if tier == SubscriptionTier.PRO and billing_cycle == "monthly":+ return "price_pro_monthly"+ if tier == SubscriptionTier.PRO and billing_cycle == "yearly":+ return "price_pro_yearly"+ return None++ with (+ patch(+ "backend.copilot.rate_limit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ ),+ patch(+ "backend.data.credit._get_active_subscription",+ new_callable=AsyncMock,+ return_value=mock_sub,+ ),+ patch(+ "backend.data.credit.get_subscription_price_id",+ side_effect=price_lookup,+ ),+ ):+ with caplog.at_level("WARNING", logger="backend.copilot.rate_limit"):+ await _warn_if_stripe_subscription_drifts(_USER, SubscriptionTier.PRO)++ drift_records = [+ r for r in caplog.records if "will drift from Stripe" in r.getMessage()+ ]+ assert len(drift_records) == 1++# ---------------------------------------------------------------------------# get_remaining_usd_budget# ---------------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex 86635b6753..bbaf4d8b54 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -4,7 +4,7 @@ import timefrom abc import ABC, abstractmethodfrom collections import defaultdictfrom datetime import datetime, timedelta, timezone-from typing import TYPE_CHECKING, Any, cast+from typing import TYPE_CHECKING, Any, Literal, castimport stripefrom fastapi.concurrency import run_in_threadpool@@ -54,6 +54,8 @@ base_url = settings.config.frontend_base_url or settings.config.platform_base_urPOSTGRES_INT_MAX = 2147483647POSTGRES_INT_MIN = -2147483648+BillingCycle = Literal["monthly", "yearly"]+class UsageTransactionMetadata(BaseModel):graph_exec_id: str | None = None@@ -1591,6 +1593,56 @@ async def _get_active_subscription(customer_id: str) -> stripe.Subscription | Noreturn None+async def get_user_billing_cycle(user_id: str) -> BillingCycle | None:+ """Return the billing cycle ("monthly"/"yearly") of the user's active sub.++ Resolves cycle by matching the active subscription's price ID against the+ LaunchDarkly-configured monthly/yearly price IDs for the user's current+ tier, falling back to scanning every priceable tier (handles the brief+ window during a tier change where DB tier and Stripe price disagree).+ Returns None when there's no Stripe customer, no active sub, or the price+ ID doesn't match any configured cycle (e.g. legacy unconfigured price).+ """+ user = await get_user_by_id(user_id)+ if not user.stripe_customer_id:+ return None+ try:+ sub = await _get_active_subscription(user.stripe_customer_id)+ except stripe.StripeError:+ logger.warning(+ "get_user_billing_cycle: Stripe lookup failed for user %s", user_id+ )+ return None+ if sub is None:+ return None+ items = sub["items"].data+ if not items:+ return None+ price = items[0].price+ current_price_id = price if isinstance(price, str) else price.id+ if not current_price_id:+ return None++ priceable = (+ SubscriptionTier.BASIC,+ SubscriptionTier.PRO,+ SubscriptionTier.MAX,+ SubscriptionTier.BUSINESS,+ )+ monthly_prices, yearly_prices = await asyncio.gather(+ asyncio.gather(*[get_subscription_price_id(t, "monthly") for t in priceable]),+ asyncio.gather(*[get_subscription_price_id(t, "yearly") for t in priceable]),+ )+ price_to_cycle: dict[str, BillingCycle] = {}+ for pid in monthly_prices:+ if pid:+ price_to_cycle[pid] = "monthly"+ for pid in yearly_prices:+ if pid:+ price_to_cycle[pid] = "yearly"+ return price_to_cycle.get(current_price_id)++async def get_active_subscription_period_end(user_id: str) -> int | None:"""Return the Unix timestamp of the active sub's current_period_end, or None.@@ -1776,7 +1828,9 @@ async def _schedule_downgrade_at_period_end(async def modify_stripe_subscription_for_tier(- user_id: str, tier: SubscriptionTier+ user_id: str,+ tier: SubscriptionTier,+ billing_cycle: BillingCycle = "monthly",) -> bool:"""Change a Stripe subscription to a new paid tier.@@ -1799,7 +1853,7 @@ async def modify_stripe_subscription_for_tier(Raises stripe.StripeError on API failures so callers can propagate a 502.Raises ValueError when no Stripe price ID is configured for the tier."""- price_id = await get_subscription_price_id(tier)+ price_id = await get_subscription_price_id(tier, billing_cycle)if not price_id:raise ValueError(f"No Stripe price ID configured for tier {tier}")@@ -1826,6 +1880,22 @@ async def modify_stripe_subscription_for_tier(await _schedule_downgrade_at_period_end(sub, price_id, user_id, tier)return True+ # Same-tier yearly→monthly is a cycle *downgrade*: the user is moving+ # from a longer commitment to a shorter one. Route it through the+ # period-end schedule so the dialog promise ("no charge today, switch+ # at end of yearly period") actually holds. Same-tier monthly→yearly+ # stays on the immediate proration path below — the user is committing+ # to more time, immediate billing is the correct semantic.+ if current_tier == tier:+ current_price = items[0].price+ current_price_id = (+ current_price if isinstance(current_price, str) else current_price.id+ )+ current_cycle = await _resolve_cycle_for_price_id(current_price_id)+ if current_cycle == "yearly" and billing_cycle == "monthly":+ await _schedule_downgrade_at_period_end(sub, price_id, user_id, tier)+ return True+# Upgrade path. If a schedule is attached from a previous pending# downgrade, release it first — an upgrade expresses the user's# intent to be on this tier immediately, which overrides any pending@@ -1844,10 +1914,19 @@ async def modify_stripe_subscription_for_tier(# at period end, leaving a confusing dual state.# always_invoice + error_if_incomplete bill the prorated upgrade now and# roll the modify back if the auto-charge fails (instead of deferring).+ # Refresh metadata so the live sub reflects the new tier+cycle — the+ # backend derives tier from price_id, but Stripe-side dashboards and+ # downstream tooling read sub.metadata directly and otherwise see the+ # stale tier/cycle from the original checkout.modify_kwargs: dict = {"items": [{"id": items[0].id, "price": price_id}],"proration_behavior": "always_invoice","payment_behavior": "error_if_incomplete",+ "metadata": {+ "user_id": user_id,+ "tier": tier.value,+ "billing_cycle": billing_cycle,+ },}if sub.cancel_at_period_end:modify_kwargs["cancel_at_period_end"] = False@@ -1962,8 +2041,8 @@ async def release_pending_subscription_schedule(user_id: str) -> bool:@cached(ttl_seconds=30, maxsize=512, cache_none=True, shared_cache=True)async def get_pending_subscription_change(user_id: str,-) -> tuple[SubscriptionTier, datetime] | None:- """Return ``(pending_tier, effective_at)`` when a change is queued, else ``None``.+) -> tuple[SubscriptionTier, datetime, BillingCycle | None] | None:+ """Return ``(pending_tier, effective_at, pending_cycle)`` when a change is queued, else ``None``.Reflects both Subscription Schedule phase transitions (paid→paid downgrade)and ``cancel_at_period_end=True`` (paid→BASIC cancel).@@ -1997,21 +2076,28 @@ async def get_pending_subscription_change(# BASIC-only users): skip the Stripe API calls entirely.return None- basic_price, pro_price, max_price, business_price = await asyncio.gather(- get_subscription_price_id(SubscriptionTier.BASIC),- get_subscription_price_id(SubscriptionTier.PRO),- get_subscription_price_id(SubscriptionTier.MAX),- get_subscription_price_id(SubscriptionTier.BUSINESS),+ priceable = (+ SubscriptionTier.BASIC,+ SubscriptionTier.PRO,+ SubscriptionTier.MAX,+ SubscriptionTier.BUSINESS,+ )+ # Gather monthly + yearly price IDs so a schedule whose next phase points+ # at a yearly price still resolves to the correct tier.+ monthly_prices, yearly_prices = await asyncio.gather(+ asyncio.gather(*[get_subscription_price_id(t, "monthly") for t in priceable]),+ asyncio.gather(*[get_subscription_price_id(t, "yearly") for t in priceable]),)price_to_tier: dict[str, SubscriptionTier] = {}- if basic_price:- price_to_tier[basic_price] = SubscriptionTier.BASIC- if pro_price:- price_to_tier[pro_price] = SubscriptionTier.PRO- if max_price:- price_to_tier[max_price] = SubscriptionTier.MAX- if business_price:- price_to_tier[business_price] = SubscriptionTier.BUSINESS+ price_to_cycle: dict[str, BillingCycle] = {}+ for t, pid in zip(priceable, monthly_prices):+ if pid:+ price_to_tier[pid] = t+ price_to_cycle[pid] = "monthly"+ for t, pid in zip(priceable, yearly_prices):+ if pid:+ price_to_tier[pid] = t+ price_to_cycle[pid] = "yearly"if not price_to_tier:logger.warning("get_pending_subscription_change: no Stripe price IDs resolvable for"@@ -2030,19 +2116,25 @@ async def get_pending_subscription_change(return Noneeffective_at = datetime.fromtimestamp(period_end, tz=timezone.utc)if sub.cancel_at_period_end:- return SubscriptionTier.NO_TIER, effective_at+ return SubscriptionTier.NO_TIER, effective_at, Noneif not sub.schedule:return Noneschedule_id = sub.schedule if isinstance(sub.schedule, str) else sub.schedule.idschedule = await stripe.SubscriptionSchedule.retrieve_async(schedule_id)- return _next_phase_tier_and_start(schedule, price_to_tier)+ return _next_phase_tier_and_start(schedule, price_to_tier, price_to_cycle)def _next_phase_tier_and_start(schedule: stripe.SubscriptionSchedule,price_to_tier: dict[str, SubscriptionTier],-) -> tuple[SubscriptionTier, datetime] | None:- """Return (tier, start_datetime) of the phase that follows the active one.+ price_to_cycle: dict[str, BillingCycle],+) -> tuple[SubscriptionTier, datetime, BillingCycle | None] | None:+ """Return ``(tier, start_datetime, billing_cycle)`` of the phase following the active one.++ ``billing_cycle`` is the cycle of the next-phase price (``"monthly"``/``"yearly"``)+ when resolvable, ``None`` for unconfigured/legacy prices. Same-tier yearly→monthly+ schedules need this so the UI can distinguish a cycle-only change (where+ ``pending_tier == current_tier``) from a real tier downgrade.Using the phase's own ``start_date`` (not the subscription's current_period_end)is correct even for schedules created outside this flow — a dashboard-authored@@ -2059,8 +2151,10 @@ def _next_phase_tier_and_start(price = items[0].priceprice_id = price if isinstance(price, str) else price.idif price_id in price_to_tier:- return price_to_tier[price_id], datetime.fromtimestamp(- phase.start_date, tz=timezone.utc+ return (+ price_to_tier[price_id],+ datetime.fromtimestamp(phase.start_date, tz=timezone.utc),+ price_to_cycle.get(price_id),)logger.warning("next_phase_tier_and_start: unknown price %s on schedule %s",@@ -2079,14 +2173,61 @@ async def get_auto_top_up(user_id: str) -> AutoTopUpConfig:return AutoTopUpConfig.model_validate(user.top_up_config)-@cached(ttl_seconds=60, maxsize=8, cache_none=False)-async def get_subscription_price_id(tier: SubscriptionTier) -> str | None:- """Return Stripe Price ID for a tier from LaunchDarkly, cached for 60 seconds.+async def _resolve_cycle_for_price_id(price_id: str | None) -> BillingCycle | None:+ """Map a Stripe price ID back to its billing cycle via the LD price flag.++ Used by ``modify_stripe_subscription_for_tier`` to detect a same-tier+ cycle change (yearly→monthly downgrade vs monthly→yearly upgrade) before+ deciding between the immediate-proration path and the period-end schedule.+ Returns None when the price ID isn't configured for any tier+cycle (legacy+ or unconfigured price), which keeps the caller on the upgrade path.+ """+ if not price_id:+ return None+ priceable = (+ SubscriptionTier.BASIC,+ SubscriptionTier.PRO,+ SubscriptionTier.MAX,+ SubscriptionTier.BUSINESS,+ )+ monthly_prices, yearly_prices = await asyncio.gather(+ asyncio.gather(*[get_subscription_price_id(t, "monthly") for t in priceable]),+ asyncio.gather(*[get_subscription_price_id(t, "yearly") for t in priceable]),+ )+ if price_id in monthly_prices:+ return "monthly"+ if price_id in yearly_prices:+ return "yearly"+ return None- Reads the ``copilot-tier-stripe-prices`` JSON flag once and looks up the- requested tier. The flag is a JSON object keyed by tier enum value- (``{"PRO": "price_xxx", "MAX": "price_yyy"}``); tiers missing from the- payload resolve to ``None`` ("not offered").++def _ld_price_key(tier: SubscriptionTier, billing_cycle: BillingCycle) -> str:+ """Compose the LaunchDarkly key for a tier+cycle.++ Monthly keeps the legacy ``<TIER>`` key (so a flag value flipped from+ monthly-only to also-yearly never breaks an older deploy that still reads+ only the monthly key). Yearly lives under ``<TIER>_YEARLY``.+ """+ if billing_cycle == "yearly":+ return f"{tier.value}_YEARLY"+ return tier.value+++@cached(ttl_seconds=60, maxsize=16, cache_none=False)+async def get_subscription_price_id(+ tier: SubscriptionTier, billing_cycle: BillingCycle = "monthly"+) -> str | None:+ """Return Stripe Price ID for a tier+cycle from LaunchDarkly, cached 60s.++ Reads the ``copilot-tier-stripe-prices`` JSON flag and looks up:++ - Monthly: ``raw["<TIER>"]`` (e.g. ``raw["PRO"]``) — the existing key+ pre-yearly. Older deploys see this exact key, so adding yearly keys+ alongside it never breaks an in-flight rollout.+ - Yearly: ``raw["<TIER>_YEARLY"]`` (e.g. ``raw["PRO_YEARLY"]``). Yearly+ requests for a tier without a configured yearly key fail closed+ (return ``None``) instead of silently falling back to the monthly+ price.``cache_none=False`` prevents a transient LD failure from caching ``None``and blocking subscription upgrades for the full 60-second TTL window.@@ -2102,7 +2243,7 @@ async def get_subscription_price_id(tier: SubscriptionTier) -> str | None:raw,)return None- price_id = raw.get(tier.value)+ price_id = raw.get(_ld_price_key(tier, billing_cycle))return price_id if isinstance(price_id, str) and price_id else None@@ -2111,9 +2252,10 @@ async def create_subscription_checkout(tier: SubscriptionTier,success_url: str,cancel_url: str,+ billing_cycle: BillingCycle = "monthly",) -> str:"""Create a Stripe Checkout Session for a subscription. Returns the redirect URL."""- price_id = await get_subscription_price_id(tier)+ price_id = await get_subscription_price_id(tier, billing_cycle)if not price_id:raise ValueError(f"Subscription not available for tier {tier.value}")customer_id = await get_stripe_customer_id(user_id)@@ -2124,7 +2266,13 @@ async def create_subscription_checkout(line_items=[{"price": price_id, "quantity": 1}],success_url=success_url,cancel_url=cancel_url,- subscription_data={"metadata": {"user_id": user_id, "tier": tier.value}},+ subscription_data={+ "metadata": {+ "user_id": user_id,+ "tier": tier.value,+ "billing_cycle": billing_cycle,+ }+ },allow_promotion_codes=True,)if not session.url:@@ -2228,20 +2376,25 @@ async def sync_subscription_from_stripe(stripe_subscription: dict) -> None:items = stripe_subscription.get("items", {}).get("data", [])if items:price_id = items[0].get("price", {}).get("id", "")- basic_price, pro_price, max_price, business_price = await asyncio.gather(- get_subscription_price_id(SubscriptionTier.BASIC),- get_subscription_price_id(SubscriptionTier.PRO),- get_subscription_price_id(SubscriptionTier.MAX),- get_subscription_price_id(SubscriptionTier.BUSINESS),- )- if price_id and basic_price and price_id == basic_price:- tier = SubscriptionTier.BASIC- elif price_id and pro_price and price_id == pro_price:- tier = SubscriptionTier.PRO- elif price_id and max_price and price_id == max_price:- tier = SubscriptionTier.MAX- elif price_id and business_price and price_id == business_price:- tier = SubscriptionTier.BUSINESS+ priceable = (+ SubscriptionTier.BASIC,+ SubscriptionTier.PRO,+ SubscriptionTier.MAX,+ SubscriptionTier.BUSINESS,+ )+ # Gather monthly + yearly price IDs for every priceable tier so a user+ # on a yearly plan still maps back to the correct tier.+ prices = await asyncio.gather(+ *[get_subscription_price_id(t, "monthly") for t in priceable],+ *[get_subscription_price_id(t, "yearly") for t in priceable],+ )+ price_to_tier: dict[str, SubscriptionTier] = {}+ for t, pid in zip(priceable + priceable, prices):+ if pid:+ price_to_tier[pid] = t+ matched = price_to_tier.get(price_id) if price_id else None+ if matched is not None:+ tier = matchedelse:# Unknown or unconfigured price ID — preserve the user's current tier# rather than defaulting to BASIC. This prevents accidental downgrades@@ -2384,6 +2537,26 @@ async def sync_subscription_schedule_from_stripe(stripe_schedule: dict) -> None:await sync_subscription_from_stripe(dict(sub))+def _invoice_subscription_id(invoice: dict) -> str:+ """Resolve the subscription ID from a Stripe Invoice payload.++ Stripe API ≥2025-04-01 deprecated the top-level ``invoice.subscription``+ field; subscription invoices now carry it at+ ``invoice.parent.subscription_details.subscription``. Read the new path+ first and fall back to the legacy field so older API versions still work.+ Returns "" when neither is set (one-off invoices, etc.).+ """+ parent = invoice.get("parent") or {}+ if isinstance(parent, dict):+ details = parent.get("subscription_details") or {}+ if isinstance(details, dict):+ new_sub = details.get("subscription")+ if isinstance(new_sub, str) and new_sub:+ return new_sub+ legacy = invoice.get("subscription")+ return legacy if isinstance(legacy, str) and legacy else ""++async def handle_subscription_payment_failure(invoice: dict) -> None:"""Handle a failed Stripe subscription payment.@@ -2420,7 +2593,7 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:returnamount_due: int = invoice.get("amount_due", 0)- sub_id: str = invoice.get("subscription", "")+ sub_id = _invoice_subscription_id(invoice)invoice_id: str = invoice.get("id", "")if amount_due <= 0:@@ -2523,7 +2696,7 @@ async def handle_subscription_payment_success(invoice: dict) -> None:"handle_subscription_payment_success: missing customer in invoice; skipping")return- sub_id: str = invoice.get("subscription") or ""+ sub_id = _invoice_subscription_id(invoice)if not sub_id:# Non-subscription invoices (one-off invoices, etc.) — no credit grant.returndiff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.pyindex fb7e204474..f3f7b4ef02 100644--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py@@ -2,6 +2,7 @@Tests for Stripe-based subscription tier billing."""+from typing import Protocolfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -27,6 +28,19 @@ from backend.data.credit import ()+class _CacheClearable(Protocol):+ """Type-only view of the cache_clear attribute attached to functions+ decorated with ``@cached`` in ``backend.util.cache``. Lets the test file+ invoke ``cache_clear`` without ``# type: ignore[attr-defined]`` while+ still checking the call site for typos at type-check time."""++ def cache_clear(self) -> None: ...+++def _clear_cache(fn: _CacheClearable) -> None:+ fn.cache_clear()++@pytest.mark.asyncioasync def test_set_subscription_tier_updates_db():with (@@ -75,7 +89,11 @@ async def test_sync_subscription_from_stripe_active():"items": {"data": [{"price": {"id": "price_pro_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if billing_cycle != "monthly":+ return Noneif tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -107,6 +125,51 @@ async def test_sync_subscription_from_stripe_active():mock_set.assert_awaited_once_with("user-1", SubscriptionTier.PRO)+async def test_sync_subscription_from_stripe_yearly_pro_maps_to_pro():+ """A user on a yearly Pro plan still maps to SubscriptionTier.PRO."""+ mock_user = _make_user()+ stripe_sub = {+ "id": "sub_yearly",+ "customer": "cus_123",+ "status": "active",+ "items": {"data": [{"price": {"id": "price_pro_yearly"}}]},+ }++ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if tier == SubscriptionTier.PRO and billing_cycle == "monthly":+ return "price_pro_monthly"+ if tier == SubscriptionTier.PRO and billing_cycle == "yearly":+ return "price_pro_yearly"+ return None++ empty_list = MagicMock()+ empty_list.data = []+ empty_list.has_more = False++ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.data.credit.get_subscription_price_id",+ side_effect=mock_price_id,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list",+ return_value=empty_list,+ ),+ patch(+ "backend.data.credit.set_subscription_tier", new_callable=AsyncMock+ ) as mock_set,+ ):+ await sync_subscription_from_stripe(stripe_sub)+ mock_set.assert_awaited_once_with("user-1", SubscriptionTier.PRO)++@pytest.mark.asyncioasync def test_sync_subscription_from_stripe_idempotent_no_write_if_unchanged():"""Stripe retries webhooks; re-sending the same event must not re-write the DB."""@@ -118,7 +181,11 @@ async def test_sync_subscription_from_stripe_idempotent_no_write_if_unchanged():"items": {"data": [{"price": {"id": "price_pro_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if billing_cycle != "monthly":+ return Noneif tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -324,7 +391,9 @@ async def test_sync_subscription_from_stripe_trialing():"items": {"data": [{"price": {"id": "price_pro_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:if tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -763,7 +832,9 @@ async def test_sync_subscription_from_stripe_unknown_price_id_preserves_current_"items": {"data": [{"price": {"id": "price_unknown"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return "price_pro_monthly" if tier == SubscriptionTier.PRO else Nonewith (@@ -824,7 +895,9 @@ async def test_sync_subscription_from_stripe_business_tier():"items": {"data": [{"price": {"id": "price_biz_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:if tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -872,7 +945,9 @@ async def test_sync_subscription_from_stripe_basic_tier_via_ld_price():"items": {"data": [{"price": {"id": "price_basic_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:if tier == SubscriptionTier.BASIC:return "price_basic_monthly"if tier == SubscriptionTier.PRO:@@ -922,7 +997,9 @@ async def test_sync_subscription_from_stripe_cancels_stale_subs():"items": {"data": [{"price": {"id": "price_biz_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:if tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -972,7 +1049,9 @@ async def test_sync_subscription_from_stripe_stale_cancel_errors_swallowed():"items": {"data": [{"price": {"id": "price_pro_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:if tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -1014,7 +1093,7 @@ async def test_get_subscription_price_id_pro():from backend.data.credit import get_subscription_price_id# Clear cached state from other tests to ensure a fresh LD flag lookup.- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,@@ -1022,14 +1101,14 @@ async def test_get_subscription_price_id_pro():):price_id = await get_subscription_price_id(SubscriptionTier.PRO)assert price_id == "price_pro_monthly"- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncioasync def test_get_subscription_price_id_basic_returns_ld_flag():from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,@@ -1037,14 +1116,14 @@ async def test_get_subscription_price_id_basic_returns_ld_flag():):price_id = await get_subscription_price_id(SubscriptionTier.BASIC)assert price_id == "price_basic_monthly"- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncioasync def test_get_subscription_price_id_max():from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,@@ -1052,7 +1131,7 @@ async def test_get_subscription_price_id_max():):price_id = await get_subscription_price_id(SubscriptionTier.MAX)assert price_id == "price_max_monthly"- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1060,7 +1139,7 @@ async def test_get_subscription_price_id_enterprise_returns_none():from backend.data.credit import get_subscription_price_id# ENTERPRISE is never a key in the JSON flag → resolves to None.- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,@@ -1068,7 +1147,7 @@ async def test_get_subscription_price_id_enterprise_returns_none():):price_id = await get_subscription_price_id(SubscriptionTier.ENTERPRISE)assert price_id is None- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1076,7 +1155,7 @@ async def test_get_subscription_price_id_empty_flag_returns_none():"""Empty dict payload → every tier resolves to None."""from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,@@ -1090,7 +1169,7 @@ async def test_get_subscription_price_id_empty_flag_returns_none():SubscriptionTier.ENTERPRISE,):assert await get_subscription_price_id(tier) is None- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1098,7 +1177,7 @@ async def test_get_subscription_price_id_partial_dict():"""Dict with only PRO resolves PRO, other tiers return None."""from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,@@ -1107,9 +1186,9 @@ async def test_get_subscription_price_id_partial_dict():assert (await get_subscription_price_id(SubscriptionTier.PRO) == "price_pro_monthly")- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)assert await get_subscription_price_id(SubscriptionTier.MAX) is None- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1117,14 +1196,14 @@ async def test_get_subscription_price_id_empty_string_value_returns_none():"""Empty-string price_id in the JSON resolves to None (defensive)."""from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,return_value={"PRO": ""},):assert await get_subscription_price_id(SubscriptionTier.PRO) is None- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1132,16 +1211,16 @@ async def test_get_subscription_price_id_non_string_value_returns_none():"""Non-string price_id (e.g. number, null) resolves to None."""from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,return_value={"PRO": 123, "MAX": None},):assert await get_subscription_price_id(SubscriptionTier.PRO) is None- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)assert await get_subscription_price_id(SubscriptionTier.MAX) is None- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1149,7 +1228,7 @@ async def test_get_subscription_price_id_non_dict_payload_returns_none(caplog):"""A non-dict LD value logs a warning and returns None for every tier."""from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,@@ -1161,7 +1240,7 @@ async def test_get_subscription_price_id_non_dict_payload_returns_none(caplog):assert any("copilot-tier-stripe-prices" in rec.message for rec in caplog.records)- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1170,14 +1249,14 @@ async def test_get_subscription_price_id_ld_raises_returns_none():get_feature_flag_value → default None) returns None and does not raise."""from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)with patch("backend.data.credit.get_feature_flag_value",new_callable=AsyncMock,return_value=None,):assert await get_subscription_price_id(SubscriptionTier.PRO) is None- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1190,7 +1269,7 @@ async def test_get_subscription_price_id_none_not_cached():"""from backend.data.credit import get_subscription_price_id- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)mock_ld = AsyncMock(side_effect=[None, {"PRO": "price_pro_monthly"}])with patch("backend.data.credit.get_feature_flag_value", mock_ld):# First call: LD returns None (transient failure)@@ -1200,7 +1279,78 @@ async def test_get_subscription_price_id_none_not_cached():second = await get_subscription_price_id(SubscriptionTier.PRO)assert second == "price_pro_monthly"assert mock_ld.call_count == 2 # both calls hit LD (None was not cached)- get_subscription_price_id.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_subscription_price_id)+++async def test_get_subscription_price_id_yearly_suffix_key():+ """Yearly request reads the <TIER>_YEARLY key."""+ from backend.data.credit import get_subscription_price_id++ _clear_cache(get_subscription_price_id)+ with patch(+ "backend.data.credit.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value={"PRO": "price_pro_m", "PRO_YEARLY": "price_pro_y"},+ ):+ assert (+ await get_subscription_price_id(SubscriptionTier.PRO, "yearly")+ == "price_pro_y"+ )+ _clear_cache(get_subscription_price_id)+++async def test_get_subscription_price_id_monthly_unchanged_after_yearly_addition():+ """Adding a yearly suffix key never changes the monthly lookup. Old code+ that only reads <TIER> keeps returning the monthly price unaffected."""+ from backend.data.credit import get_subscription_price_id++ _clear_cache(get_subscription_price_id)+ with patch(+ "backend.data.credit.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value={"PRO": "price_pro_m", "PRO_YEARLY": "price_pro_y"},+ ):+ assert (+ await get_subscription_price_id(SubscriptionTier.PRO, "monthly")+ == "price_pro_m"+ )+ _clear_cache(get_subscription_price_id)+++async def test_get_subscription_price_id_yearly_missing_returns_none():+ """No <TIER>_YEARLY key → yearly request fails closed (no silent monthly)."""+ from backend.data.credit import get_subscription_price_id++ _clear_cache(get_subscription_price_id)+ with patch(+ "backend.data.credit.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value={"PRO": "price_pro_m"},+ ):+ assert await get_subscription_price_id(SubscriptionTier.PRO, "yearly") is None+ _clear_cache(get_subscription_price_id)+++async def test_get_subscription_price_id_monthly_only_flag_serves_monthly():+ """Backward compat: a monthly-only flag value (pre-yearly rollout) keeps+ serving monthly requests exactly as before this PR."""+ from backend.data.credit import get_subscription_price_id++ _clear_cache(get_subscription_price_id)+ with patch(+ "backend.data.credit.get_feature_flag_value",+ new_callable=AsyncMock,+ return_value={"PRO": "price_pro_monthly_only"},+ ):+ assert (+ await get_subscription_price_id(SubscriptionTier.PRO, "monthly")+ == "price_pro_monthly_only"+ )+ _clear_cache(get_subscription_price_id)@pytest.mark.asyncio@@ -1247,7 +1397,9 @@ async def test_sync_subscription_from_stripe_metadata_user_id_matches():"items": {"data": [{"price": {"id": "price_pro_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return "price_pro_monthly" if tier == SubscriptionTier.PRO else Noneempty_list = MagicMock()@@ -1317,7 +1469,9 @@ async def test_sync_subscription_from_stripe_no_metadata_user_id_skips_check():# No "metadata" key at all}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return "price_pro_monthly" if tier == SubscriptionTier.PRO else Noneempty_list = MagicMock()@@ -1838,6 +1992,11 @@ async def test_modify_stripe_subscription_for_tier_modifies_existing_sub():items=[{"id": "si_abc", "price": "price_pro_monthly"}],proration_behavior="always_invoice",payment_behavior="error_if_incomplete",+ metadata={+ "user_id": "user-1",+ "tier": SubscriptionTier.PRO.value,+ "billing_cycle": "monthly",+ },)mock_set_tier.assert_awaited_once_with("user-1", SubscriptionTier.PRO)@@ -1897,6 +2056,11 @@ async def test_modify_stripe_subscription_for_tier_clears_cancel_at_period_end_oitems=[{"id": "si_abc", "price": "price_biz_monthly"}],proration_behavior="always_invoice",payment_behavior="error_if_incomplete",+ metadata={+ "user_id": "user-1",+ "tier": SubscriptionTier.BUSINESS.value,+ "billing_cycle": "monthly",+ },cancel_at_period_end=False,)mock_set_tier.assert_awaited_once_with("user-1", SubscriptionTier.BUSINESS)@@ -2122,6 +2286,11 @@ async def test_modify_stripe_subscription_for_tier_upgrade_immediate_proration()items=[{"id": "si_pro", "price": "price_biz_monthly"}],proration_behavior="always_invoice",payment_behavior="error_if_incomplete",+ metadata={+ "user_id": "user-1",+ "tier": SubscriptionTier.BUSINESS.value,+ "billing_cycle": "monthly",+ },)mock_schedule_create.assert_not_called()@@ -2182,6 +2351,11 @@ async def test_modify_stripe_subscription_for_tier_pro_to_max_bills_immediately(items=[{"id": "si_pro", "price": "price_max_monthly"}],proration_behavior="always_invoice",payment_behavior="error_if_incomplete",+ metadata={+ "user_id": "user-1",+ "tier": SubscriptionTier.MAX.value,+ "billing_cycle": "monthly",+ },)mock_set_tier.assert_awaited_once_with("user-1", SubscriptionTier.MAX)@@ -2383,7 +2557,7 @@ async def test_get_pending_subscription_change_cancel_at_period_end():"""cancel_at_period_end=True maps to pending NO_TIER at current_period_end."""import time as time_mod- get_pending_subscription_change.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_pending_subscription_change)now = int(time_mod.time())period_end = now + 10 * 24 * 3600@@ -2402,7 +2576,9 @@ async def test_get_pending_subscription_change_cancel_at_period_end():mock_user = MagicMock()mock_user.stripe_customer_id = "cus_abc"- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:if tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -2428,9 +2604,10 @@ async def test_get_pending_subscription_change_cancel_at_period_end():result = await get_pending_subscription_change("user-1")assert result is not None- pending_tier, effective_at = result+ pending_tier, effective_at, pending_cycle = resultassert pending_tier == SubscriptionTier.NO_TIERassert int(effective_at.timestamp()) == period_end+ assert pending_cycle is None@pytest.mark.asyncio@@ -2438,7 +2615,7 @@ async def test_get_pending_subscription_change_from_schedule():"""A schedule whose next phase uses the PRO price maps to pending_tier=PRO."""import time as time_mod- get_pending_subscription_change.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_pending_subscription_change)now = int(time_mod.time())period_end = now + 10 * 24 * 3600@@ -2475,7 +2652,11 @@ async def test_get_pending_subscription_change_from_schedule():mock_user = MagicMock()mock_user.stripe_customer_id = "cus_abc"- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if billing_cycle == "yearly":+ return Noneif tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -2506,9 +2687,100 @@ async def test_get_pending_subscription_change_from_schedule():result = await get_pending_subscription_change("user-1")assert result is not None- pending_tier, effective_at = result+ pending_tier, effective_at, pending_cycle = resultassert pending_tier == SubscriptionTier.PROassert int(effective_at.timestamp()) == period_end+ assert pending_cycle == "monthly"+++async def test_get_pending_subscription_change_yearly_next_phase_maps_to_tier():+ """A schedule whose next phase uses a YEARLY price still resolves to the+ correct tier — yearly subscribers must see their pending downgrade in UI."""+ import time as time_mod++ _clear_cache(get_pending_subscription_change)++ now = int(time_mod.time())+ period_end = now + 10 * 24 * 3600+ mock_sub = stripe.Subscription.construct_from(+ {+ "id": "sub_biz_yearly",+ "current_period_end": period_end,+ "cancel_at_period_end": False,+ "schedule": "sub_sched_yearly",+ },+ "k",+ )+ mock_list = MagicMock()+ mock_list.data = [mock_sub]++ mock_schedule = stripe.SubscriptionSchedule.construct_from(+ {+ "id": "sub_sched_yearly",+ "phases": [+ {+ "start_date": now - 3 * 24 * 3600,+ "end_date": period_end,+ "items": [{"price": "price_biz_yearly"}],+ },+ {+ "start_date": period_end,+ "items": [{"price": "price_pro_yearly"}],+ },+ ],+ },+ "k",+ )++ mock_user = MagicMock()+ mock_user.stripe_customer_id = "cus_abc"++ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if billing_cycle == "yearly":+ if tier == SubscriptionTier.PRO:+ return "price_pro_yearly"+ if tier == SubscriptionTier.BUSINESS:+ return "price_biz_yearly"+ return None+ # Monthly entries also configured (mixed config) — confirms the lookup+ # picks up the yearly mapping rather than only seeing monthly.+ if tier == SubscriptionTier.PRO:+ return "price_pro_monthly"+ if tier == SubscriptionTier.BUSINESS:+ return "price_biz_monthly"+ return None++ with (+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ ),+ patch(+ "backend.data.credit.get_subscription_price_id",+ side_effect=mock_price_id,+ ),+ 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,+ return_value=mock_schedule,+ ),+ ):+ result = await get_pending_subscription_change("user-yearly")++ assert result is not None+ pending_tier, effective_at, pending_cycle = result+ assert pending_tier == SubscriptionTier.PRO+ assert int(effective_at.timestamp()) == period_end+ assert pending_cycle == "yearly"@pytest.mark.asyncio@@ -2516,7 +2788,7 @@ async def test_get_pending_subscription_change_from_schedule_to_basic():"""A schedule whose next phase uses the BASIC price maps to pending_tier=BASIC."""import time as time_mod- get_pending_subscription_change.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_pending_subscription_change)now = int(time_mod.time())period_end = now + 10 * 24 * 3600@@ -2553,7 +2825,11 @@ async def test_get_pending_subscription_change_from_schedule_to_basic():mock_user = MagicMock()mock_user.stripe_customer_id = "cus_abc"- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if billing_cycle == "yearly":+ return Noneif tier == SubscriptionTier.BASIC:return "price_basic_monthly"if tier == SubscriptionTier.PRO:@@ -2586,9 +2862,10 @@ async def test_get_pending_subscription_change_from_schedule_to_basic():result = await get_pending_subscription_change("user-1")assert result is not None- pending_tier, effective_at = result+ pending_tier, effective_at, pending_cycle = resultassert pending_tier == SubscriptionTier.BASICassert int(effective_at.timestamp()) == period_end+ assert pending_cycle == "monthly"@pytest.mark.asyncio@@ -2596,7 +2873,7 @@ async def test_get_pending_subscription_change_none_when_no_schedule_or_cancel()"""Returns None when neither a schedule nor cancel_at_period_end is set."""import time as time_mod- get_pending_subscription_change.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_pending_subscription_change)now = int(time_mod.time())mock_sub = stripe.Subscription.construct_from(@@ -2614,7 +2891,9 @@ async def test_get_pending_subscription_change_none_when_no_schedule_or_cancel()mock_user = MagicMock()mock_user.stripe_customer_id = "cus_abc"- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return {SubscriptionTier.PRO: "price_pro",SubscriptionTier.BUSINESS: "price_biz",@@ -2641,6 +2920,92 @@ async def test_get_pending_subscription_change_none_when_no_schedule_or_cancel()assert result is None+async def test_get_pending_subscription_change_same_tier_yearly_to_monthly_reports_cycle():+ """Same-tier yearly→monthly schedule must surface the next-phase cycle so the+ UI can describe a cycle-only switch correctly (pending_tier == current tier+ would otherwise look like a no-op or a confusing same-tier "downgrade")."""+ import time as time_mod++ _clear_cache(get_pending_subscription_change)++ now = int(time_mod.time())+ period_end = now + 200 * 24 * 3600+ mock_sub = stripe.Subscription.construct_from(+ {+ "id": "sub_pro_yearly",+ "current_period_end": period_end,+ "cancel_at_period_end": False,+ "schedule": "sub_sched_cycle",+ },+ "k",+ )+ mock_list = MagicMock()+ mock_list.data = [mock_sub]++ mock_schedule = stripe.SubscriptionSchedule.construct_from(+ {+ "id": "sub_sched_cycle",+ "phases": [+ {+ "start_date": now - 5 * 24 * 3600,+ "end_date": period_end,+ "items": [{"price": "price_pro_yearly"}],+ },+ {+ "start_date": period_end,+ "items": [{"price": "price_pro_monthly"}],+ },+ ],+ },+ "k",+ )++ mock_user = MagicMock()+ mock_user.stripe_customer_id = "cus_abc"++ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:+ if billing_cycle == "yearly":+ return {+ SubscriptionTier.PRO: "price_pro_yearly",+ SubscriptionTier.MAX: "price_max_yearly",+ }.get(tier)+ return {+ SubscriptionTier.PRO: "price_pro_monthly",+ SubscriptionTier.MAX: "price_max_monthly",+ }.get(tier)++ with (+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ ),+ patch(+ "backend.data.credit.get_subscription_price_id",+ side_effect=mock_price_id,+ ),+ 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,+ return_value=mock_schedule,+ ),+ ):+ result = await get_pending_subscription_change("user-yearly-to-monthly")++ assert result is not None+ pending_tier, _, pending_cycle = result+ assert pending_tier == SubscriptionTier.PRO+ assert pending_cycle == "monthly"++@pytest.mark.asyncioasync def test_sync_subscription_schedule_from_stripe_retrieves_and_delegates():"""subscription_schedule.released triggers a sync via the active subscription object."""@@ -2735,7 +3100,9 @@ async def test_sync_subscription_from_stripe_phase_transition_updates_tier():"items": {"data": [{"price": {"id": "price_pro_monthly"}}]},}- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:if tier == SubscriptionTier.PRO:return "price_pro_monthly"if tier == SubscriptionTier.BUSINESS:@@ -3135,6 +3502,80 @@ async def test_upgrade_releases_pending_schedule():items=[{"id": "si_pro", "price": "price_biz_monthly"}],proration_behavior="always_invoice",payment_behavior="error_if_incomplete",+ metadata={+ "user_id": "user-1",+ "tier": SubscriptionTier.BUSINESS.value,+ "billing_cycle": "monthly",+ },+ )+++async def test_modify_stripe_subscription_for_tier_upgrade_refreshes_metadata():+ """Pro→Max yearly upgrade must overwrite the original sub.metadata so the+ Stripe Dashboard and downstream observability reflect the new tier+cycle+ instead of the stale values left over from the original checkout."""+ mock_sub = stripe.Subscription.construct_from(+ {+ "id": "sub_pro",+ "items": {"data": [{"id": "si_pro", "price": {"id": "price_pro_monthly"}}]},+ "schedule": None,+ "cancel_at_period_end": False,+ "metadata": {+ "user_id": "user-1",+ "tier": SubscriptionTier.PRO.value,+ "billing_cycle": "monthly",+ },+ },+ "k",+ )+ mock_list = MagicMock()+ mock_list.data = [mock_sub]++ mock_user = MagicMock(spec=User)+ mock_user.stripe_customer_id = "cus_abc"+ mock_user.subscription_tier = SubscriptionTier.PRO++ with (+ patch(+ "backend.data.credit.get_subscription_price_id",+ new_callable=AsyncMock,+ return_value="price_max_yearly",+ ),+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ new_callable=AsyncMock,+ return_value=mock_list,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.modify_async",+ new_callable=AsyncMock,+ ) as mock_modify,+ patch(+ "backend.data.credit.set_subscription_tier",+ new_callable=AsyncMock,+ ),+ ):+ result = await modify_stripe_subscription_for_tier(+ "user-1", SubscriptionTier.MAX, billing_cycle="yearly"+ )++ assert result is True+ mock_modify.assert_called_once_with(+ "sub_pro",+ items=[{"id": "si_pro", "price": "price_max_yearly"}],+ proration_behavior="always_invoice",+ payment_behavior="error_if_incomplete",+ metadata={+ "user_id": "user-1",+ "tier": SubscriptionTier.MAX.value,+ "billing_cycle": "yearly",+ },)@@ -3165,9 +3606,14 @@ async def test_next_phase_tier_and_start_logs_unknown_price(caplog):"k",)price_to_tier = {"price_pro_monthly": SubscriptionTier.PRO}+ price_to_cycle = {"price_pro_monthly": "monthly"}with caplog.at_level(logging.WARNING, logger="backend.data.credit"):- result = _next_phase_tier_and_start(schedule, price_to_tier)+ result = _next_phase_tier_and_start(+ schedule,+ price_to_tier,+ price_to_cycle, # type: ignore[arg-type]+ )assert result is Noneassert any(@@ -3183,12 +3629,14 @@ async def test_get_pending_subscription_change_raises_when_price_lookups_fail():@cached wrapper doesn't store None and hide pending changes for 30s."""from backend.data.credit import PendingChangeUnknown- get_pending_subscription_change.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_pending_subscription_change)mock_user = MagicMock()mock_user.stripe_customer_id = "cus_abc"- async def mock_price_id(tier: SubscriptionTier) -> str | None:+ async def mock_price_id(+ tier: SubscriptionTier, billing_cycle: str = "monthly"+ ) -> str | None:return Nonewith (@@ -3211,7 +3659,7 @@ async def test_release_pending_subscription_schedule_invalidates_cache_on_partia"""If schedule.release succeeds but cancel_at_period_end clear fails, thecache must still be invalidated — otherwise the UI shows a stale pendingbanner for up to 30s even though the schedule was actually released."""- get_pending_subscription_change.cache_clear() # type: ignore[attr-defined]+ _clear_cache(get_pending_subscription_change)mock_user = MagicMock()mock_user.stripe_customer_id = "cus_abc"@@ -3342,3 +3790,243 @@ async def test_admin_get_user_history_include_inactive_omits_filter():where = prisma_mock.find_many.await_args.kwargs["where"]assert "isActive" not in whereassert where["type"] == CreditTransactionType.TOP_UP+++async def test_modify_stripe_subscription_same_tier_yearly_to_monthly_schedules_downgrade():+ """Same-tier yearly→monthly is a cycle downgrade: defer to period end via+ Subscription Schedule, NOT immediate always_invoice modify.++ Without this branch, the dialog promise ("no charge today, switch at end of+ yearly period") is broken — Stripe would change the price + draft a $0+ prorated invoice immediately, mid-period."""+ import time as time_mod++ now = int(time_mod.time())+ period_end = now + 200 * 24 * 3600+ mock_sub = stripe.Subscription.construct_from(+ {+ "id": "sub_pro_yearly",+ "items": {+ "data": [{"id": "si_pro_y", "price": {"id": "price_pro_yearly"}}]+ },+ "current_period_start": now - 165 * 24 * 3600,+ "current_period_end": period_end,+ "schedule": None,+ "cancel_at_period_end": False,+ },+ "k",+ )+ mock_list = MagicMock()+ mock_list.data = [mock_sub]++ mock_user = MagicMock(spec=User)+ mock_user.stripe_customer_id = "cus_abc"+ mock_user.subscription_tier = SubscriptionTier.PRO++ mock_schedule = stripe.SubscriptionSchedule.construct_from(+ {"id": "sub_sched_cycle"}, "k"+ )++ async def price_lookup(tier: SubscriptionTier, billing_cycle: str = "monthly"):+ if tier == SubscriptionTier.PRO and billing_cycle == "monthly":+ return "price_pro_monthly"+ if tier == SubscriptionTier.PRO and billing_cycle == "yearly":+ return "price_pro_yearly"+ if tier == SubscriptionTier.MAX and billing_cycle == "monthly":+ return "price_max_monthly"+ if tier == SubscriptionTier.MAX and billing_cycle == "yearly":+ return "price_max_yearly"+ return None++ with (+ patch(+ "backend.data.credit.get_subscription_price_id",+ new=AsyncMock(side_effect=price_lookup),+ ),+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ new_callable=AsyncMock,+ return_value=mock_list,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.modify_async",+ new_callable=AsyncMock,+ ) as mock_modify,+ patch(+ "backend.data.credit.stripe.SubscriptionSchedule.create_async",+ new_callable=AsyncMock,+ return_value=mock_schedule,+ ) as mock_schedule_create,+ patch(+ "backend.data.credit.stripe.SubscriptionSchedule.modify_async",+ new_callable=AsyncMock,+ ) as mock_schedule_modify,+ ):+ result = await modify_stripe_subscription_for_tier(+ "user-1", SubscriptionTier.PRO, billing_cycle="monthly"+ )++ assert result is True+ # Did NOT bill immediately — no Subscription.modify with always_invoice.+ mock_modify.assert_not_called()+ # Created a schedule that runs the current yearly price to period end, then+ # flips to the monthly price afterwards.+ mock_schedule_create.assert_called_once_with(from_subscription="sub_pro_yearly")+ assert mock_schedule_modify.call_count == 1+ _, kwargs = mock_schedule_modify.call_args+ phases = kwargs["phases"]+ assert phases[0]["items"][0]["price"] == "price_pro_yearly"+ assert phases[0]["end_date"] == period_end+ assert phases[1]["items"][0]["price"] == "price_pro_monthly"+ assert phases[0]["proration_behavior"] == "none"+ assert phases[1]["proration_behavior"] == "none"+++async def test_modify_stripe_subscription_same_tier_monthly_to_yearly_immediate():+ """Same-tier monthly→yearly is a cycle *upgrade* (more commitment): keep+ the immediate proration semantic so the user is billed for the longer+ cycle today rather than a free upgrade until period end."""+ mock_sub = stripe.Subscription.construct_from(+ {+ "id": "sub_pro_monthly",+ "items": {+ "data": [{"id": "si_pro_m", "price": {"id": "price_pro_monthly"}}]+ },+ "schedule": None,+ "cancel_at_period_end": False,+ },+ "k",+ )+ mock_list = MagicMock()+ mock_list.data = [mock_sub]++ mock_user = MagicMock(spec=User)+ mock_user.stripe_customer_id = "cus_abc"+ mock_user.subscription_tier = SubscriptionTier.PRO++ async def price_lookup(tier: SubscriptionTier, billing_cycle: str = "monthly"):+ if tier == SubscriptionTier.PRO and billing_cycle == "monthly":+ return "price_pro_monthly"+ if tier == SubscriptionTier.PRO and billing_cycle == "yearly":+ return "price_pro_yearly"+ if tier == SubscriptionTier.MAX and billing_cycle == "monthly":+ return "price_max_monthly"+ if tier == SubscriptionTier.MAX and billing_cycle == "yearly":+ return "price_max_yearly"+ return None++ with (+ patch(+ "backend.data.credit.get_subscription_price_id",+ new=AsyncMock(side_effect=price_lookup),+ ),+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ new_callable=AsyncMock,+ return_value=mock_list,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.modify_async",+ new_callable=AsyncMock,+ ) as mock_modify,+ patch(+ "backend.data.credit.stripe.SubscriptionSchedule.create_async",+ new_callable=AsyncMock,+ ) as mock_schedule_create,+ patch(+ "backend.data.credit.set_subscription_tier",+ new_callable=AsyncMock,+ ),+ ):+ result = await modify_stripe_subscription_for_tier(+ "user-1", SubscriptionTier.PRO, billing_cycle="yearly"+ )++ assert result is True+ mock_modify.assert_called_once_with(+ "sub_pro_monthly",+ items=[{"id": "si_pro_m", "price": "price_pro_yearly"}],+ proration_behavior="always_invoice",+ payment_behavior="error_if_incomplete",+ metadata={+ "user_id": "user-1",+ "tier": SubscriptionTier.PRO.value,+ "billing_cycle": "yearly",+ },+ )+ mock_schedule_create.assert_not_called()+++async def test_modify_stripe_subscription_tier_upgrade_yearly_still_immediate():+ """Regression: tier upgrade (PRO→MAX) on yearly stays on the immediate+ always_invoice path — same-tier-cycle-downgrade detection must not+ accidentally route tier upgrades to the period-end schedule."""+ mock_sub = stripe.Subscription.construct_from(+ {+ "id": "sub_pro_yearly",+ "items": {+ "data": [{"id": "si_pro_y", "price": {"id": "price_pro_yearly"}}]+ },+ "schedule": None,+ "cancel_at_period_end": False,+ },+ "k",+ )+ mock_list = MagicMock()+ mock_list.data = [mock_sub]++ mock_user = MagicMock(spec=User)+ mock_user.stripe_customer_id = "cus_abc"+ mock_user.subscription_tier = SubscriptionTier.PRO++ with (+ patch(+ "backend.data.credit.get_subscription_price_id",+ new_callable=AsyncMock,+ return_value="price_max_yearly",+ ),+ patch(+ "backend.data.credit.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ new_callable=AsyncMock,+ return_value=mock_list,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.modify_async",+ new_callable=AsyncMock,+ ) as mock_modify,+ patch(+ "backend.data.credit.stripe.SubscriptionSchedule.create_async",+ new_callable=AsyncMock,+ ) as mock_schedule_create,+ patch(+ "backend.data.credit.set_subscription_tier",+ new_callable=AsyncMock,+ ),+ ):+ result = await modify_stripe_subscription_for_tier(+ "user-1", SubscriptionTier.MAX, billing_cycle="yearly"+ )++ assert result is True+ mock_modify.assert_called_once()+ _, kwargs = mock_modify.call_args+ assert kwargs["proration_behavior"] == "always_invoice"+ mock_schedule_create.assert_not_called()diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsxindex a5bebfe782..6387c1e8e7 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx@@ -4,8 +4,8 @@ import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";import { FadeIn } from "@/components/atoms/FadeIn/FadeIn";import { Text } from "@/components/atoms/Text/Text";import { cn } from "@/lib/utils";-import { PlanCard } from "./components/PlanCard/PlanCard";-import { PLAN_KEYS, PLANS } from "./helpers";+import { PlanCard } from "@/components/molecules/PlanCard/PlanCard";+import { PLAN_KEYS, PLANS } from "@/components/molecules/PlanCard/plans";import { useSubscriptionStep } from "./useSubscriptionStep";export function SubscriptionStep() {diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/helpers.tsdeleted file mode 100644index 0b978ea6c4..0000000000--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/helpers.ts+++ /dev/null@@ -1,30 +0,0 @@-import { type Country } from "../../countries";-import { type PlanDef, YEARLY_PRICE_FACTOR } from "../../helpers";--interface PriceComputationArgs {- plan: PlanDef;- country: Country;- isYearly: boolean;-}--export function computePlanPricing({- plan,- country,- isYearly,-}: PriceComputationArgs) {- const monthlyLocal =- plan.usdMonthly !== null ? plan.usdMonthly * country.rate : null;- const displayPrice =- monthlyLocal !== null- ? isYearly- ? monthlyLocal * YEARLY_PRICE_FACTOR * 12- : monthlyLocal- : null;- const monthlyEquiv =- isYearly && monthlyLocal !== null- ? monthlyLocal * YEARLY_PRICE_FACTOR- : null;- const perLabel = isYearly ? "/ year" : "/ month";-- return { displayPrice, monthlyEquiv, perLabel };-}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/helpers.tsdeleted file mode 100644index 207f6b12ce..0000000000--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/helpers.ts+++ /dev/null@@ -1,88 +0,0 @@-export const PRO_USD_MONTHLY = 50;-export const MAX_USD_MONTHLY = 320;-// Fraction of the full monthly price paid when billed yearly. 0.85 = 15% off.-export const YEARLY_PRICE_FACTOR = 0.85;-export const TEAM_INTAKE_FORM_URL = "https://tally.so/r/2Eb9zj";--export const PLAN_KEYS = {- PRO: "PRO",- MAX: "MAX",- TEAM: "TEAM",-} as const;-export type PlanKey = (typeof PLAN_KEYS)[keyof typeof PLAN_KEYS];--export interface PlanDef {- key: PlanKey;- name: string;- usage: string | null;- usdMonthly: number | null;- description: string;- features: string[];- cta: string;- highlighted: boolean;- badge: string | null;- buttonVariant: "primary" | "secondary";-}--export const PLANS: PlanDef[] = [- {- key: PLAN_KEYS.PRO,- name: "Pro",- usage: "1x",- usdMonthly: PRO_USD_MONTHLY,- description:- "For individuals getting started with dependable everyday automation.",- features: [- "Access to virtually any leading AI model",- "Agents work non-stop in the background",- "Visual agent builder and chat-based agent creation",- "File-aware agents that can work with your documents",- "End-to-end agent management and run visibility",- "Scheduled and event-based triggers",- ],- cta: "Get Pro",- highlighted: false,- badge: null,- buttonVariant: "secondary",- },- {- key: PLAN_KEYS.MAX,- name: "Max",- usage: "8.5x",- usdMonthly: MAX_USD_MONTHLY,- description: "For users who are serious about getting more work done.",- features: [- "Includes everything in Pro",- "8.5x Pro usage",- "5x file storage",- "Early access to features before anyone else",- "Expand our extensive integration library",- "Priority support",- "Help drive the roadmap for new features",- ],- cta: "Upgrade to Max",- highlighted: true,- badge: "Best value",- buttonVariant: "primary",- },- {- key: PLAN_KEYS.TEAM,- name: "Team",- usage: null,- usdMonthly: null,- description:- "For teams that need collaboration, controls, and custom usage.",- features: [- "Multi-user workspaces",- "Admin controls & roles",- "Centralized billing & seat management",- "Collaboration & approvals",- "Security & compliance options",- "Secure access for shared integrations",- ],- cta: "Contact sales",- highlighted: false,- badge: "Coming soon",- buttonVariant: "secondary",- },-];diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.tsindex 33f0699936..e9efd1d40b 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts@@ -6,11 +6,15 @@ import { environment } from "@/services/environment";import { useState } from "react";import { normalizeOnboardingProfile } from "../../helpers";import { useOnboardingWizardStore } from "../../store";-import { COUNTRIES } from "./countries";-import { PLAN_KEYS, type PlanKey, TEAM_INTAKE_FORM_URL } from "./helpers";+import { COUNTRIES } from "@/components/molecules/PlanCard/countries";+import {+ PLAN_KEYS,+ type PlanKey,+ TEAM_INTAKE_FORM_URL,+} from "@/components/molecules/PlanCard/plans";const PLAN_TO_TIER: Record<- Exclude<PlanKey, typeof PLAN_KEYS.TEAM>,+ Exclude<PlanKey, typeof PLAN_KEYS.TEAM | typeof PLAN_KEYS.BUSINESS>,SubscriptionTierRequestTier> = {PRO: "PRO",@@ -53,6 +57,7 @@ export function useSubscriptionStep() {window.open(TEAM_INTAKE_FORM_URL, "_blank", "noopener,noreferrer");return;}+ if (planKey === PLAN_KEYS.BUSINESS) return;if (isProcessing) return;setIsSubmitting(true);@@ -91,6 +96,7 @@ export function useSubscriptionStep() {tier,success_url: `${baseUrl}?step=5&subscription=success`,cancel_url: `${baseUrl}?step=4&subscription=cancelled`,+ billing_cycle: isYearly ? "yearly" : "monthly",},});const url = (result?.data as CheckoutResponse | undefined)?.url;diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsxindex 3d292aaaf7..07dba07c18 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx@@ -104,6 +104,55 @@ describe("SubscriptionStep", () => {expect(capturedProfileBody!.pain_points).toEqual(["Repetitive work"]);});+ test("toggling yearly + selecting Pro forwards billing_cycle=yearly", async () => {+ let capturedTierBody: {+ tier?: string;+ billing_cycle?: string;+ } | null = null;++ server.use(+ http.post("*/api/onboarding/profile", () =>+ HttpResponse.json({}, { status: 200 }),+ ),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedTierBody = (await request.json()) as typeof capturedTierBody;+ return HttpResponse.json({ url: null });+ }),+ );++ render(<SubscriptionStep />);+ fireEvent.click(screen.getByRole("button", { name: /Yearly billing/i }));+ fireEvent.click(screen.getByRole("button", { name: /Get Pro/i }));++ await waitFor(() => {+ expect(capturedTierBody).not.toBeNull();+ });+ expect(capturedTierBody!.tier).toBe("PRO");+ expect(capturedTierBody!.billing_cycle).toBe("yearly");+ });++ test("default monthly billing forwards billing_cycle=monthly", async () => {+ let capturedTierBody: { billing_cycle?: string } | null = null;++ server.use(+ http.post("*/api/onboarding/profile", () =>+ HttpResponse.json({}, { status: 200 }),+ ),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedTierBody = (await request.json()) as typeof capturedTierBody;+ return HttpResponse.json({ url: null });+ }),+ );++ render(<SubscriptionStep />);+ fireEvent.click(screen.getByRole("button", { name: /Get Pro/i }));++ await waitFor(() => {+ expect(capturedTierBody).not.toBeNull();+ });+ expect(capturedTierBody!.billing_cycle).toBe("monthly");+ });+test("selecting Max uses the MAX tier in the Stripe Checkout request", async () => {let capturedTierBody: { tier?: string } | null = null;diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsxindex 24105f7b4e..a50cb6d3eb 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/PaywallModal.tsx@@ -1,19 +1,139 @@"use client";import { Dialog } from "@/components/molecules/Dialog/Dialog";-import { SubscriptionTierSection } from "@/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { Text } from "@/components/atoms/Text/Text";+import { PlanCard } from "@/components/molecules/PlanCard/PlanCard";+import { cn } from "@/lib/utils";+import { SwitchTierDialog } from "../settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog";+import { usePaywallModal } from "./usePaywallModal";-// Non-dismissable Stripe paywall. The user can only exit by picking a tier-// (Stripe Checkout or modify-in-place). Reuses the existing tier picker so-// the underlying Checkout / modify wiring stays in one place — the-// SubscriptionTierSection already renders its own "Pick a plan" banner +-// description when tier === "BASIC", so the dialog itself is title-less.+// Non-dismissable Stripe paywall for NO_TIER users. Reuses the onboarding+// PlanCard + Monthly/Yearly toggle so both surfaces share one visual.export function PaywallModal() {+ const {+ isLoading,+ plans,+ country,+ isYearly,+ selectedCycle,+ setSelectedCycle,+ handleSelectPlan,+ isPending,+ selectedTier,+ pendingTier,+ pendingTierLabel,+ confirmPendingTier,+ cancelPendingTier,+ } = usePaywallModal();+return (<Dialog forceOpen controlled={{ isOpen: true, set: () => {} }}><Dialog.Content>- <SubscriptionTierSection />+ <div className="flex w-full flex-col items-center gap-4 px-2 py-2">+ <div className="flex flex-col items-center gap-1 text-center">+ <Text+ variant="h3"+ className="!text-[1.375rem] !leading-[1.6rem] md:!text-[1.75rem] md:!leading-[2.5rem]"+ >+ Choose the plan that's right for{" "}+ <span className="bg-gradient-to-r from-purple-500 to-indigo-500 bg-clip-text text-transparent">+ you+ </span>+ </Text>+ <Text variant="body" className="!text-zinc-500">+ Pick a plan to unlock AutoPilot and start running agents.+ </Text>+ </div>++ {plans.length > 0 && (+ <div+ role="radiogroup"+ aria-label="Billing cycle"+ className="inline-flex rounded-full border border-[#d8d8d8] bg-zinc-100 p-[3px]"+ >+ {(["monthly", "yearly"] as const).map((cycle) => (+ <button+ key={cycle}+ role="radio"+ aria-checked={selectedCycle === cycle}+ type="button"+ onClick={() => setSelectedCycle(cycle)}+ className={cn(+ "rounded-full border-none px-4 py-1.5 text-xs font-medium transition-all",+ selectedCycle === cycle+ ? "bg-white text-zinc-900 shadow-sm"+ : "bg-transparent text-zinc-500 hover:text-zinc-700",+ )}+ >+ {cycle === "monthly" ? (+ "Monthly billing"+ ) : (+ <>+ Yearly billing{" "}+ <span className="ml-1.5 bg-gradient-to-r from-green-500 via-emerald-500 to-teal-500 bg-clip-text text-[11px] font-semibold text-transparent">+ Save 15%+ </span>+ </>+ )}+ </button>+ ))}+ </div>+ )}++ <div className="relative mt-2 w-full max-w-[75.625rem]">+ {isLoading ? (+ <div className="grid w-full grid-cols-1 gap-4 px-[1rem] md:grid-cols-3 md:px-0">+ <Skeleton className="h-[26rem] rounded-2xl" />+ <Skeleton className="h-[26rem] rounded-2xl" />+ <Skeleton className="h-[26rem] rounded-2xl" />+ </div>+ ) : plans.length === 0 ? (+ <p className="text-center text-sm text-zinc-500">+ Subscriptions are temporarily unavailable. Please try again+ shortly.+ </p>+ ) : (+ <div+ className={cn(+ "grid w-full gap-4 px-[1rem] md:px-0",+ plans.length === 1 && "grid-cols-1",+ plans.length === 2 && "grid-cols-1 md:grid-cols-2",+ plans.length >= 3 && "grid-cols-1 md:grid-cols-3",+ )}+ >+ {plans.map((plan) => (+ <PlanCard+ key={plan.key}+ plan={plan}+ country={country}+ isYearly={isYearly}+ onSelect={() => handleSelectPlan(plan.key)}+ loading={isPending && selectedTier === plan.key}+ disabled={isPending && selectedTier !== plan.key}+ />+ ))}+ </div>+ )}+ </div>+ </div></Dialog.Content>+ {pendingTier && pendingTierLabel ? (+ <SwitchTierDialog+ isOpen={pendingTier !== null}+ onOpenChange={(open) => {+ if (!open) cancelPendingTier();+ }}+ targetTierLabel={pendingTierLabel}+ title={`Switch to ${pendingTierLabel}?`}+ confirmLabel={`Switch to ${pendingTierLabel}`}+ body="Your current Stripe subscription will be modified — you may be charged or refunded the prorated difference. Continue?"+ isSaving={isPending}+ onConfirm={() => {+ void confirmPendingTier();+ }}+ />+ ) : null}</Dialog>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsxindex 153981ee50..4fd4199858 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx@@ -1,56 +1,437 @@-import { render } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";--// Mock SubscriptionTierSection — its full render exercises the credits-// query, LD flag, and Stripe wiring which are out of scope for PaywallModal-// itself. The modal's job is to wrap the section in a non-dismissable Dialog;-// that's what we verify here.-vi.mock(- "@/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection",- () => ({- SubscriptionTierSection: () => (- <div data-testid="tier-section">tier picker</div>- ),- }),-);--// Mock the Dialog so we can introspect its props without booting Radix portals-// under jsdom (which doesn't reliably render them).-let lastDialogProps: Record<string, unknown> | null = null;+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ render,+ screen,+ fireEvent,+ waitFor,+ cleanup,+} from "@/tests/integrations/test-utils";++const mockUseGetSubscriptionStatus = vi.fn();+const mockUseUpdateSubscriptionTier = vi.fn();+vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({+ useGetSubscriptionStatus: (opts: unknown) =>+ mockUseGetSubscriptionStatus(opts),+ useUpdateSubscriptionTier: () => mockUseUpdateSubscriptionTier(),+}));++const mockToast = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (args: unknown) => mockToast(args),+ useToast: () => ({ toast: mockToast }),+ useToastOnFail: () => mockToast,+}));++// Strip Radix portals — happy-dom doesn't render them. The mock keeps the+// Dialog tree visible while ignoring controlled/forceOpen props.+function MockDialog({ children }: { children: React.ReactNode }) {+ return <div role="dialog">{children}</div>;+}+function MockDialogContent({ children }: { children: React.ReactNode }) {+ return <div>{children}</div>;+}+function MockDialogFooter({ children }: { children: React.ReactNode }) {+ return <div>{children}</div>;+}+MockDialog.Content = MockDialogContent;+MockDialog.Footer = MockDialogFooter;vi.mock("@/components/molecules/Dialog/Dialog", () => ({- Dialog: Object.assign(- function MockDialog(props: Record<string, unknown>) {- lastDialogProps = props;- return (- <div data-testid="dialog">{props.children as React.ReactNode}</div>- );- },- {- Content: ({ children }: { children: React.ReactNode }) => (- <div data-testid="dialog-content">{children}</div>- ),- },- ),+ Dialog: MockDialog,}));import { PaywallModal } from "../PaywallModal";-describe("PaywallModal", () => {- it("renders SubscriptionTierSection inside a forceOpen, non-dismissable Dialog", () => {- const { getByTestId } = render(<PaywallModal />);- expect(getByTestId("dialog")).toBeDefined();- expect(getByTestId("dialog-content")).toBeDefined();- expect(getByTestId("tier-section")).toBeDefined();- expect(lastDialogProps?.forceOpen).toBe(true);- // controlled.set is a no-op (set: () => {}) so the modal can never be- // closed by the Dialog's own state machinery — only by subscription state- // changing in the consuming PaywallGate.+interface SubscriptionShape {+ tier: string;+ tier_costs: Record<string, number>;+ tier_costs_yearly?: Record<string, number>;+ monthly_cost?: number;+ proration_credit_cents?: number;+ has_active_stripe_subscription?: boolean;+}++function setupMocks({+ subscription,+ isLoading = false,+ mutateFn = vi.fn().mockResolvedValue({ status: 200, data: { url: "" } }),+ isPending = false,+}: {+ subscription: SubscriptionShape | null;+ isLoading?: boolean;+ mutateFn?: ReturnType<typeof vi.fn>;+ isPending?: boolean;+}) {+ mockUseGetSubscriptionStatus.mockReturnValue({+ data: subscription,+ isLoading,+ });+ mockUseUpdateSubscriptionTier.mockReturnValue({+ mutateAsync: mutateFn,+ isPending,+ });+ return { mutateFn };+}++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("PaywallModal — dynamic plan rendering", () => {+ it("renders one card per tier in tier_costs (PRO + MAX → 2 cards)", () => {+ setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ },+ });++ render(<PaywallModal />);++ expect(screen.getByText("Pro")).toBeDefined();+ expect(screen.getByText("Max")).toBeDefined();+ expect(screen.queryByText("Business")).toBeNull();+ });++ it("renders three cards when tier_costs includes BUSINESS", () => {+ setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000, BUSINESS: 100000 },+ tier_costs_yearly: {+ PRO: 51000,+ MAX: 326400,+ BUSINESS: 1020000,+ },+ },+ });++ render(<PaywallModal />);++ expect(screen.getByText("Pro")).toBeDefined();+ expect(screen.getByText("Max")).toBeDefined();+ // BUSINESS is rendered as "Team" — contact-sales tier label.+ expect(screen.getByText("Team")).toBeDefined();+ });++ it("hides cards for tiers absent from tier_costs (LD-hidden tier)", () => {+ setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000 },+ },+ });++ render(<PaywallModal />);++ expect(screen.getByText("Pro")).toBeDefined();+ expect(screen.queryByText("Max")).toBeNull();+ expect(screen.queryByText("Business")).toBeNull();+ });+});++describe("PaywallModal — Monthly/Yearly cycle toggle", () => {+ it("displays monthly prices by default", () => {+ setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ },+ });++ render(<PaywallModal />);++ // PRO monthly = 5000 cents = $50.00+ expect(screen.getByText("$50.00")).toBeDefined();+ expect(screen.getByText("$320.00")).toBeDefined();+ });++ it("toggling Yearly switches displayed prices to tier_costs_yearly", async () => {+ setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ },+ });++ render(<PaywallModal />);++ fireEvent.click(screen.getByRole("radio", { name: /yearly/i }));++ // PRO yearly = 51000 cents = $510.00; MAX yearly = 326400 cents = $3,264.00+ await waitFor(() => {+ expect(screen.getByText("$510.00")).toBeDefined();+ expect(screen.getByText("$3,264.00")).toBeDefined();+ });+ });+});++describe("PaywallModal — upgrade mutation", () => {+ const originalLocation = window.location;++ afterEach(() => {+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: originalLocation,+ });+ });++ function stubLocation() {+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: { origin: "https://app.test", href: "" },+ });+ }++ it("clicking Upgrade to Pro with monthly toggle fires {tier:PRO, billing_cycle:monthly}", async () => {+ stubLocation();+ const { mutateFn } = setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ },+ });++ render(<PaywallModal />);++ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));++ await waitFor(() => {+ expect(mutateFn).toHaveBeenCalledTimes(1);+ });+ const [args] = mutateFn.mock.calls[0];+ expect(args.data.tier).toBe("PRO");+ expect(args.data.billing_cycle).toBe("monthly");+ });++ it("clicking Upgrade to Pro with yearly toggle fires {tier:PRO, billing_cycle:yearly}", async () => {+ stubLocation();+ const { mutateFn } = setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ },+ });++ render(<PaywallModal />);++ fireEvent.click(screen.getByRole("radio", { name: /yearly/i }));+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));++ await waitFor(() => {+ expect(mutateFn).toHaveBeenCalledTimes(1);+ });+ const [args] = mutateFn.mock.calls[0];+ expect(args.data.tier).toBe("PRO");+ expect(args.data.billing_cycle).toBe("yearly");+ });++ it("redirects to Stripe when the response includes a checkout URL", async () => {+ stubLocation();+ const mutateFn = vi.fn().mockResolvedValue({+ status: 200,+ data: { url: "https://checkout.stripe.com/c/test" },+ });+ setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ },+ mutateFn,+ });++ render(<PaywallModal />);++ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));++ await waitFor(() => {+ expect(window.location.href).toBe("https://checkout.stripe.com/c/test");+ });+ });++ it("Team (BUSINESS) opens the contact-sales intake form instead of firing updateTier", async () => {+ stubLocation();+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);+ const { mutateFn } = setupMocks({+ subscription: {+ tier: "NO_TIER",+ // Including BUSINESS in tier_costs so the card renders; click should+ // still divert to the intake form rather than POSTing to /credits/subscription.+ tier_costs: { PRO: 5000, MAX: 32000, BUSINESS: 50000 },+ },+ });++ render(<PaywallModal />);++ // BUSINESS card renders the "Talk to sales" CTA per PLAN_METADATA.+ fireEvent.click(screen.getByRole("button", { name: /talk to sales/i }));++ expect(openSpy).toHaveBeenCalledWith(+ expect.stringContaining("tally.so"),+ "_blank",+ "noopener,noreferrer",+ );+ expect(mutateFn).not.toHaveBeenCalled();+ });++ it("422 from updateTier surfaces a toast and does not redirect", async () => {+ stubLocation();+ const mutateFn = vi+ .fn()+ .mockRejectedValue(new Error("Unprocessable Entity"));+ setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ },+ mutateFn,+ });++ render(<PaywallModal />);++ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));++ await waitFor(() => {+ expect(mockToast).toHaveBeenCalledTimes(1);+ });+ expect(window.location.href).toBe("");+ });+});++describe("PaywallModal — admin-overridden NO_TIER with active Stripe sub", () => {+ const originalLocation = window.location;++ afterEach(() => {+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: originalLocation,+ });+ });++ function stubLocation() {+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: { origin: "https://app.test", href: "" },+ });+ }++ it("staging gate: clicking Upgrade with active Stripe sub opens confirm dialog and skips mutation", () => {+ stubLocation();+ const { mutateFn } = setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ } as SubscriptionShape,+ });++ render(<PaywallModal />);+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));++ // Confirmation dialog text surfaces; mutation has NOT fired yet.expect(- typeof (lastDialogProps?.controlled as { set?: unknown } | undefined)- ?.set,- ).toBe("function");+ screen.getByText(+ /current Stripe subscription will be modified — you may be charged or refunded/i,+ ),+ ).toBeDefined();+ expect(mutateFn).not.toHaveBeenCalled();+ });++ it("confirming the dialog fires the upgrade mutation", async () => {+ stubLocation();+ const { mutateFn } = setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ has_active_stripe_subscription: true,+ } as SubscriptionShape,+ });++ render(<PaywallModal />);+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /switch to pro/i }));++ await waitFor(() => {+ expect(mutateFn).toHaveBeenCalledTimes(1);+ });+ const [args] = mutateFn.mock.calls[0];+ expect(args.data.tier).toBe("PRO");+ });++ it("cancelling the dialog leaves the user on the paywall and does not fire", () => {+ stubLocation();+ const { mutateFn } = setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ has_active_stripe_subscription: true,+ } as SubscriptionShape,+ });++ render(<PaywallModal />);+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));+ fireEvent.click(screen.getByRole("button", { name: /cancel/i }));++ expect(mutateFn).not.toHaveBeenCalled();+ });++ it("no active Stripe sub: clicking Upgrade fires the mutation directly (Checkout flow)", async () => {+ stubLocation();+ const { mutateFn } = setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: { PRO: 5000, MAX: 32000 },+ has_active_stripe_subscription: false,+ } as SubscriptionShape,+ });++ render(<PaywallModal />);+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));++ await waitFor(() => {+ expect(mutateFn).toHaveBeenCalledTimes(1);+ });+ });+});++describe("PaywallModal — empty / loading states", () => {+ it("renders the temporarily-unavailable fallback when tier_costs is empty", () => {+ setupMocks({+ subscription: {+ tier: "NO_TIER",+ tier_costs: {},+ },+ });++ render(<PaywallModal />);++ expect(+ screen.getByText(/Subscriptions are temporarily unavailable/i),+ ).toBeDefined();+ // No upgrade buttons, no cycle toggle, no plan cards.+ expect(screen.queryByRole("radio", { name: /monthly/i })).toBeNull();+ expect(screen.queryByRole("button", { name: /upgrade to/i })).toBeNull();+ });++ it("renders skeletons while subscription status is loading", () => {+ setupMocks({ subscription: null, isLoading: true });++ render(<PaywallModal />);++ // Skeleton has no a11y role; assert no cards rendered.+ expect(screen.queryByRole("button", { name: /upgrade to/i })).toBeNull();expect(- (lastDialogProps?.controlled as { isOpen?: boolean } | undefined)?.isOpen,- ).toBe(true);+ screen.queryByText(/Subscriptions are temporarily unavailable/i),+ ).toBeNull();});});diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.tsnew file mode 100644index 0000000000..d45b15e282--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts@@ -0,0 +1,160 @@+"use client";++import { useState } from "react";+import {+ useGetSubscriptionStatus,+ useUpdateSubscriptionTier,+} from "@/app/api/__generated__/endpoints/credits/credits";+import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";+import { toast } from "@/components/molecules/Toast/use-toast";+import { COUNTRIES } from "@/components/molecules/PlanCard/countries";+import {+ type BackendTierKey,+ PLAN_METADATA,+ type PlanDef,+ TEAM_INTAKE_FORM_URL,+} from "@/components/molecules/PlanCard/plans";++interface CheckoutResponse {+ url?: string;+}++const TIER_DISPLAY_ORDER: BackendTierKey[] = ["PRO", "MAX", "BUSINESS"];++const PLAN_LABEL: Record<string, string> = {+ PRO: "Pro",+ MAX: "Max",+ BUSINESS: "Team",+};++// Build a PlanDef per priceable tier exposed by /credits/subscription. Static+// metadata (features / cta / highlight) is layered on top of the API-driven+// monthly + yearly amounts, so a tier appears here iff LD has a Stripe price+// for it.+function deriveAvailablePlans(+ tierCosts: Record<string, number> | undefined,+ tierCostsYearly: Record<string, number> | undefined,+): PlanDef[] {+ if (!tierCosts) return [];+ return TIER_DISPLAY_ORDER.filter(+ (tier) => typeof tierCosts[tier] === "number",+ ).map((tier) => {+ const monthlyCents = tierCosts[tier] ?? 0;+ const yearlyCents = tierCostsYearly?.[tier];+ return {+ ...PLAN_METADATA[tier],+ usdMonthly: monthlyCents / 100,+ usdYearly: typeof yearlyCents === "number" ? yearlyCents / 100 : null,+ };+ });+}++export function usePaywallModal() {+ const { data: subscription, isLoading } = useGetSubscriptionStatus({+ query: { select: (res) => (res.status === 200 ? res.data : null) },+ });+ const { mutateAsync: updateTier, isPending } = useUpdateSubscriptionTier();+ const [selectedCycle, setSelectedCycle] = useState<"monthly" | "yearly">(+ "monthly",+ );+ const [selectedTier, setSelectedTier] = useState<string | null>(null);+ // When the user already has an active Stripe subscription (admin override+ // flipped DB tier to NO_TIER but Stripe sub is still live), modify-in-place+ // skips Stripe Checkout entirely — clicking Upgrade silently re-bills the+ // saved card and looks like a no-op. Stage the target tier here and surface+ // a confirmation dialog before firing the mutation.+ const [pendingTier, setPendingTier] = useState<string | null>(null);++ const country = COUNTRIES[0];+ const isYearly = selectedCycle === "yearly";++ const plans = deriveAvailablePlans(+ subscription?.tier_costs,+ subscription?.tier_costs_yearly,+ );++ const hasActiveStripeSubscription = Boolean(+ subscription?.has_active_stripe_subscription,+ );++ async function fireUpdate(tier: string) {+ setSelectedTier(tier);+ try {+ const baseUrl = `${window.location.origin}/profile/credits`;+ const result = await updateTier({+ data: {+ tier: tier as SubscriptionTierRequestTier,+ success_url: `${baseUrl}?subscription=success`,+ cancel_url: `${baseUrl}?subscription=cancelled`,+ billing_cycle: isYearly ? "yearly" : "monthly",+ },+ });+ const url = (result?.data as CheckoutResponse | undefined)?.url;+ if (url) {+ window.location.href = url;+ }+ } catch (error) {+ toast({+ title: "Couldn't start checkout",+ description:+ error instanceof Error+ ? error.message+ : "Stripe didn't accept the request. Please try again.",+ variant: "destructive",+ });+ } finally {+ setSelectedTier(null);+ }+ }++ async function handleSelectPlan(tier: string) {+ if (isPending) return;+ // Team (BUSINESS) is contact-sales, not a self-serve Stripe Checkout —+ // divert to the intake form like onboarding + Settings billing do.+ // Without this, the POST hits the backend with tier=BUSINESS which 422s+ // (no LD price) and surfaces a generic "couldn't start checkout" toast.+ if (tier === "BUSINESS") {+ window.open(TEAM_INTAKE_FORM_URL, "_blank", "noopener,noreferrer");+ return;+ }+ // Active Stripe sub → modify-in-place hits saved-card auto-charge; no+ // Stripe Checkout opens, so the click would otherwise be a silent+ // re-bill / refund. Stage the tier behind the confirmation dialog.+ if (hasActiveStripeSubscription) {+ setPendingTier(tier);+ return;+ }+ await fireUpdate(tier);+ }++ async function confirmPendingTier() {+ if (!pendingTier) return;+ const tier = pendingTier;+ await fireUpdate(tier);+ setPendingTier(null);+ }++ function cancelPendingTier() {+ setPendingTier(null);+ }++ const pendingTierLabel = pendingTier+ ? (PLAN_LABEL[pendingTier] ?? pendingTier)+ : null;++ return {+ isLoading,+ plans,+ country,+ isYearly,+ selectedCycle,+ setSelectedCycle,+ handleSelectPlan,+ isPending,+ selectedTier,+ pendingTier,+ pendingTierLabel,+ confirmPendingTier,+ cancelPendingTier,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsxindex 55ea9ae12b..43ec20b007 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx@@ -160,6 +160,575 @@ describe("YourPlanCard", () => {});});+describe("YourPlanCard cycle toggle", () => {+ it("renders Monthly selected when billing_cycle is monthly", async () => {+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 5000,+ billing_cycle: "monthly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ );++ render(<YourPlanCard />);++ const monthly = await screen.findByRole("radio", { name: /monthly/i });+ const yearly = screen.getByRole("radio", { name: /yearly/i });+ expect(monthly.getAttribute("aria-checked")).toBe("true");+ expect(yearly.getAttribute("aria-checked")).toBe("false");+ });++ it("renders Yearly selected when billing_cycle is yearly", async () => {+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 51000,+ billing_cycle: "yearly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ );++ render(<YourPlanCard />);++ const yearly = await screen.findByRole("radio", { name: /yearly/i });+ const monthly = screen.getByRole("radio", { name: /monthly/i });+ expect(yearly.getAttribute("aria-checked")).toBe("true");+ expect(monthly.getAttribute("aria-checked")).toBe("false");+ });++ it("opens the confirmation dialog with prorated copy when monthly Pro user clicks Yearly", async () => {+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 5000,+ billing_cycle: "monthly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ );++ render(<YourPlanCard />);++ const yearly = await screen.findByRole("radio", { name: /yearly/i });+ fireEvent.click(yearly);++ expect(+ await screen.findByText(/Switch billing to Yearly\?/i),+ ).toBeDefined();+ expect(+ screen.getByText(/charged the prorated difference immediately/i),+ ).toBeDefined();+ expect(screen.getByText(/\$510\.00/)).toBeDefined();+ expect(+ screen.getByRole("button", { name: /switch to yearly/i }),+ ).toBeDefined();+ });++ it("fires updateTier with billing_cycle on confirm", async () => {+ let capturedBody: { tier?: string; billing_cycle?: string } | null = null;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 5000,+ billing_cycle: "monthly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedBody = (await request.json()) as typeof capturedBody;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(await screen.findByRole("radio", { name: /yearly/i }));+ fireEvent.click(+ await screen.findByRole("button", { name: /switch to yearly/i }),+ );++ await waitFor(() => {+ expect(capturedBody).not.toBeNull();+ expect(capturedBody?.tier).toBe("PRO");+ expect(capturedBody?.billing_cycle).toBe("yearly");+ });+ });++ it("cancelling the dialog leaves no mutation fired", async () => {+ let mutationFired = false;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 5000,+ billing_cycle: "monthly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", () => {+ mutationFired = true;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(await screen.findByRole("radio", { name: /yearly/i }));+ fireEvent.click(await screen.findByRole("button", { name: /^cancel$/i }));++ await waitFor(() =>+ expect(+ screen.queryByRole("button", { name: /switch to yearly/i }),+ ).toBeNull(),+ );+ expect(mutationFired).toBe(false);+ });++ it("opens a confirmation dialog (no API call) when a paid user clicks Upgrade to Max", async () => {+ let mutationFired = false;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 5000,+ billing_cycle: "monthly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", () => {+ mutationFired = true;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(+ await screen.findByRole("button", { name: /upgrade to max/i }),+ );++ expect(await screen.findByText(/Upgrade to Max\?/i)).toBeDefined();+ expect(+ screen.getByText(+ /charged the prorated difference immediately for the rest of your monthly period/i,+ ),+ ).toBeDefined();+ expect(mutationFired).toBe(false);+ });++ it("fires updateTier with the server billing cycle when the upgrade dialog is confirmed", async () => {+ let capturedBody: { tier?: string; billing_cycle?: string } | null = null;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 51000,+ billing_cycle: "yearly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedBody = (await request.json()) as typeof capturedBody;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(+ await screen.findByRole("button", { name: /upgrade to max/i }),+ );++ const confirmInDialog = await screen.findAllByRole("button", {+ name: /upgrade to max/i,+ });+ // Two buttons share the label: the card's trigger + the dialog's confirm.+ // The confirm is the second one in DOM order.+ fireEvent.click(confirmInDialog[confirmInDialog.length - 1]);++ await waitFor(() => {+ expect(capturedBody).not.toBeNull();+ expect(capturedBody?.tier).toBe("MAX");+ expect(capturedBody?.billing_cycle).toBe("yearly");+ });+ });++ it("cancelling the upgrade dialog leaves no mutation fired", async () => {+ let mutationFired = false;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 5000,+ billing_cycle: "monthly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", () => {+ mutationFired = true;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(+ await screen.findByRole("button", { name: /upgrade to max/i }),+ );+ expect(await screen.findByText(/Upgrade to Max\?/i)).toBeDefined();+ fireEvent.click(await screen.findByRole("button", { name: /^cancel$/i }));++ await waitFor(() =>+ expect(screen.queryByText(/Upgrade to Max\?/i)).toBeNull(),+ );+ expect(mutationFired).toBe(false);+ });++ it("clicking Downgrade to Pro opens a confirmation dialog with end-of-period copy", async () => {+ let mutationFired = false;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "MAX",+ monthly_cost: 32000,+ billing_cycle: "monthly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ current_period_end: 1900000000,+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", () => {+ mutationFired = true;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(+ await screen.findByRole("button", { name: /downgrade to pro/i }),+ );++ expect(await screen.findByText(/Downgrade to Pro\?/i)).toBeDefined();+ expect(+ screen.getByText(/until .* then switch to Pro\. No charge today\./i),+ ).toBeDefined();+ expect(mutationFired).toBe(false);+ });++ it("confirming the downgrade dialog fires updateTier with prevTier + serverCycle", async () => {+ let capturedBody: { tier?: string; billing_cycle?: string } | null = null;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "MAX",+ monthly_cost: 326400,+ billing_cycle: "yearly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedBody = (await request.json()) as typeof capturedBody;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(+ await screen.findByRole("button", { name: /downgrade to pro/i }),+ );++ const confirmInDialog = await screen.findAllByRole("button", {+ name: /downgrade to pro/i,+ });+ // Two buttons share the label: the card's trigger + the dialog's confirm.+ fireEvent.click(confirmInDialog[confirmInDialog.length - 1]);++ await waitFor(() => {+ expect(capturedBody).not.toBeNull();+ expect(capturedBody?.tier).toBe("PRO");+ expect(capturedBody?.billing_cycle).toBe("yearly");+ });+ });++ it("cancelling the downgrade dialog leaves no mutation fired", async () => {+ let mutationFired = false;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "MAX",+ monthly_cost: 32000,+ billing_cycle: "monthly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", () => {+ mutationFired = true;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(+ await screen.findByRole("button", { name: /downgrade to pro/i }),+ );+ expect(await screen.findByText(/Downgrade to Pro\?/i)).toBeDefined();+ fireEvent.click(await screen.findByRole("button", { name: /^cancel$/i }));++ await waitFor(() =>+ expect(screen.queryByText(/Downgrade to Pro\?/i)).toBeNull(),+ );+ expect(mutationFired).toBe(false);+ });++ it("NO_TIER user clicking Get Pro skips the confirmation dialog (Stripe Checkout flow)", async () => {+ let mutationFired = false;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "NO_TIER",+ monthly_cost: 0,+ has_active_stripe_subscription: false,+ status: "inactive",+ }),+ jsonHandler("get", "/api/credits/manage", { url: null }),+ http.post("*/api/credits/subscription", () => {+ mutationFired = true;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(await screen.findByRole("button", { name: /get pro/i }));++ // No SwitchTierDialog rendered for free→paid (Checkout success_url path).+ await waitFor(() => expect(mutationFired).toBe(true));+ expect(screen.queryByText(/Upgrade to Pro\?/i)).toBeNull();+ });++ it("hides the cycle toggle entirely for ENTERPRISE tier", async () => {+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "ENTERPRISE",+ monthly_cost: 0,+ billing_cycle: "monthly",+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", { url: null }),+ );++ render(<YourPlanCard />);++ await waitFor(() => expect(screen.queryAllByRole("radio").length).toBe(0));+ });++ it("hides the cycle toggle entirely for BASIC tier", async () => {+ // BASIC is a reserved internal slot (no Stripe sub, no upgrade target);+ // showing a cycle toggle would imply user-manageable billing.+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "BASIC",+ monthly_cost: 0,+ billing_cycle: "monthly",+ has_active_stripe_subscription: false,+ status: "inactive",+ }),+ jsonHandler("get", "/api/credits/manage", { url: null }),+ );++ render(<YourPlanCard />);++ await waitFor(() => expect(screen.queryAllByRole("radio").length).toBe(0));+ });++ it("hides the cycle toggle entirely for NO_TIER users (no active sub)", async () => {+ // NO_TIER means no active subscription — the user has nothing to switch.+ // The toggle would be dead UI implying functionality that doesn't apply.+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "NO_TIER",+ monthly_cost: 0,+ has_active_stripe_subscription: false,+ status: "inactive",+ }),+ jsonHandler("get", "/api/credits/manage", { url: null }),+ );++ render(<YourPlanCard />);++ await waitFor(() => expect(screen.queryAllByRole("radio").length).toBe(0));+ });++ it("downgrade preserves yearly cycle (forwards billing_cycle in mutation)", async () => {+ let capturedBody: { tier?: string; billing_cycle?: string } | null = null;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "MAX",+ monthly_cost: 326400,+ billing_cycle: "yearly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedBody = (await request.json()) as typeof capturedBody;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(+ await screen.findByRole("button", { name: /downgrade to pro/i }),+ );+ // Downgrade now goes through a confirm dialog (symmetric with upgrade).+ // Two buttons share the label: the card's trigger + the dialog's confirm —+ // confirm is the second one in DOM order.+ const confirmInDialog = await screen.findAllByRole("button", {+ name: /downgrade to pro/i,+ });+ fireEvent.click(confirmInDialog[confirmInDialog.length - 1]);++ await waitFor(() => {+ expect(capturedBody).not.toBeNull();+ expect(capturedBody?.tier).toBe("PRO");+ // Without forwarding the current cycle the backend defaults to monthly,+ // silently flipping the yearly subscriber at period end.+ expect(capturedBody?.billing_cycle).toBe("yearly");+ });+ });++ it("resume preserves yearly cycle (forwards billing_cycle in mutation)", async () => {+ let capturedBody: { tier?: string; billing_cycle?: string } | null = null;+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 51000,+ billing_cycle: "yearly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ pending_tier: "NO_TIER",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedBody = (await request.json()) as typeof capturedBody;+ return HttpResponse.json({ url: "" });+ }),+ );++ render(<YourPlanCard />);++ fireEvent.click(+ await screen.findByRole("button", { name: /resume subscription/i }),+ );++ await waitFor(() => {+ expect(capturedBody).not.toBeNull();+ expect(capturedBody?.tier).toBe("PRO");+ // Same-tier release path also defaults to monthly when billing_cycle is+ // omitted — gates as a cycle-switch and silently flips to monthly.+ expect(capturedBody?.billing_cycle).toBe("yearly");+ });+ });++ it("shows 'Cycle switch scheduled' badge + cycle-only secondary line when same-tier yearly→monthly is queued", async () => {+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier: "PRO",+ monthly_cost: 51000,+ billing_cycle: "yearly",+ tier_costs: { PRO: 5000, MAX: 32000 },+ tier_costs_yearly: { PRO: 51000, MAX: 326400 },+ has_active_stripe_subscription: true,+ status: "active",+ pending_tier: "PRO",+ pending_billing_cycle: "monthly",+ pending_tier_effective_at: "2026-12-15T00:00:00Z",+ }),+ jsonHandler("get", "/api/credits/manage", {+ url: "https://billing.stripe.com/p/test",+ }),+ );++ render(<YourPlanCard />);++ expect(await screen.findByText("Cycle switch scheduled")).toBeDefined();+ // Active yearly price stays on the primary line; secondary line describes+ // the queued switch with no charge today.+ expect(screen.getByText(/\$510\.00 \/ year/)).toBeDefined();+ expect(+ screen.getByText(/Switching to monthly Pro on .* · No charge today/i),+ ).toBeDefined();+ expect(+ screen.getByRole("button", { name: /cancel cycle switch/i }),+ ).toBeDefined();+ // Tier-downgrade button is suppressed while a cycle switch is pending —+ // the user needs to cancel/release the schedule first.+ expect(screen.queryByRole("button", { name: /^downgrade to/i })).toBeNull();+ });+});+describe("PaymentMethodCard", () => {it("disables 'Open portal' until the portal URL resolves", async () => {server.use(jsonHandler("get", "/api/credits/manage", { url: null }));diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsxindex 4b8fc19d69..bcf555aca6 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx@@ -510,7 +510,7 @@ describe("useYourPlanCard", () => {expect(result.current.plan?.nextTierIsTeamLink).toBe(true);});- it("onDowngrade calls updateTier with the previous tier (MAX → PRO)", async () => {+ it("onDowngrade stages the confirm dialog and onConfirmTierDowngrade fires updateTier (MAX → PRO)", async () => {let capturedTier: string | null = null;server.use(jsonHandler("get", "/api/credits/subscription", {@@ -533,10 +533,21 @@ describe("useYourPlanCard", () => {await waitFor(() => expect(result.current.isLoading).toBe(false));+ // Clicking Downgrade stages the dialog state — no mutation yet.await act(async () => {result.current.onDowngrade();});+ await waitFor(() =>+ expect(result.current.pendingTierDowngrade).toBe("PRO"),+ );+ expect(capturedTier).toBeNull();++ // Confirming the dialog fires the mutation.+ await act(async () => {+ result.current.onConfirmTierDowngrade();+ });+await waitFor(() => expect(capturedTier).toBe("PRO"));});@@ -647,9 +658,17 @@ describe("useYourPlanCard", () => {await waitFor(() => expect(result.current.isLoading).toBe(false));expect(result.current.canUpgrade).toBe(true);+ // Paid → paid upgrade now stages a confirmation dialog before firing the+ // mutation (silent prorated charge guard). onUpgrade only sets pending+ // state; onConfirmTierUpgrade fires the actual updateTier call.await act(async () => {result.current.onUpgrade();});+ await waitFor(() => expect(result.current.pendingTierUpgrade).toBe("MAX"));++ await act(async () => {+ await result.current.onConfirmTierUpgrade();+ });await waitFor(() => expect(capturedTier).toBe("MAX"));});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/CycleToggle.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/CycleToggle.tsxnew file mode 100644index 0000000000..dfcb2810e7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/CycleToggle.tsx@@ -0,0 +1,53 @@+"use client";++import { cn } from "@/lib/utils";++interface Props {+ value: "monthly" | "yearly";+ onChange: (cycle: "monthly" | "yearly") => void;+ disabled?: boolean;+}++const CYCLES = ["monthly", "yearly"] as const;++export function CycleToggle({ value, onChange, disabled }: Props) {+ return (+ <div+ role="radiogroup"+ aria-label="Billing cycle"+ className="inline-flex rounded-full border border-[#d8d8d8] bg-zinc-100 p-[3px]"+ >+ {CYCLES.map((cycle) => {+ const selected = value === cycle;+ return (+ <button+ key={cycle}+ type="button"+ role="radio"+ aria-checked={selected}+ disabled={disabled}+ onClick={() => onChange(cycle)}+ className={cn(+ "rounded-full border-none px-3 py-1 text-xs font-medium transition-all",+ selected+ ? "bg-white text-zinc-900 shadow-sm"+ : "bg-transparent text-zinc-500 hover:text-zinc-700",+ disabled && "cursor-not-allowed opacity-60",+ )}+ >+ {cycle === "monthly" ? (+ "Monthly"+ ) : (+ <>+ Yearly{" "}+ <span className="ml-1 bg-gradient-to-r from-green-500 via-emerald-500 to-teal-500 bg-clip-text text-[11px] font-semibold text-transparent">+ Save 15%+ </span>+ </>+ )}+ </button>+ );+ })}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchCycleDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchCycleDialog.tsxnew file mode 100644index 0000000000..4c9d260ff9--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchCycleDialog.tsx@@ -0,0 +1,63 @@+"use client";++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;+ onOpenChange: (open: boolean) => void;+ targetCycle: "monthly" | "yearly";+ body: string;+ isSaving: boolean;+ onConfirm: () => void;+}++export function SwitchCycleDialog({+ isOpen,+ onOpenChange,+ targetCycle,+ body,+ isSaving,+ onConfirm,+}: Props) {+ const targetLabel = targetCycle === "yearly" ? "Yearly" : "Monthly";++ return (+ <Dialog+ title={`Switch billing to ${targetLabel}?`}+ styling={{ maxWidth: "440px" }}+ controlled={{ isOpen, set: onOpenChange }}+ >+ <Dialog.Content>+ <div className="flex flex-col gap-4">+ <Text variant="body" as="span" className="text-zinc-700">+ {body}+ </Text>+ </div>++ <Dialog.Footer>+ <Button+ type="button"+ variant="ghost"+ size="small"+ onClick={() => onOpenChange(false)}+ disabled={isSaving}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="primary"+ size="small"+ onClick={onConfirm}+ disabled={isSaving}+ loading={isSaving}+ >+ Switch to {targetLabel}+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog.tsxnew file mode 100644index 0000000000..25bc765898--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/SwitchTierDialog.tsx@@ -0,0 +1,65 @@+"use client";++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;+ onOpenChange: (open: boolean) => void;+ targetTierLabel: string;+ body: string;+ isSaving: boolean;+ onConfirm: () => void;+ title?: string;+ confirmLabel?: string;+}++export function SwitchTierDialog({+ isOpen,+ onOpenChange,+ targetTierLabel,+ body,+ isSaving,+ onConfirm,+ title,+ confirmLabel,+}: Props) {+ return (+ <Dialog+ title={title ?? `Upgrade to ${targetTierLabel}?`}+ styling={{ maxWidth: "440px" }}+ controlled={{ isOpen, set: onOpenChange }}+ >+ <Dialog.Content>+ <div className="flex flex-col gap-4">+ <Text variant="body" as="span" className="text-zinc-700">+ {body}+ </Text>+ </div>++ <Dialog.Footer>+ <Button+ type="button"+ variant="ghost"+ size="small"+ onClick={() => onOpenChange(false)}+ disabled={isSaving}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="primary"+ size="small"+ onClick={onConfirm}+ disabled={isSaving}+ loading={isSaving}+ >+ {confirmLabel ?? `Upgrade to ${targetTierLabel}`}+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsxindex 2679af9479..e9093c556a 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx@@ -13,6 +13,9 @@ import {formatShortDate,getSectionMotionProps,} from "../../../helpers";+import { CycleToggle } from "./CycleToggle";+import { SwitchCycleDialog } from "./SwitchCycleDialog";+import { SwitchTierDialog } from "./SwitchTierDialog";import { useYourPlanCard } from "./useYourPlanCard";interface Props {@@ -29,6 +32,23 @@ export function YourPlanCard({ index = 0 }: Props) {canUpgrade,canDowngrade,canResume,+ selectedCycle,+ pendingCycle,+ pendingTierUpgrade,+ pendingTierUpgradeLabel,+ pendingTierDowngrade,+ pendingTierDowngradeLabel,+ isCycleToggleVisible,+ cycleDialogBody,+ tierUpgradeDialogBody,+ tierDowngradeDialogBody,+ onCycleChange,+ onConfirmCycleSwitch,+ onCancelCycleSwitch,+ onConfirmTierUpgrade,+ onCancelTierUpgrade,+ onConfirmTierDowngrade,+ onCancelTierDowngrade,onUpgrade,onDowngrade,onResume,@@ -54,8 +74,8 @@ export function YourPlanCard({ index = 0 }: Props) {</div><div className="flex flex-wrap items-center justify-between gap-4 rounded-[18px] border border-zinc-200 bg-white p-5 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">- <div className="flex min-w-0 flex-col gap-1">- <div className="flex items-center gap-2">+ <div className="flex min-w-0 flex-col gap-2">+ <div className="flex flex-wrap items-center gap-2"><Text variant="large-medium" as="span" className="text-textBlack">{plan.label}</Text>@@ -63,7 +83,9 @@ export function YourPlanCard({ index = 0 }: Props) {variant="success"size="small"className={- plan.isPendingCancel || plan.isPendingDowngrade+ plan.isPendingCancel ||+ plan.isPendingDowngrade ||+ plan.isPendingCycleSwitch? "bg-amber-100 text-amber-800": "bg-violet-100 text-violet-800"}@@ -74,25 +96,46 @@ export function YourPlanCard({ index = 0 }: Props) {? "Cancellation scheduled": plan.isPendingDowngrade? "Downgrade scheduled"- : "Active"}+ : plan.isPendingCycleSwitch+ ? "Cycle switch scheduled"+ : "Active"}</Badge>+ {isCycleToggleVisible ? (+ <CycleToggle+ value={selectedCycle}+ onChange={onCycleChange}+ disabled={isUpdatingTier}+ />+ ) : null}</div>{plan.isPaidPlan ? (<Text variant="body" as="span" className="text-zinc-700">- {formatCents(plan.monthlyCostCents)} / month+ {formatCents(plan.monthlyCostCents)}+ {plan.billingCycle === "yearly" ? " / year" : " / month"}{plan.isPendingCancel && plan.pendingEffectiveAt? ` · Ends on ${formatShortDate(plan.pendingEffectiveAt)}`: plan.isPendingDowngrade && plan.pendingEffectiveAt? ` · Switches to ${plan.pendingTierLabel} on ${formatShortDate(plan.pendingEffectiveAt)}`- : plan.currentPeriodEnd- ? ` · Renews on ${formatShortDate(plan.currentPeriodEnd * 1000)}`- : null}+ : plan.isPendingCycleSwitch && plan.pendingEffectiveAt+ ? ` · Active until ${formatShortDate(plan.pendingEffectiveAt)}`+ : plan.currentPeriodEnd+ ? ` · Renews on ${formatShortDate(plan.currentPeriodEnd * 1000)}`+ : null}</Text>) : (<Text variant="body" as="span" className="text-zinc-700">Pick a plan to continue using AutoGPT.</Text>)}+ {plan.isPaidPlan &&+ plan.isPendingCycleSwitch &&+ plan.pendingEffectiveAt &&+ plan.pendingCycle ? (+ <Text variant="small" as="span" className="text-zinc-500">+ Switching to {plan.pendingCycle} {plan.label} on{" "}+ {formatShortDate(plan.pendingEffectiveAt)} · No charge today+ </Text>+ ) : null}</div><div className="ml-auto flex flex-wrap items-center gap-2">@@ -106,7 +149,9 @@ export function YourPlanCard({ index = 0 }: Props) {>{plan.isPendingCancel? "Resume subscription"- : "Cancel downgrade"}+ : plan.isPendingCycleSwitch+ ? "Cancel cycle switch"+ : "Cancel downgrade"}</Button>) : null}{canDowngrade && plan.previousTierLabel ? (@@ -152,6 +197,47 @@ export function YourPlanCard({ index = 0 }: Props) {) : null}</div></div>++ {pendingCycle ? (+ <SwitchCycleDialog+ isOpen={pendingCycle !== null}+ onOpenChange={(open) => {+ if (!open) onCancelCycleSwitch();+ }}+ targetCycle={pendingCycle}+ body={cycleDialogBody}+ isSaving={isUpdatingTier}+ onConfirm={onConfirmCycleSwitch}+ />+ ) : null}++ {pendingTierUpgrade && pendingTierUpgradeLabel ? (+ <SwitchTierDialog+ isOpen={pendingTierUpgrade !== null}+ onOpenChange={(open) => {+ if (!open) onCancelTierUpgrade();+ }}+ targetTierLabel={pendingTierUpgradeLabel}+ body={tierUpgradeDialogBody}+ isSaving={isUpdatingTier}+ onConfirm={onConfirmTierUpgrade}+ />+ ) : null}++ {pendingTierDowngrade && pendingTierDowngradeLabel ? (+ <SwitchTierDialog+ isOpen={pendingTierDowngrade !== null}+ onOpenChange={(open) => {+ if (!open) onCancelTierDowngrade();+ }}+ targetTierLabel={pendingTierDowngradeLabel}+ title={`Downgrade to ${pendingTierDowngradeLabel}?`}+ confirmLabel={`Downgrade to ${pendingTierDowngradeLabel}`}+ body={tierDowngradeDialogBody}+ isSaving={isUpdatingTier}+ onConfirm={onConfirmTierDowngrade}+ />+ ) : null}</motion.section>);}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 89d4e66d7e..e3be4d7876 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@@ -1,5 +1,7 @@"use client";+import { useEffect, useState } from "react";+import {useGetSubscriptionStatus,useGetV1ManagePaymentMethods,@@ -7,10 +9,12 @@ import {} from "@/app/api/__generated__/endpoints/credits/credits";import type { GetV1ManagePaymentMethods200 } from "@/app/api/__generated__/models/getV1ManagePaymentMethods200";import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";+import type { SubscriptionTierRequestBillingCycle } from "@/app/api/__generated__/models/subscriptionTierRequestBillingCycle";import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { toast } from "@/components/molecules/Toast/use-toast";-import { formatShortDate } from "../../../helpers";+import { formatCents, formatShortDate } from "../../../helpers";const PLAN_LABEL: Record<string, string> = {NO_TIER: "No active subscription",@@ -71,17 +75,62 @@ export function useYourPlanCard() {const effectiveTier = subscription.data?.tier ?? null;const isPaid = effectiveTier !== null && effectiveTier !== "NO_TIER";+ const serverCycle: SubscriptionTierRequestBillingCycle =+ subscription.data?.billing_cycle === "yearly" ? "yearly" : "monthly";+ const [selectedCycle, setSelectedCycle] =+ useState<SubscriptionTierRequestBillingCycle>(serverCycle);+ const [pendingCycle, setPendingCycle] =+ useState<SubscriptionTierRequestBillingCycle | null>(null);+ // Tier upgrades on a paid plan run through always_invoice immediate billing+ // — without a confirmation step the user is silently charged a large+ // prorated amount on a single click. Stage the target tier here and only+ // fire the mutation after the SwitchTierDialog confirms.+ const [pendingTierUpgrade, setPendingTierUpgrade] =+ useState<SubscriptionTierRequestTier | null>(null);+ // Downgrade is end-of-period (no charge today) so the risk is lower than+ // upgrade, but we still gate behind a confirm dialog so the user gets+ // explicit feedback that the action took effect.+ const [pendingTierDowngrade, setPendingTierDowngrade] =+ useState<SubscriptionTierRequestTier | null>(null);++ // Re-sync local toggle when the server response updates (e.g. after refetch+ // post-mutation). Avoids stale "yearly" pill after a successful switch.+ useEffect(() => {+ setSelectedCycle(serverCycle);+ }, [serverCycle]);+const nextTierKey = effectiveTier ? getNextTier(effectiveTier) : null;const previousTierKey = effectiveTier ? getPreviousTier(effectiveTier) : null;const pendingTier = subscription.data?.pending_tier ?? null;const pendingEffectiveAt =subscription.data?.pending_tier_effective_at ?? null;+ const pendingBillingCycle = subscription.data?.pending_billing_cycle ?? null;// Cancellation = pending change to the "no active subscription" state.const isPendingCancel = pendingTier === "NO_TIER";- // Paid→paid downgrade scheduled in Stripe (e.g. MAX → PRO at period end).- // Initiated from the Stripe billing portal — there's no in-app trigger.- const isPendingDowngrade = pendingTier !== null && pendingTier !== "NO_TIER";+ // Same-tier yearly→monthly schedule: pending_tier matches current tier but+ // pending_billing_cycle differs from serverCycle. Treat as a cycle-only+ // switch so the badge + copy describe the change accurately rather than+ // claiming a confusing "downgrade to <same tier>".+ const isPendingCycleSwitch =+ pendingTier !== null &&+ pendingTier !== "NO_TIER" &&+ pendingTier === effectiveTier &&+ pendingBillingCycle !== null &&+ pendingBillingCycle !== serverCycle;+ // Paid→paid tier downgrade scheduled in Stripe (e.g. MAX → PRO at period+ // end). The in-app trigger lives on the Downgrade button below; the Stripe+ // billing portal can also originate one.+ const isPendingDowngrade =+ pendingTier !== null &&+ pendingTier !== "NO_TIER" &&+ pendingTier !== effectiveTier;++ const tierCostsYearly = subscription.data?.tier_costs_yearly ?? {};+ const tierCosts = subscription.data?.tier_costs ?? {};+ const currentTierKey = effectiveTier ?? "NO_TIER";+ const currentYearlyCents = tierCostsYearly[currentTierKey];+ const currentMonthlyCents = tierCosts[currentTierKey];const plan = subscription.data? {@@ -109,12 +158,27 @@ export function useYourPlanCard() {? (PLAN_LABEL[pendingTier] ?? pendingTier): null,pendingEffectiveAt,+ pendingCycle: pendingBillingCycle,isPendingCancel,isPendingDowngrade,+ isPendingCycleSwitch,+ billingCycle: serverCycle,}: undefined;- async function changeTier(tier: SubscriptionTierRequestTier) {+ // ENTERPRISE seats are admin-managed; BASIC is a reserved internal slot;+ // NO_TIER means no active subscription. None of those have a+ // user-manageable cycle to switch — the toggle would be dead UI.+ const isCycleToggleVisible =+ effectiveTier !== null &&+ effectiveTier !== "ENTERPRISE" &&+ effectiveTier !== "BASIC" &&+ effectiveTier !== "NO_TIER";++ async function changeTier(+ tier: SubscriptionTierRequestTier,+ billingCycle?: SubscriptionTierRequestBillingCycle,+ ) {const successUrl = `${window.location.origin}${window.location.pathname}?subscription=success`;const cancelUrl = `${window.location.origin}${window.location.pathname}?subscription=cancelled`;try {@@ -123,6 +187,7 @@ export function useYourPlanCard() {tier,success_url: successUrl,cancel_url: cancelUrl,+ ...(billingCycle ? { billing_cycle: billingCycle } : {}),},});const url = (result?.data as { url?: string } | undefined)?.url;@@ -135,6 +200,23 @@ export function useYourPlanCard() {await subscription.refetch();return true;} catch (error) {+ // 422 fail-closed on a YEARLY request = LD missing the *_YEARLY price for+ // this tier. Match billingCycle === "yearly" specifically — a 422 on a+ // monthly request is a different failure (e.g. tier unconfigured) and+ // should surface the generic "Couldn't update your plan" copy below+ // instead of misleading the user about yearly availability.+ if (+ error instanceof ApiError &&+ error.status === 422 &&+ billingCycle === "yearly"+ ) {+ toast({+ title: "Yearly billing is not yet available for your plan.",+ description: "Please contact support.",+ variant: "destructive",+ });+ return false;+ }toast({title: "Couldn't update your plan",description:@@ -147,13 +229,19 @@ export function useYourPlanCard() {}}- async function downgradeSubscription() {+ async function downgradeSubscription(+ targetTier: SubscriptionTierRequestTier,+ ) {// End-of-period downgrade: backend's modify_stripe_subscription_for_tier// schedules a phase change at current_period_end. No proration today —// user keeps higher tier until period end, then drops to lower price.- if (!plan?.isPaidPlan || !plan?.previousTier) return;- const targetLabel = plan.previousTierLabel ?? plan.previousTier;- const ok = await changeTier(plan.previousTier);+ if (!plan?.isPaidPlan) return;+ const targetLabel = PLAN_LABEL[targetTier] ?? targetTier;+ // Preserve the user's current cycle on downgrade — without forwarding+ // serverCycle, the backend would default the missing billing_cycle to+ // "monthly" and silently flip a yearly subscriber to monthly at period+ // end (Sentry caught this; the same-tier release path also bites).+ const ok = await changeTier(targetTier, serverCycle);if (!ok) return;const periodEnd = plan.currentPeriodEnd? formatShortDate(plan.currentPeriodEnd * 1000)@@ -167,26 +255,164 @@ export function useYourPlanCard() {}async function resumeSubscription() {- // POSTing the current tier back to the backend releases any pending- // schedule — both cancel_at_period_end (NO_TIER pending) and paid→paid- // downgrade phases. See release_pending_subscription_schedule + the- // same-tier branch of update_subscription_tier.+ // POSTing the current tier+cycle back to the backend releases any pending+ // schedule — cancel_at_period_end (NO_TIER pending), paid→paid downgrade,+ // and same-tier yearly→monthly cycle switch all share the release path.+ // See release_pending_subscription_schedule + the same-tier branch of+ // update_subscription_tier.if (!plan?.isPaidPlan ||- (!plan?.isPendingCancel && !plan?.isPendingDowngrade)+ (!plan?.isPendingCancel &&+ !plan?.isPendingDowngrade &&+ !plan?.isPendingCycleSwitch)) {return;}- const ok = await changeTier(plan.tierKey as SubscriptionTierRequestTier);+ // Same-tier release also gates on cycle: omitting billing_cycle defaults+ // the backend to "monthly", which on a yearly sub is treated as a+ // cycle-switch instead of a release-pending — silent flip to monthly.+ const ok = await changeTier(+ plan.tierKey as SubscriptionTierRequestTier,+ serverCycle,+ );if (!ok) return;toast({title: plan.isPendingCancel? "Subscription resumed"- : "Downgrade cancelled",+ : plan.isPendingCycleSwitch+ ? "Cycle switch cancelled"+ : "Downgrade cancelled",description: `Your ${plan.label} plan will continue to renew as normal.`,});}+ function onCycleChange(nextCycle: SubscriptionTierRequestBillingCycle) {+ if (nextCycle === selectedCycle) return;+ if (!plan?.isPaidPlan) {+ // NO_TIER — the upgrade flow forwards `selectedCycle` to changeTier.+ setSelectedCycle(nextCycle);+ return;+ }+ if (nextCycle === serverCycle) {+ // User toggled back to their current server cycle while a switch+ // dialog was open elsewhere — just clear the staged change.+ setSelectedCycle(nextCycle);+ setPendingCycle(null);+ return;+ }+ setPendingCycle(nextCycle);+ }++ async function confirmCycleSwitch() {+ if (!pendingCycle || !plan?.tierKey) return;+ const ok = await changeTier(+ plan.tierKey as SubscriptionTierRequestTier,+ pendingCycle,+ );+ setPendingCycle(null);+ if (!ok) return;+ setSelectedCycle(pendingCycle);+ toast({+ title:+ pendingCycle === "yearly"+ ? "Switched to yearly billing"+ : "Switching to monthly at period end",+ description:+ pendingCycle === "yearly"+ ? "Stripe will charge the prorated difference today."+ : "Your plan will switch to monthly at the end of the current period.",+ });+ }++ function cancelCycleSwitch() {+ setPendingCycle(null);+ }++ function getDialogBody(): string {+ if (!pendingCycle) return "";+ if (pendingCycle === "yearly") {+ const yearly =+ currentYearlyCents !== undefined ? formatCents(currentYearlyCents) : "";+ return [+ "You'll be charged the prorated difference immediately.",+ yearly+ ? `After this period, your plan renews yearly at ${yearly}.`+ : "After this period, your plan renews on the new yearly cadence.",+ ].join(" ");+ }+ const monthly =+ currentMonthlyCents !== undefined ? formatCents(currentMonthlyCents) : "";+ return [+ "Your plan will switch to monthly billing at the end of your current yearly period; no charge today.",+ monthly ? `New monthly price: ${monthly}.` : "",+ ]+ .filter(Boolean)+ .join(" ");+ }++ function getTierUpgradeDialogBody(): string {+ if (!pendingTierUpgrade) return "";+ const targetCents =+ serverCycle === "yearly"+ ? tierCostsYearly[pendingTierUpgrade]+ : tierCosts[pendingTierUpgrade];+ const newPrice =+ typeof targetCents === "number" ? formatCents(targetCents) : "";+ const cycleNoun = serverCycle === "yearly" ? "yearly" : "monthly";+ const cycleUnit = serverCycle === "yearly" ? "year" : "month";+ const renewLine = newPrice+ ? `After this period, your plan renews at ${newPrice} per ${cycleUnit}.`+ : "";+ return [+ `You'll be charged the prorated difference immediately for the rest of your ${cycleNoun} period.`,+ renewLine,+ ]+ .filter(Boolean)+ .join(" ");+ }++ async function confirmTierUpgrade() {+ if (!pendingTierUpgrade) return;+ const target = pendingTierUpgrade;+ const ok = await changeTier(target, serverCycle);+ setPendingTierUpgrade(null);+ if (!ok) return;+ }++ function cancelTierUpgrade() {+ setPendingTierUpgrade(null);+ }++ function getTierDowngradeDialogBody(): string {+ if (!pendingTierDowngrade || !plan) return "";+ const targetLabel =+ PLAN_LABEL[pendingTierDowngrade] ?? pendingTierDowngrade;+ const cycleNoun = serverCycle === "yearly" ? "yearly" : "monthly";+ const periodEnd = plan.currentPeriodEnd+ ? formatShortDate(plan.currentPeriodEnd * 1000)+ : null;+ if (periodEnd) {+ return `You'll keep ${plan.label} (${cycleNoun}) until ${periodEnd}, then switch to ${targetLabel}. No charge today.`;+ }+ return `Your plan will switch to ${targetLabel} at the close of the current billing period. No charge today.`;+ }++ async function confirmTierDowngrade() {+ // Capture pendingTierDowngrade locally before the state-clear — passing+ // the captured value to downgradeSubscription guarantees the request+ // targets exactly the tier the user confirmed in the dialog, even if+ // plan.previousTier shifts between dialog open and confirm (e.g. an+ // unrelated subscription refetch lands).+ const target = pendingTierDowngrade;+ if (!target) return;+ setPendingTierDowngrade(null);+ await downgradeSubscription(target);+ }++ function cancelTierDowngrade() {+ setPendingTierDowngrade(null);+ }+return {plan,isLoading: subscription.isLoading,@@ -195,7 +421,10 @@ export function useYourPlanCard() {// Don't offer upgrade alongside Resume — pending cancel/downgrade should// be released first via resumeSubscription, not stacked with a new tier.canUpgrade: Boolean(- plan?.nextTier && !plan?.isPendingCancel && !plan?.isPendingDowngrade,+ plan?.nextTier &&+ !plan?.isPendingCancel &&+ !plan?.isPendingDowngrade &&+ !plan?.isPendingCycleSwitch,),// Downgrade only when an active paid sub has a tier below it AND no// pending change is already in flight — avoids stacking schedules.@@ -203,9 +432,41 @@ export function useYourPlanCard() {plan?.isPaidPlan &&plan?.previousTier &&!plan?.isPendingCancel &&- !plan?.isPendingDowngrade,+ !plan?.isPendingDowngrade &&+ !plan?.isPendingCycleSwitch,+ ),+ canResume: Boolean(+ plan?.isPendingCancel ||+ plan?.isPendingDowngrade ||+ plan?.isPendingCycleSwitch,),- canResume: Boolean(plan?.isPendingCancel || plan?.isPendingDowngrade),+ selectedCycle,+ pendingCycle,+ pendingTierUpgrade,+ pendingTierUpgradeLabel: pendingTierUpgrade+ ? (PLAN_LABEL[pendingTierUpgrade] ?? pendingTierUpgrade)+ : null,+ pendingTierDowngrade,+ pendingTierDowngradeLabel: pendingTierDowngrade+ ? (PLAN_LABEL[pendingTierDowngrade] ?? pendingTierDowngrade)+ : null,+ isCycleToggleVisible,+ cycleDialogBody: getDialogBody(),+ tierUpgradeDialogBody: getTierUpgradeDialogBody(),+ tierDowngradeDialogBody: getTierDowngradeDialogBody(),+ onCycleChange,+ onConfirmCycleSwitch: () => {+ void confirmCycleSwitch();+ },+ onCancelCycleSwitch: cancelCycleSwitch,+ onConfirmTierUpgrade: () => {+ void confirmTierUpgrade();+ },+ onCancelTierUpgrade: cancelTierUpgrade,+ onConfirmTierDowngrade: () => {+ void confirmTierDowngrade();+ },+ onCancelTierDowngrade: cancelTierDowngrade,onUpgrade: () => {if (!plan?.nextTier) return;// Team (BUSINESS) tier is contact-sales — divert to marketing page@@ -214,10 +475,19 @@ export function useYourPlanCard() {window.open(TEAM_UPGRADE_URL, "_blank", "noopener,noreferrer");return;}- void changeTier(plan.nextTier);+ // Free tier (NO_TIER) flow runs through Stripe Checkout via the+ // success_url redirect — there's no immediate proration risk, so go+ // straight to changeTier without a confirm step. Only paid→paid+ // upgrades hit the always_invoice immediate-billing path.+ if (!plan.isPaidPlan) {+ void changeTier(plan.nextTier, selectedCycle);+ return;+ }+ setPendingTierUpgrade(plan.nextTier);},onDowngrade: () => {- void downgradeSubscription();+ if (!plan?.previousTier) return;+ setPendingTierDowngrade(plan.previousTier);},onResume: () => {void resumeSubscription();diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 62fb7eb80f..47aae7efb4 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -16618,6 +16618,19 @@"type": "object","title": "Tier Costs"},+ "tier_costs_yearly": {+ "additionalProperties": { "type": "integer" },+ "type": "object",+ "title": "Tier Costs Yearly",+ "description": "Tier → yearly amount in cents. Populated only for tiers with a yearly Stripe price configured in LaunchDarkly. Empty for monthly-only configurations."+ },+ "billing_cycle": {+ "type": "string",+ "enum": ["monthly", "yearly"],+ "title": "Billing Cycle",+ "description": "Billing cycle of the user's active Stripe subscription. Defaults to ``monthly`` for users without an active sub. ``monthly_cost`` above reflects this cycle's actual price (so a yearly subscriber sees their yearly amount, not the monthly equivalent).",+ "default": "monthly"+ },"tier_multipliers": {"additionalProperties": { "type": "number" },"type": "object",@@ -16656,6 +16669,14 @@],"title": "Pending Tier Effective At"},+ "pending_billing_cycle": {+ "anyOf": [+ { "type": "string", "enum": ["monthly", "yearly"] },+ { "type": "null" }+ ],+ "title": "Pending Billing Cycle",+ "description": "Billing cycle of the queued change, when resolvable. Set alongside ``pending_tier`` for tier downgrades and same-tier cycle switches (yearly→monthly). The frontend uses this to differentiate a cycle-only schedule (``pending_tier == current tier``) from a real tier downgrade so the UI copy can describe the actual change. ``None`` for cancellations and unconfigured legacy prices."+ },"url": {"type": "string","title": "Url",@@ -16694,6 +16715,12 @@"type": "string","title": "Cancel Url","default": ""+ },+ "billing_cycle": {+ "type": "string",+ "enum": ["monthly", "yearly"],+ "title": "Billing Cycle",+ "default": "monthly"}},"type": "object",diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/PlanCard.tsx b/autogpt_platform/frontend/src/components/molecules/PlanCard/PlanCard.tsxsimilarity index 97%rename from autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/PlanCard.tsxrename to autogpt_platform/frontend/src/components/molecules/PlanCard/PlanCard.tsxindex de40f147fa..0b4d4f50e0 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/PlanCard.tsx+++ b/autogpt_platform/frontend/src/components/molecules/PlanCard/PlanCard.tsx@@ -6,9 +6,9 @@ import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { cn } from "@/lib/utils";import { CheckIcon, StarIcon } from "@phosphor-icons/react";-import { type Country, formatPrice } from "../../countries";-import { PLAN_KEYS, type PlanDef, type PlanKey } from "../../helpers";-import { computePlanPricing } from "./helpers";+import { type Country, formatPrice } from "./countries";+import { PLAN_KEYS, type PlanDef, type PlanKey } from "./plans";+import { computePlanPricing } from "./computePricing";interface Props {plan: PlanDef;diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/helpers.test.ts b/autogpt_platform/frontend/src/components/molecules/PlanCard/computePricing.test.tssimilarity index 93%rename from autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/helpers.test.tsrename to autogpt_platform/frontend/src/components/molecules/PlanCard/computePricing.test.tsindex ccec48a8f5..111be0bc94 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/helpers.test.ts+++ b/autogpt_platform/frontend/src/components/molecules/PlanCard/computePricing.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from "vitest";-import { type Country } from "../../countries";-import { type PlanDef, PLAN_KEYS, YEARLY_PRICE_FACTOR } from "../../helpers";-import { computePlanPricing } from "./helpers";+import { type Country } from "./countries";+import { type PlanDef, PLAN_KEYS, YEARLY_PRICE_FACTOR } from "./plans";+import { computePlanPricing } from "./computePricing";const usdCountry: Country = {name: "United States",diff --git a/autogpt_platform/frontend/src/components/molecules/PlanCard/computePricing.ts b/autogpt_platform/frontend/src/components/molecules/PlanCard/computePricing.tsnew file mode 100644index 0000000000..1a6f77e4e8--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/PlanCard/computePricing.ts@@ -0,0 +1,31 @@+import { type Country } from "./countries";+import { type PlanDef, YEARLY_PRICE_FACTOR } from "./plans";++interface PriceComputationArgs {+ plan: PlanDef;+ country: Country;+ isYearly: boolean;+}++export function computePlanPricing({+ plan,+ country,+ isYearly,+}: PriceComputationArgs) {+ const monthlyLocal =+ plan.usdMonthly !== null ? plan.usdMonthly * country.rate : null;+ // Prefer the explicit yearly price (API-driven) over the YEARLY_PRICE_FACTOR+ // estimate so the displayed amount matches what Stripe will actually charge.+ const yearlyLocal =+ plan.usdYearly != null+ ? plan.usdYearly * country.rate+ : monthlyLocal !== null+ ? monthlyLocal * YEARLY_PRICE_FACTOR * 12+ : null;+ const displayPrice = isYearly ? yearlyLocal : monthlyLocal;+ const monthlyEquiv =+ isYearly && yearlyLocal !== null ? yearlyLocal / 12 : null;+ const perLabel = isYearly ? "/ year" : "/ month";++ return { displayPrice, monthlyEquiv, perLabel };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/countries.test.ts b/autogpt_platform/frontend/src/components/molecules/PlanCard/countries.test.tssimilarity index 100%rename from autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/countries.test.tsrename to autogpt_platform/frontend/src/components/molecules/PlanCard/countries.test.tsdiff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/countries.ts b/autogpt_platform/frontend/src/components/molecules/PlanCard/countries.tssimilarity index 100%rename from autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/countries.tsrename to autogpt_platform/frontend/src/components/molecules/PlanCard/countries.tsdiff --git a/autogpt_platform/frontend/src/components/molecules/PlanCard/plans.ts b/autogpt_platform/frontend/src/components/molecules/PlanCard/plans.tsnew file mode 100644index 0000000000..751e3c8540--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/PlanCard/plans.ts@@ -0,0 +1,162 @@+export const PRO_USD_MONTHLY = 50;+export const MAX_USD_MONTHLY = 320;+// Fraction of the full monthly price paid when billed yearly. 0.85 = 15% off.+export const YEARLY_PRICE_FACTOR = 0.85;+export const TEAM_INTAKE_FORM_URL = "https://tally.so/r/2Eb9zj";++export const PLAN_KEYS = {+ PRO: "PRO",+ MAX: "MAX",+ TEAM: "TEAM",+ BUSINESS: "BUSINESS",+} as const;+export type PlanKey = (typeof PLAN_KEYS)[keyof typeof PLAN_KEYS];++export interface PlanDef {+ key: PlanKey;+ name: string;+ usage: string | null;+ usdMonthly: number | null;+ // Explicit yearly price in USD; when provided, computePlanPricing uses it+ // instead of usdMonthly * YEARLY_PRICE_FACTOR * 12. Lets API-driven surfaces+ // (PaywallGate) display the actual Stripe yearly amount.+ usdYearly?: number | null;+ description: string;+ features: string[];+ cta: string;+ highlighted: boolean;+ badge: string | null;+ buttonVariant: "primary" | "secondary";+}++export const PLANS: PlanDef[] = [+ {+ key: PLAN_KEYS.PRO,+ name: "Pro",+ usage: "1x",+ usdMonthly: PRO_USD_MONTHLY,+ description:+ "For individuals getting started with dependable everyday automation.",+ features: [+ "Access to virtually any leading AI model",+ "Agents work non-stop in the background",+ "Visual agent builder and chat-based agent creation",+ "File-aware agents that can work with your documents",+ "End-to-end agent management and run visibility",+ "Scheduled and event-based triggers",+ ],+ cta: "Get Pro",+ highlighted: false,+ badge: null,+ buttonVariant: "secondary",+ },+ {+ key: PLAN_KEYS.MAX,+ name: "Max",+ usage: "8.5x",+ usdMonthly: MAX_USD_MONTHLY,+ description: "For users who are serious about getting more work done.",+ features: [+ "Includes everything in Pro",+ "8.5x Pro usage",+ "5x file storage",+ "Early access to features before anyone else",+ "Expand our extensive integration library",+ "Priority support",+ "Help drive the roadmap for new features",+ ],+ cta: "Upgrade to Max",+ highlighted: true,+ badge: "Best value",+ buttonVariant: "primary",+ },+ {+ key: PLAN_KEYS.TEAM,+ name: "Team",+ usage: null,+ usdMonthly: null,+ description:+ "For teams that need collaboration, controls, and custom usage.",+ features: [+ "Multi-user workspaces",+ "Admin controls & roles",+ "Centralized billing & seat management",+ "Collaboration & approvals",+ "Security & compliance options",+ "Secure access for shared integrations",+ ],+ cta: "Contact sales",+ highlighted: false,+ badge: "Coming soon",+ buttonVariant: "secondary",+ },+];++// Backend-tier → static visual metadata. Used by API-driven surfaces+// (PaywallGate) which derive prices from /credits/subscription and need only+// the descriptive content (features/usage/highlight/cta).+export type BackendTierKey = "PRO" | "MAX" | "BUSINESS";++export const PLAN_METADATA: Record<+ BackendTierKey,+ Omit<PlanDef, "usdMonthly" | "usdYearly">+> = {+ PRO: {+ key: PLAN_KEYS.PRO,+ name: "Pro",+ usage: "1x",+ description:+ "For individuals getting started with dependable everyday automation.",+ features: [+ "Access to virtually any leading AI model",+ "Agents work non-stop in the background",+ "Visual agent builder and chat-based agent creation",+ "File-aware agents that can work with your documents",+ "End-to-end agent management and run visibility",+ "Scheduled and event-based triggers",+ ],+ cta: "Upgrade to Pro",+ highlighted: false,+ badge: null,+ buttonVariant: "secondary",+ },+ MAX: {+ key: PLAN_KEYS.MAX,+ name: "Max",+ usage: "8.5x",+ description: "For users who are serious about getting more work done.",+ features: [+ "Includes everything in Pro",+ "8.5x Pro usage",+ "5x file storage",+ "Early access to features before anyone else",+ "Expand our extensive integration library",+ "Priority support",+ "Help drive the roadmap for new features",+ ],+ cta: "Upgrade to Max",+ highlighted: true,+ badge: "Best value",+ buttonVariant: "primary",+ },+ BUSINESS: {+ key: PLAN_KEYS.BUSINESS,+ name: "Team",+ usage: null,+ description:+ "For teams and heavy workloads that need expanded capacity and controls.",+ features: [+ "Includes everything in Max",+ "Highest AutoPilot capacity",+ "Priority support and onboarding",+ "Advanced security & compliance options",+ "Dedicated account contact",+ ],+ // Team is contact-sales — the click handler diverts to TEAM_INTAKE_FORM_URL+ // rather than POSTing to /credits/subscription, so the CTA reflects that.+ cta: "Talk to sales",+ highlighted: false,+ badge: null,+ buttonVariant: "secondary",+ },+};