Skip to content

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

feat(platform): defer paid-to-paid subscription downgrades + cancel-pending flow (#12865)

Zamil Majdy343222ace156
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
index c20e0d0ceb..96fd8763eb 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
@@ -47,6 +47,40 @@ def _configure_frontend_origin(mocker: pytest_mock.MockFixture) -> None:
)
[email protected](autouse=True)
+def _stub_pending_subscription_change(mocker: pytest_mock.MockFixture) -> None:
+ """Default pending-change lookup to None so tests don't hit Stripe/DB.
+
+ Individual tests can override via their own mocker.patch call.
+ """
+ mocker.patch(
+ "backend.api.features.v1.get_pending_subscription_change",
+ new_callable=AsyncMock,
+ return_value=None,
+ )
+
+
[email protected](autouse=True)
+def _stub_subscription_status_lookups(mocker: pytest_mock.MockFixture) -> None:
+ """Stub Stripe price + proration lookups used by get_subscription_status.
+
+ The POST /credits/subscription handler now returns the full subscription
+ status payload from every branch (same-tier, FREE downgrade, paid→paid
+ modify, checkout creation), so every POST test implicitly hits these
+ helpers. Individual tests can override via their own mocker.patch call.
+ """
+ mocker.patch(
+ "backend.api.features.v1.get_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value=None,
+ )
+ mocker.patch(
+ "backend.api.features.v1.get_proration_credit_cents",
+ new_callable=AsyncMock,
+ return_value=0,
+ )
+
+
@pytest.mark.parametrize(
"url,expected",
[
@@ -407,30 +441,77 @@ def test_update_subscription_tier_enterprise_blocked(
set_tier_mock.assert_not_awaited()
-def test_update_subscription_tier_same_tier_is_noop(
+def test_update_subscription_tier_same_tier_releases_pending_change(
client: fastapi.testclient.TestClient,
mocker: pytest_mock.MockFixture,
) -> None:
- """POST /credits/subscription for the user's current paid tier returns 200 with empty URL.
+ """POST /credits/subscription for the user's current tier releases any pending change.
- Without this guard a duplicate POST (double-click, browser retry, stale page) would
- create a second Stripe Checkout Session for the same price, potentially billing the
- user twice until the webhook reconciliation fires.
+ "Stay on my current tier" — the collapsed replacement for the old
+ /credits/subscription/cancel-pending route. Always calls
+ release_pending_subscription_schedule (idempotent when nothing is pending)
+ and returns the refreshed status with url="". Never creates a Checkout
+ Session — that would double-charge a user who double-clicks their own tier.
"""
mock_user = Mock()
- mock_user.subscription_tier = SubscriptionTier.PRO
-
- async def mock_feature_enabled(*args, **kwargs):
- return True
+ mock_user.subscription_tier = SubscriptionTier.BUSINESS
mocker.patch(
"backend.api.features.v1.get_user_by_id",
new_callable=AsyncMock,
return_value=mock_user,
)
- mocker.patch(
+ release_mock = mocker.patch(
+ "backend.api.features.v1.release_pending_subscription_schedule",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ checkout_mock = mocker.patch(
+ "backend.api.features.v1.create_subscription_checkout",
+ new_callable=AsyncMock,
+ )
+ feature_mock = mocker.patch(
"backend.api.features.v1.is_feature_enabled",
- side_effect=mock_feature_enabled,
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+
+ response = client.post(
+ "/credits/subscription",
+ json={
+ "tier": "BUSINESS",
+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",
+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",
+ },
+ )
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["tier"] == "BUSINESS"
+ assert data["url"] == ""
+ release_mock.assert_awaited_once_with(TEST_USER_ID)
+ checkout_mock.assert_not_awaited()
+ # Same-tier branch short-circuits before the payment-flag check.
+ feature_mock.assert_not_awaited()
+
+
+def test_update_subscription_tier_same_tier_no_pending_change_returns_status(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Same-tier request when nothing is pending still returns status with url=""."""
+ 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,
+ )
+ release_mock = mocker.patch(
+ "backend.api.features.v1.release_pending_subscription_schedule",
+ new_callable=AsyncMock,
+ return_value=False,
)
checkout_mock = mocker.patch(
"backend.api.features.v1.create_subscription_checkout",
@@ -447,10 +528,50 @@ def test_update_subscription_tier_same_tier_is_noop(
)
assert response.status_code == 200
- assert response.json()["url"] == ""
+ data = response.json()
+ assert data["tier"] == "PRO"
+ assert data["url"] == ""
+ assert data["pending_tier"] is None
+ release_mock.assert_awaited_once_with(TEST_USER_ID)
checkout_mock.assert_not_awaited()
+def test_update_subscription_tier_same_tier_stripe_error_returns_502(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Same-tier request surfaces a 502 when Stripe release fails.
+
+ Carries forward the error contract from the removed
+ /credits/subscription/cancel-pending route so clients keep seeing 502 for
+ transient Stripe failures.
+ """
+ mock_user = Mock()
+ mock_user.subscription_tier = SubscriptionTier.BUSINESS
+
+ mocker.patch(
+ "backend.api.features.v1.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ )
+ mocker.patch(
+ "backend.api.features.v1.release_pending_subscription_schedule",
+ side_effect=stripe.StripeError("network"),
+ )
+
+ response = client.post(
+ "/credits/subscription",
+ json={
+ "tier": "BUSINESS",
+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",
+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",
+ },
+ )
+
+ assert response.status_code == 502
+ assert "contact support" in response.json()["detail"].lower()
+
+
def test_update_subscription_tier_free_with_payment_schedules_cancel_and_does_not_update_db(
client: fastapi.testclient.TestClient,
mocker: pytest_mock.MockFixture,
@@ -803,3 +924,197 @@ def test_update_subscription_tier_free_no_stripe_subscription(
cancel_mock.assert_awaited_once_with(TEST_USER_ID)
# DB tier must be updated immediately — no webhook will fire for a missing sub
set_tier_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.FREE)
+
+
+def test_get_subscription_status_includes_pending_tier(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """GET /credits/subscription exposes pending_tier and pending_tier_effective_at."""
+ import datetime as dt
+
+ mock_user = Mock()
+ mock_user.subscription_tier = SubscriptionTier.BUSINESS
+
+ effective_at = dt.datetime(2030, 1, 1, tzinfo=dt.timezone.utc)
+
+ async def mock_price_id(tier: SubscriptionTier) -> str | None:
+ 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.get_subscription_price_id",
+ side_effect=mock_price_id,
+ )
+ mocker.patch(
+ "backend.api.features.v1.get_proration_credit_cents",
+ new_callable=AsyncMock,
+ return_value=0,
+ )
+ mocker.patch(
+ "backend.api.features.v1.get_pending_subscription_change",
+ new_callable=AsyncMock,
+ return_value=(SubscriptionTier.PRO, effective_at),
+ )
+
+ response = client.get("/credits/subscription")
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["pending_tier"] == "PRO"
+ assert data["pending_tier_effective_at"] is not None
+
+
+def test_get_subscription_status_no_pending_tier(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """When no pending change exists the response omits pending_tier."""
+ 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_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value=None,
+ )
+ mocker.patch(
+ "backend.api.features.v1.get_proration_credit_cents",
+ new_callable=AsyncMock,
+ return_value=0,
+ )
+ mocker.patch(
+ "backend.api.features.v1.get_pending_subscription_change",
+ new_callable=AsyncMock,
+ return_value=None,
+ )
+
+ response = client.get("/credits/subscription")
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["pending_tier"] is None
+ assert data["pending_tier_effective_at"] is None
+
+
+def test_update_subscription_tier_downgrade_paid_to_paid_schedules(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """A BUSINESS→PRO downgrade request dispatches to modify_stripe_subscription_for_tier."""
+ mock_user = Mock()
+ mock_user.subscription_tier = SubscriptionTier.BUSINESS
+
+ 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,
+ )
+ modify_mock = mocker.patch(
+ "backend.api.features.v1.modify_stripe_subscription_for_tier",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+ checkout_mock = mocker.patch(
+ "backend.api.features.v1.create_subscription_checkout",
+ 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",
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["url"] == ""
+ modify_mock.assert_awaited_once_with(TEST_USER_ID, SubscriptionTier.PRO)
+ checkout_mock.assert_not_awaited()
+
+
+def test_stripe_webhook_dispatches_subscription_schedule_released(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """subscription_schedule.released routes to sync_subscription_schedule_from_stripe."""
+ schedule_obj = {"id": "sub_sched_1", "subscription": "sub_pro"}
+ event = {
+ "type": "subscription_schedule.released",
+ "data": {"object": schedule_obj},
+ }
+ mocker.patch(
+ "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ new="whsec_test",
+ )
+ mocker.patch(
+ "backend.api.features.v1.stripe.Webhook.construct_event",
+ return_value=event,
+ )
+ sync_mock = mocker.patch(
+ "backend.api.features.v1.sync_subscription_schedule_from_stripe",
+ new_callable=AsyncMock,
+ )
+
+ response = client.post(
+ "/credits/stripe_webhook",
+ content=b"{}",
+ headers={"stripe-signature": "t=1,v1=abc"},
+ )
+
+ assert response.status_code == 200
+ sync_mock.assert_awaited_once_with(schedule_obj)
+
+
+def test_stripe_webhook_ignores_subscription_schedule_updated(
+ client: fastapi.testclient.TestClient,
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """subscription_schedule.updated must NOT dispatch: our own
+ SubscriptionSchedule.create/.modify calls fire this event and would
+ otherwise loop redundant traffic through the sync handler. State
+ transitions we care about surface via .released/.completed, and phase
+ advance to a new price is already covered by customer.subscription.updated.
+ """
+ schedule_obj = {"id": "sub_sched_1", "subscription": "sub_pro"}
+ event = {
+ "type": "subscription_schedule.updated",
+ "data": {"object": schedule_obj},
+ }
+ mocker.patch(
+ "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ new="whsec_test",
+ )
+ mocker.patch(
+ "backend.api.features.v1.stripe.Webhook.construct_event",
+ return_value=event,
+ )
+ sync_mock = mocker.patch(
+ "backend.api.features.v1.sync_subscription_schedule_from_stripe",
+ new_callable=AsyncMock,
+ )
+
+ response = client.post(
+ "/credits/stripe_webhook",
+ content=b"{}",
+ headers={"stripe-signature": "t=1,v1=abc"},
+ )
+
+ assert response.status_code == 200
+ sync_mock.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index ab0b69071d..3559071043 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -26,7 +26,7 @@ from fastapi import (
)
from fastapi.concurrency import run_in_threadpool
from prisma.enums import SubscriptionTier
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from starlette.status import HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND
from typing_extensions import Optional, TypedDict
@@ -49,20 +49,24 @@ from backend.data.auth import api_key as api_key_db
from backend.data.block import BlockInput, CompletedBlockOutput
from backend.data.credit import (
AutoTopUpConfig,
+ PendingChangeUnknown,
RefundRequest,
TransactionHistory,
UserCredit,
cancel_stripe_subscription,
create_subscription_checkout,
get_auto_top_up,
+ get_pending_subscription_change,
get_proration_credit_cents,
get_subscription_price_id,
get_user_credit_model,
handle_subscription_payment_failure,
modify_stripe_subscription_for_tier,
+ release_pending_subscription_schedule,
set_auto_top_up,
set_subscription_tier,
sync_subscription_from_stripe,
+ sync_subscription_schedule_from_stripe,
)
from backend.data.graph import GraphSettings
from backend.data.model import CredentialsMetaInput, UserOnboarding
@@ -698,15 +702,21 @@ class SubscriptionTierRequest(BaseModel):
cancel_url: str = ""
-class SubscriptionCheckoutResponse(BaseModel):
- url: str
-
-
class SubscriptionStatusResponse(BaseModel):
tier: Literal["FREE", "PRO", "BUSINESS", "ENTERPRISE"]
monthly_cost: int # amount in cents (Stripe convention)
tier_costs: dict[str, int] # tier name -> amount in cents
proration_credit_cents: int # unused portion of current sub to convert on upgrade
+ pending_tier: Optional[Literal["FREE", "PRO", "BUSINESS"]] = None
+ pending_tier_effective_at: Optional[datetime] = None
+ url: str = Field(
+ default="",
+ description=(
+ "Populated only when POST /credits/subscription starts a Stripe Checkout"
+ " Session (FREE → paid upgrade). Empty string in all other branches —"
+ " the client redirects to this URL when non-empty."
+ ),
+ )
def _validate_checkout_redirect_url(url: str) -> bool:
@@ -804,17 +814,42 @@ async def get_subscription_status(
current_monthly_cost = tier_costs.get(tier.value, 0)
proration_credit = await get_proration_credit_cents(user_id, current_monthly_cost)
- return SubscriptionStatusResponse(
+ try:
+ pending = await get_pending_subscription_change(user_id)
+ except (stripe.StripeError, PendingChangeUnknown):
+ # Swallow Stripe-side failures (rate limits, transient network) AND
+ # PendingChangeUnknown (LaunchDarkly price-id lookup failed). Both
+ # propagate past the cache so the next request retries fresh instead
+ # of serving a stale None for the TTL window. Let real bugs (KeyError,
+ # AttributeError, etc.) propagate so they surface in Sentry.
+ logger.exception(
+ "get_subscription_status: failed to resolve pending change for user %s",
+ user_id,
+ )
+ pending = None
+
+ response = SubscriptionStatusResponse(
tier=tier.value,
monthly_cost=current_monthly_cost,
tier_costs=tier_costs,
proration_credit_cents=proration_credit,
)
+ if pending is not None:
+ pending_tier_enum, pending_effective_at = pending
+ if pending_tier_enum == SubscriptionTier.FREE:
+ response.pending_tier = "FREE"
+ elif pending_tier_enum == SubscriptionTier.PRO:
+ response.pending_tier = "PRO"
+ elif pending_tier_enum == SubscriptionTier.BUSINESS:
+ response.pending_tier = "BUSINESS"
+ if response.pending_tier is not None:
+ response.pending_tier_effective_at = pending_effective_at
+ return response
@v1_router.post(
path="/credits/subscription",
- summary="Start a Stripe Checkout session to upgrade subscription tier",
+ summary="Update subscription tier or start a Stripe Checkout session",
operation_id="updateSubscriptionTier",
tags=["credits"],
dependencies=[Security(requires_user)],
@@ -822,7 +857,7 @@ async def get_subscription_status(
async def update_subscription_tier(
request: SubscriptionTierRequest,
user_id: Annotated[str, Security(get_user_id)],
-) -> SubscriptionCheckoutResponse:
+) -> SubscriptionStatusResponse:
# Pydantic validates tier is one of FREE/PRO/BUSINESS via Literal type.
tier = SubscriptionTier(request.tier)
@@ -834,6 +869,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→FREE 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.FREE) == tier:
+ try:
+ await release_pending_subscription_schedule(user_id)
+ except stripe.StripeError as e:
+ logger.exception(
+ "Stripe error releasing pending subscription change for user %s: %s",
+ user_id,
+ e,
+ )
+ raise HTTPException(
+ status_code=502,
+ detail=(
+ "Unable to cancel the pending subscription change right now. "
+ "Please try again or contact support."
+ ),
+ )
+ return await get_subscription_status(user_id)
+
payment_enabled = await is_feature_enabled(
Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False
)
@@ -871,9 +929,9 @@ async def update_subscription_tier(
# admin-granted tier. Update DB immediately since the
# subscription.deleted webhook will never fire.
await set_subscription_tier(user_id, tier)
- return SubscriptionCheckoutResponse(url="")
+ return await get_subscription_status(user_id)
await set_subscription_tier(user_id, tier)
- return SubscriptionCheckoutResponse(url="")
+ return await get_subscription_status(user_id)
# Paid tier changes require payment to be enabled — block self-service upgrades
# when the flag is off. Admins use the /api/admin/ routes to set tiers directly.
@@ -883,15 +941,6 @@ async def update_subscription_tier(
detail=f"Subscription not available for tier {tier}",
)
- # No-op short-circuit: if the user is already on the requested paid tier,
- # do NOT create a new Checkout Session. Without this guard, a duplicate
- # request (double-click, retried POST, stale page) creates a second
- # subscription for the same price; the user would be charged for both
- # until `_cleanup_stale_subscriptions` runs from the resulting webhook —
- # which only fires after the second charge has cleared.
- if (user.subscription_tier or SubscriptionTier.FREE) == tier:
- return SubscriptionCheckoutResponse(url="")
-
# Paid→paid tier change: if the user already has a Stripe subscription,
# modify it in-place with proration instead of creating a new Checkout
# Session. This preserves remaining paid time and avoids double-charging.
@@ -901,14 +950,14 @@ async def update_subscription_tier(
try:
modified = await modify_stripe_subscription_for_tier(user_id, tier)
if modified:
- return SubscriptionCheckoutResponse(url="")
+ return await get_subscription_status(user_id)
# modify_stripe_subscription_for_tier returns False when no active
# Stripe subscription exists — i.e. the user has an admin-granted
# paid tier with no Stripe record. In that case, update the DB
# tier directly (same as the FREE-downgrade path for admin-granted
# users) rather than sending them through a new Checkout Session.
await set_subscription_tier(user_id, tier)
- return SubscriptionCheckoutResponse(url="")
+ return await get_subscription_status(user_id)
except ValueError as e:
raise HTTPException(status_code=422, detail=str(e))
except stripe.StripeError as e:
@@ -978,7 +1027,9 @@ async def update_subscription_tier(
),
)
- return SubscriptionCheckoutResponse(url=url)
+ status = await get_subscription_status(user_id)
+ status.url = url
+ return status
@v1_router.post(
@@ -1043,6 +1094,18 @@ async def stripe_webhook(request: Request):
):
await sync_subscription_from_stripe(data_object)
+ # `subscription_schedule.updated` is deliberately omitted: our own
+ # `SubscriptionSchedule.create` + `.modify` calls in
+ # `_schedule_downgrade_at_period_end` would fire that event right back at us
+ # and loop redundant traffic through this handler. We only care about state
+ # transitions (released / completed); phase advance to the new price is
+ # already covered by `customer.subscription.updated`.
+ if event_type in (
+ "subscription_schedule.released",
+ "subscription_schedule.completed",
+ ):
+ await sync_subscription_schedule_from_stripe(data_object)
+
if event_type == "invoice.payment_failed":
await handle_subscription_payment_failure(data_object)
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.py
index 3124c28992..c08cb1b3a8 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py
@@ -17,6 +17,7 @@ from redis.exceptions import RedisError
from backend.data.db_accessors import user_db
from backend.data.redis_client import get_redis_async
+from backend.data.user import get_user_by_id
from backend.util.cache import cached
logger = logging.getLogger(__name__)
@@ -459,8 +460,20 @@ get_user_tier.cache_delete = _fetch_user_tier.cache_delete # type: ignore[attr-
async def set_user_tier(user_id: str, tier: SubscriptionTier) -> None:
"""Persist the user's rate-limit tier to the database.
- Also invalidates the ``get_user_tier`` cache for this user so that
- subsequent rate-limit checks immediately see the new tier.
+ Invalidates every cache that keys off the user's subscription tier so the
+ change is visible immediately: this function's own ``get_user_tier``, the
+ shared ``get_user_by_id`` (which exposes ``user.subscription_tier``), and
+ ``get_pending_subscription_change`` (since an admin override can invalidate
+ a cached ``cancel_at_period_end`` or schedule-based pending state).
+
+ If the user has an active Stripe subscription whose current price does not
+ match ``tier``, Stripe will keep billing the old price and the next
+ ``customer.subscription.updated`` webhook will overwrite the DB tier back
+ to whatever Stripe has. Proper reconciliation (cancelling or modifying the
+ Stripe subscription when an admin overrides the tier) is out of scope for
+ this PR — it changes the admin contract and needs its own test coverage.
+ For now we emit a ``WARNING`` so drift surfaces via Sentry until that
+ follow-up lands.
Raises:
prisma.errors.RecordNotFoundError: If the user does not exist.
@@ -469,8 +482,113 @@ async def set_user_tier(user_id: str, tier: SubscriptionTier) -> None:
where={"id": user_id},
data={"subscriptionTier": tier.value},
)
- # Invalidate cached tier so rate-limit checks pick up the change immediately.
get_user_tier.cache_delete(user_id) # type: ignore[attr-defined]
+ # Local import required: backend.data.credit imports backend.copilot.rate_limit
+ # (via get_user_tier in credit.py's _invalidate_user_tier_caches), so a
+ # top-level ``from backend.data.credit import ...`` here would create a
+ # circular import at module-load time.
+ from backend.data.credit import get_pending_subscription_change
+
+ get_user_by_id.cache_delete(user_id) # type: ignore[attr-defined]
+ get_pending_subscription_change.cache_delete(user_id) # type: ignore[attr-defined]
+
+ # The DB write above is already committed; the drift check is best-effort
+ # diagnostic logging. Fire-and-forget so admin bulk ops don't wait on a
+ # Stripe roundtrip. The inner helper wraps its body in a timeout + broad
+ # except so background task errors still surface via logs rather than as
+ # "task exception never retrieved" warnings. Cancellation on request
+ # shutdown is acceptable — the drift warning is non-load-bearing.
+ asyncio.ensure_future(_drift_check_background(user_id, tier))
+
+
+async def _drift_check_background(user_id: str, tier: SubscriptionTier) -> None:
+ """Run the Stripe drift check in the background, logging rather than raising."""
+ try:
+ await asyncio.wait_for(
+ _warn_if_stripe_subscription_drifts(user_id, tier),
+ timeout=5.0,
+ )
+ logger.debug(
+ "set_user_tier: drift check completed for user=%s admin_tier=%s",
+ user_id,
+ tier.value,
+ )
+ except asyncio.TimeoutError:
+ logger.warning(
+ "set_user_tier: drift check timed out for user=%s admin_tier=%s",
+ user_id,
+ tier.value,
+ )
+ except asyncio.CancelledError:
+ # Request may have completed and the event loop is cancelling tasks —
+ # the drift log is non-critical, so accept cancellation silently.
+ raise
+ except Exception:
+ logger.exception(
+ "set_user_tier: drift check background task failed for"
+ " user=%s admin_tier=%s",
+ user_id,
+ tier.value,
+ )
+
+
+async def _warn_if_stripe_subscription_drifts(
+ user_id: str, new_tier: SubscriptionTier
+) -> None:
+ """Emit a WARNING when an admin tier override leaves an active Stripe sub on a
+ mismatched price.
+
+ The warning is diagnostic only: Stripe remains the billing source of truth,
+ so the next ``customer.subscription.updated`` webhook will reset the DB
+ tier. Surfacing the drift here lets ops catch admin overrides that bypass
+ the intended Checkout / Portal cancel flows before users notice surprise
+ charges.
+ """
+ # Local imports: see note in ``set_user_tier`` about the credit <-> rate_limit
+ # circular. These helpers (``_get_active_subscription``,
+ # ``get_subscription_price_id``) live in credit.py alongside the rest of
+ # the Stripe billing code.
+ from backend.data.credit import _get_active_subscription, get_subscription_price_id
+
+ try:
+ user = await get_user_by_id(user_id)
+ if not getattr(user, "stripe_customer_id", None):
+ return
+ sub = await _get_active_subscription(user.stripe_customer_id)
+ if sub is None:
+ return
+ items = sub["items"].data
+ if not items:
+ return
+ price = items[0].price
+ current_price_id = price if isinstance(price, str) else price.id
+ # The LaunchDarkly-backed price lookup must live inside this try/except:
+ # an LD SDK failure (network, token revoked) here would otherwise
+ # propagate past set_user_tier's already-committed DB write and turn a
+ # best-effort diagnostic into a 500 on admin tier writes.
+ expected_price_id = await get_subscription_price_id(new_tier)
+ except Exception:
+ logger.debug(
+ "_warn_if_stripe_subscription_drifts: drift lookup failed for"
+ " user=%s; skipping drift warning",
+ user_id,
+ exc_info=True,
+ )
+ return
+ if expected_price_id is not None and expected_price_id == current_price_id:
+ return
+ logger.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.",
+ user_id,
+ new_tier.value,
+ sub.id,
+ current_price_id,
+ expected_price_id,
+ )
async def get_global_rate_limits(
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit_test.py b/autogpt_platform/backend/backend/copilot/rate_limit_test.py
index ea87658710..577093c752 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit_test.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit_test.py
@@ -581,6 +581,80 @@ class TestSetUserTier:
assert tier_after == SubscriptionTier.ENTERPRISE
+ @pytest.mark.asyncio
+ async def test_drift_check_swallows_launchdarkly_failure(self):
+ """LaunchDarkly price-id lookup failures inside the drift check must
+ never bubble up and 500 the admin tier write — the DB update is
+ already committed by the time we check drift."""
+ mock_prisma = AsyncMock()
+ mock_prisma.update = AsyncMock(return_value=None)
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ mock_sub = MagicMock()
+ mock_sub.id = "sub_abc"
+ mock_sub["items"].data = [MagicMock(price=MagicMock(id="price_mismatch"))]
+
+ with (
+ patch(
+ "backend.copilot.rate_limit.PrismaUser.prisma",
+ return_value=mock_prisma,
+ ),
+ 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",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("LD SDK not initialized"),
+ ),
+ ):
+ # Must NOT raise — drift check is best-effort diagnostic only.
+ await set_user_tier(_USER, SubscriptionTier.PRO)
+
+ mock_prisma.update.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_drift_check_timeout_is_bounded(self):
+ """A Stripe call that stalls on the 80s SDK default must not block the
+ admin tier write — set_user_tier wraps the drift check in a 5s timeout
+ and logs + returns on TimeoutError."""
+ import asyncio as _asyncio
+
+ mock_prisma = AsyncMock()
+ mock_prisma.update = AsyncMock(return_value=None)
+
+ async def _never_returns(_user_id: str, _tier):
+ await _asyncio.sleep(60)
+
+ with (
+ patch(
+ "backend.copilot.rate_limit.PrismaUser.prisma",
+ return_value=mock_prisma,
+ ),
+ patch(
+ "backend.copilot.rate_limit._warn_if_stripe_subscription_drifts",
+ side_effect=_never_returns,
+ ),
+ patch(
+ "backend.copilot.rate_limit.asyncio.wait_for",
+ new_callable=AsyncMock,
+ side_effect=_asyncio.TimeoutError,
+ ),
+ ):
+ await set_user_tier(_USER, SubscriptionTier.PRO)
+
+ # Set_user_tier still completed — the drift timeout did not propagate.
+ mock_prisma.update.assert_awaited_once()
+
# ---------------------------------------------------------------------------
# get_global_rate_limits with tiers
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index e97578d5cc..a42ba91be8 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -15,7 +15,7 @@ from prisma.enums import (
OnboardingStep,
SubscriptionTier,
)
-from prisma.errors import UniqueViolationError
+from prisma.errors import PrismaError, UniqueViolationError
from prisma.models import CreditRefundRequest, CreditTransaction, User, UserBalance
from prisma.types import CreditRefundRequestCreateInput, CreditTransactionWhereInput
from pydantic import BaseModel
@@ -1280,6 +1280,12 @@ async def set_subscription_tier(user_id: str, tier: SubscriptionTier) -> None:
from backend.copilot.rate_limit import get_user_tier # local import avoids circular
get_user_tier.cache_delete(user_id) # type: ignore[attr-defined]
+ # Invalidate the pending-change cache too — an admin tier override or the
+ # webhook-driven phase transition means any cached pending-change state
+ # (schedule, cancel_at_period_end) is likely stale. Without this the
+ # billing page can show a pending change for up to 30s after the tier
+ # has already flipped.
+ get_pending_subscription_change.cache_delete(user_id)
async def _cancel_customer_subscriptions(
@@ -1330,6 +1336,21 @@ async def _cancel_customer_subscriptions(
continue
seen_ids.add(sub_id)
if at_period_end:
+ # Stripe rejects modify(cancel_at_period_end=True) with 400 when a
+ # Subscription Schedule is attached (e.g. the user previously
+ # queued a paid→paid downgrade and is now clicking "Cancel").
+ # Release the schedule first so the cancel flag can be set; the
+ # schedule's pending phase change is superseded by the cancel.
+ existing_schedule = sub.schedule
+ if existing_schedule:
+ schedule_id = (
+ existing_schedule
+ if isinstance(existing_schedule, str)
+ else existing_schedule.id
+ )
+ await _release_schedule_ignoring_terminal(
+ schedule_id, "_cancel_customer_subscriptions"
+ )
await run_in_threadpool(
stripe.Subscription.modify, sub_id, cancel_at_period_end=True
)
@@ -1366,6 +1387,8 @@ async def cancel_stripe_subscription(user_id: str) -> bool:
cancelled_count = await _cancel_customer_subscriptions(
customer_id, at_period_end=True
)
+ if cancelled_count > 0:
+ get_pending_subscription_change.cache_delete(user_id)
return cancelled_count > 0
except stripe.StripeError:
logger.warning(
@@ -1415,18 +1438,224 @@ async def get_proration_credit_cents(user_id: str, monthly_cost_cents: int) -> i
return 0
+# Ordered from least- to most-privileged. Used to distinguish upgrades
+# (move right) from downgrades (move left); ENTERPRISE is admin-managed and
+# never reached via self-service flows.
+_TIER_ORDER: tuple[SubscriptionTier, ...] = (
+ SubscriptionTier.FREE,
+ SubscriptionTier.PRO,
+ SubscriptionTier.BUSINESS,
+ SubscriptionTier.ENTERPRISE,
+)
+
+
+def _tier_rank(tier: SubscriptionTier) -> int:
+ return _TIER_ORDER.index(tier)
+
+
+def is_tier_upgrade(current: SubscriptionTier, target: SubscriptionTier) -> bool:
+ return _tier_rank(target) > _tier_rank(current)
+
+
+def is_tier_downgrade(current: SubscriptionTier, target: SubscriptionTier) -> bool:
+ return _tier_rank(target) < _tier_rank(current)
+
+
+class PendingChangeUnknown(Exception):
+ """Raised when pending-change state cannot be determined (e.g. LaunchDarkly
+ price-id lookup failed). Propagates past the @cached wrapper so the next
+ request retries instead of serving a stale `None` for the TTL window."""
+
+
+async def _get_active_subscription(customer_id: str) -> stripe.Subscription | None:
+ """Return the customer's active or trialing subscription, or None."""
+ for status in ("active", "trialing"):
+ subs = await stripe.Subscription.list_async(
+ customer=customer_id, status=status, limit=1
+ )
+ if subs.data:
+ return subs.data[0]
+ return None
+
+
+# Substrings Stripe uses in InvalidRequestError messages when the schedule is
+# already in a terminal state (released / completed / canceled) and therefore
+# cannot be released again. We only swallow the error when one of these appears;
+# anything else (typo'd schedule id, wrong subscription, 404, etc.) must
+# propagate so bugs aren't masked as silent no-ops.
+_TERMINAL_SCHEDULE_ERROR_SUBSTRINGS = (
+ "already been released",
+ "already released",
+ "already been completed",
+ "already completed",
+ "already been canceled",
+ "already been cancelled",
+ "already canceled",
+ "already cancelled",
+ "is not active",
+ "is not in a state",
+)
+
+
+async def _release_schedule_ignoring_terminal(
+ schedule_id: str, log_context: str
+) -> bool:
+ """Release a Stripe schedule; swallow InvalidRequestError on terminal state.
+
+ Returns True if the release call succeeded, False if the schedule was
+ already in a terminal (released / completed / canceled) state. Any other
+ Stripe error — including non-terminal InvalidRequestErrors such as typo'd
+ ids or 404s — propagates so the caller can surface the failure instead of
+ silently masking a bug.
+ """
+ try:
+ await stripe.SubscriptionSchedule.release_async(schedule_id)
+ return True
+ except stripe.InvalidRequestError as e:
+ message = getattr(e, "user_message", None) or str(e)
+ if not any(
+ marker in message.lower() for marker in _TERMINAL_SCHEDULE_ERROR_SUBSTRINGS
+ ):
+ logger.warning(
+ "%s: schedule %s release failed with non-terminal"
+ " InvalidRequestError (%s); re-raising",
+ log_context,
+ schedule_id,
+ message,
+ )
+ raise
+ logger.warning(
+ "%s: schedule %s not releasable (%s); treating as already released",
+ log_context,
+ schedule_id,
+ message,
+ )
+ return False
+
+
+async def _schedule_downgrade_at_period_end(
+ sub: stripe.Subscription,
+ new_price_id: str,
+ user_id: str,
+ tier: SubscriptionTier,
+) -> None:
+ """Create a Subscription Schedule that defers a tier change to period end.
+
+ Stripe's Subscription Schedule drives an existing subscription through a
+ series of phases. By keeping the current price for the remainder of the
+ billing period and switching to ``new_price_id`` afterwards, the user does
+ NOT receive an immediate proration charge and keeps their current tier
+ until period end.
+
+ Stripe allows at most one active schedule per subscription and rejects
+ ``SubscriptionSchedule.create`` if either (a) a schedule is already
+ attached to the subscription or (b) ``cancel_at_period_end=True`` is set.
+ Both conditions mean the user is overwriting a pending change they made
+ earlier (e.g. BUSINESS→FREE cancel, now switching to BUSINESS→PRO
+ downgrade). We clear the conflicting state first so the new schedule can
+ be created. These defensive reads serialize through Stripe's own atomic
+ operations — by the time modify/release returns, the subscription is in a
+ known-clean state for the subsequent create.
+ """
+ sub_id = sub.id
+ # ``sub["items"]`` (dict-item) rather than ``sub.items`` because the latter
+ # is shadowed by Python's dict.items() method on StripeObject.
+ items = sub["items"].data
+ if not items:
+ raise ValueError(f"Subscription {sub_id} has no items; cannot schedule")
+ price = items[0].price
+ current_price_id = price if isinstance(price, str) else price.id
+ period_start: int = sub["current_period_start"]
+ period_end: int = sub["current_period_end"]
+
+ if sub.cancel_at_period_end:
+ await stripe.Subscription.modify_async(sub_id, cancel_at_period_end=False)
+ logger.info(
+ "_schedule_downgrade_at_period_end: cleared cancel_at_period_end"
+ " on sub %s for user %s before scheduling downgrade",
+ sub_id,
+ user_id,
+ )
+ if sub.schedule:
+ existing_schedule_id = (
+ sub.schedule if isinstance(sub.schedule, str) else sub.schedule.id
+ )
+ await _release_schedule_ignoring_terminal(
+ existing_schedule_id, "_schedule_downgrade_at_period_end"
+ )
+
+ # Create + modify as a two-step transaction. If modify fails (network,
+ # Stripe 500) the created schedule is orphaned AND attached to the
+ # subscription, which blocks any future Stripe-side change until manually
+ # released. Roll back by releasing the orphan, then re-raise so the caller
+ # sees the original failure.
+ schedule = await stripe.SubscriptionSchedule.create_async(from_subscription=sub_id)
+ try:
+ await stripe.SubscriptionSchedule.modify_async(
+ schedule.id,
+ phases=[
+ {
+ "items": [{"price": current_price_id, "quantity": 1}],
+ "start_date": period_start,
+ "end_date": period_end,
+ "proration_behavior": "none",
+ },
+ {
+ "items": [{"price": new_price_id, "quantity": 1}],
+ "proration_behavior": "none",
+ },
+ ],
+ metadata={"user_id": user_id, "pending_tier": tier.value},
+ )
+ except stripe.StripeError:
+ logger.exception(
+ "_schedule_downgrade_at_period_end: modify failed for schedule %s"
+ " on sub %s user %s; attempting rollback release",
+ schedule.id,
+ sub_id,
+ user_id,
+ )
+ try:
+ await _release_schedule_ignoring_terminal(
+ schedule.id, "_schedule_downgrade_at_period_end_rollback"
+ )
+ except stripe.StripeError:
+ logger.exception(
+ "_schedule_downgrade_at_period_end: rollback release also failed"
+ " for orphaned schedule %s on sub %s user %s; manual cleanup"
+ " required",
+ schedule.id,
+ sub_id,
+ user_id,
+ )
+ raise
+ logger.info(
+ "modify_stripe_subscription_for_tier: scheduled sub %s downgrade for user %s → %s at %d",
+ sub_id,
+ user_id,
+ tier,
+ period_end,
+ )
+
+
async def modify_stripe_subscription_for_tier(
user_id: str, tier: SubscriptionTier
) -> bool:
- """Modify an existing Stripe subscription to a new paid tier using proration.
+ """Change a Stripe subscription to a new paid tier.
+
+ Upgrades (e.g. PRO→BUSINESS) apply immediately via ``stripe.Subscription.modify``
+ with ``proration_behavior="create_prorations"``: Stripe credits unused time on
+ the old plan and charges the pro-rated amount for the new plan in the same
+ billing cycle.
- For paid→paid tier changes (e.g. PRO↔BUSINESS), modifying the existing
- subscription is preferable to cancelling + creating a new one via Checkout:
- Stripe handles proration automatically, crediting unused time on the old plan
- and charging the pro-rated amount for the new plan in the same billing cycle.
+ Downgrades (e.g. BUSINESS→PRO) are deferred to the end of the current billing
+ period via a Stripe Subscription Schedule: the user keeps their current tier
+ for the time they already paid for, and the new tier takes effect when the
+ next invoice is generated. The DB tier flip happens via the webhook fired
+ when the schedule advances to its next phase.
Returns:
- True — a subscription was found and modified successfully.
+ True — a subscription was found and modified/scheduled successfully.
False — no active/trialing subscription exists (e.g. admin-granted tier or
first-time paid signup); caller should fall back to Checkout.
@@ -1437,41 +1666,262 @@ async def modify_stripe_subscription_for_tier(
if not price_id:
raise ValueError(f"No Stripe price ID configured for tier {tier}")
- # Guard: only proceed if the user already has a Stripe customer ID. Calling
- # get_stripe_customer_id for a user with no Stripe record (e.g. admin-granted tier)
- # would create an orphaned customer object if the subsequent Subscription.list call
- # fails. Return False early so the API layer falls back to Checkout instead.
user = await get_user_by_id(user_id)
if not user.stripe_customer_id:
return False
+ current_tier = user.subscription_tier or SubscriptionTier.FREE
- customer_id = user.stripe_customer_id
- for status in ("active", "trialing"):
- subscriptions = await run_in_threadpool(
- stripe.Subscription.list, customer=customer_id, status=status, limit=1
- )
- if not subscriptions.data:
- continue
- sub = subscriptions.data[0]
- sub_id = sub["id"]
- items = sub.get("items", {}).get("data", [])
- if not items:
- continue
- item_id = items[0]["id"]
- await run_in_threadpool(
- stripe.Subscription.modify,
- sub_id,
- items=[{"id": item_id, "price": price_id}],
- proration_behavior="create_prorations",
- )
+ sub = await _get_active_subscription(user.stripe_customer_id)
+ if sub is None:
+ return False
+ items = sub["items"].data
+ if not items:
+ return False
+ sub_id = sub.id
+
+ # Invalidate the cache unconditionally on exit (success OR failure): any
+ # Stripe mutation below — clearing cancel_at_period_end, releasing an old
+ # schedule, creating a new one — may have landed partially before an error
+ # was raised, and the cached pending-change state would otherwise go stale
+ # for up to 30s until the TTL expires.
+ try:
+ if is_tier_downgrade(current_tier, tier):
+ 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
+ # deferred change. Ignore terminal-state errors from release.
+ if sub.schedule:
+ existing_schedule_id = (
+ sub.schedule if isinstance(sub.schedule, str) else sub.schedule.id
+ )
+ await _release_schedule_ignoring_terminal(
+ existing_schedule_id, "modify_stripe_subscription_for_tier"
+ )
+
+ # If a paid→FREE cancel is pending (cancel_at_period_end=True), clear it
+ # as part of the upgrade — the user is explicitly choosing to stay on a
+ # paid tier. Without this, the sub would be upgraded AND still cancelled
+ # at period end, leaving a confusing dual state.
+ modify_kwargs: dict = {
+ "items": [{"id": items[0].id, "price": price_id}],
+ "proration_behavior": "create_prorations",
+ }
+ if sub.cancel_at_period_end:
+ modify_kwargs["cancel_at_period_end"] = False
+
+ await stripe.Subscription.modify_async(sub_id, **modify_kwargs)
+ # Flip the DB tier immediately. The customer.subscription.updated webhook
+ # will also fire and set it again — idempotent. Without this synchronous
+ # update, the UI refetches before the webhook lands and shows the old
+ # tier, making the upgrade look like a no-op to the user.
+ #
+ # Swallow DB-write exceptions here: Stripe is authoritative and the
+ # modify above already succeeded (the user has been charged). If the
+ # DB write fails and we re-raised, the API would return 5xx and the UI
+ # would surface a failed upgrade to a user who was already charged.
+ # The customer.subscription.updated webhook will reconcile the DB shortly.
+ #
+ # Only catch actual DB/connection failures — letting KeyError,
+ # AttributeError etc. propagate so programming errors surface in Sentry
+ # instead of being silently masked as benign DB-write-swallow events.
+ try:
+ await set_subscription_tier(user_id, tier)
+ except (PrismaError, ConnectionError, asyncio.TimeoutError):
+ logger.exception(
+ "modify_stripe_subscription_for_tier: Stripe modify on sub %s"
+ " succeeded for user %s → %s but DB tier flip failed; webhook"
+ " will reconcile",
+ sub_id,
+ user_id,
+ tier,
+ )
logger.info(
- "modify_stripe_subscription_for_tier: modified sub %s for user %s → %s",
+ "modify_stripe_subscription_for_tier: upgraded sub %s for user %s → %s",
sub_id,
user_id,
tier,
)
return True
- return False
+ finally:
+ get_pending_subscription_change.cache_delete(user_id)
+
+
+async def release_pending_subscription_schedule(user_id: str) -> bool:
+ """Cancel any pending subscription change (scheduled downgrade or cancellation).
+
+ Two pending-change mechanisms can be attached to a Stripe subscription:
+
+ - **Subscription Schedule** (paid→paid downgrade): ``stripe.SubscriptionSchedule.release``
+ detaches the schedule and lets the subscription continue on its current
+ phase's price.
+ - **cancel_at_period_end=True** (paid→FREE cancel): clearing that flag via
+ ``stripe.Subscription.modify`` keeps the subscription active indefinitely.
+
+ Returns True if a pending change was found and reverted, False otherwise.
+ """
+ user = await get_user_by_id(user_id)
+ if not user.stripe_customer_id:
+ return False
+
+ sub = await _get_active_subscription(user.stripe_customer_id)
+ if sub is None:
+ return False
+
+ sub_id = sub.id
+ did_anything = False
+ schedule_released = False
+ schedule_id: str | None = None
+ try:
+ if sub.schedule:
+ schedule_id = (
+ sub.schedule if isinstance(sub.schedule, str) else sub.schedule.id
+ )
+ schedule_released = await _release_schedule_ignoring_terminal(
+ schedule_id, "release_pending_subscription_schedule"
+ )
+ if schedule_released:
+ logger.info(
+ "release_pending_subscription_schedule: released schedule %s for user %s",
+ schedule_id,
+ user_id,
+ )
+ did_anything = True
+ if sub.cancel_at_period_end:
+ try:
+ await stripe.Subscription.modify_async(
+ sub_id, cancel_at_period_end=False
+ )
+ except stripe.StripeError:
+ if schedule_released:
+ logger.exception(
+ "release_pending_subscription_schedule: partial release"
+ " — schedule %s released but cancel_at_period_end clear"
+ " failed on sub %s for user %s; manual reconciliation"
+ " may be needed",
+ schedule_id,
+ sub_id,
+ user_id,
+ )
+ raise
+ did_anything = True
+ logger.info(
+ "release_pending_subscription_schedule: cleared cancel_at_period_end"
+ " on sub %s for user %s",
+ sub_id,
+ user_id,
+ )
+ finally:
+ if did_anything:
+ get_pending_subscription_change.cache_delete(user_id)
+ return did_anything
+
+
+@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``.
+
+ Reflects both Subscription Schedule phase transitions (paid→paid downgrade)
+ and ``cancel_at_period_end=True`` (paid→FREE cancel).
+
+ Cached for 30 seconds per user_id. *Why the cache exists:* this function
+ runs on every dashboard/home fetch and would otherwise fire
+ 2× Subscription.list + 1× Schedule.retrieve per page load. A busy user
+ polling the billing page would quickly brush up against Stripe's per-API
+ rate limits; the 30s TTL absorbs dashboard polling while being short
+ enough that the UI reconciles quickly after a downgrade / cancel action.
+
+ *Invalidation contract.* Every call-site that mutates Stripe state which
+ could change the pending-change answer MUST call
+ ``get_pending_subscription_change.cache_delete(user_id)`` so the UI never
+ shows a stale pending badge after a user-visible action. Current
+ invalidators (keep this list in sync when adding new mutators):
+
+ - ``set_subscription_tier`` — admin or webhook-driven tier flip.
+ - ``modify_stripe_subscription_for_tier`` — ``finally`` block (covers
+ upgrade path clear + downgrade-schedule create + any partial failure).
+ - ``release_pending_subscription_schedule`` — ``finally`` block when a
+ schedule release OR ``cancel_at_period_end`` clear succeeded.
+ - ``cancel_stripe_subscription`` — after scheduling period-end cancel.
+ - ``sync_subscription_from_stripe`` — webhook entry point.
+ - ``set_user_tier`` (``backend.copilot.rate_limit``) — admin tier override
+ invalidates any cached pending state keyed off the old tier.
+ """
+ user = await get_user_by_id(user_id)
+ if not user.stripe_customer_id:
+ # Short-circuit for users with no Stripe customer (admin-granted tiers,
+ # FREE-only users): skip the Stripe API calls entirely.
+ return None
+
+ pro_price, biz_price = await asyncio.gather(
+ get_subscription_price_id(SubscriptionTier.PRO),
+ get_subscription_price_id(SubscriptionTier.BUSINESS),
+ )
+ price_to_tier: dict[str, SubscriptionTier] = {}
+ if pro_price:
+ price_to_tier[pro_price] = SubscriptionTier.PRO
+ if biz_price:
+ price_to_tier[biz_price] = SubscriptionTier.BUSINESS
+ if not price_to_tier:
+ logger.warning(
+ "get_pending_subscription_change: no Stripe price IDs resolvable for"
+ " PRO/BUSINESS (LaunchDarkly fetch failed?); raising to bypass the"
+ " None cache so the next request retries fresh"
+ )
+ raise PendingChangeUnknown(
+ "Stripe price lookup failed; pending-change state cannot be determined"
+ )
+
+ sub = await _get_active_subscription(user.stripe_customer_id)
+ if sub is None:
+ return None
+ period_end = sub.current_period_end
+ if not isinstance(period_end, int):
+ return None
+ effective_at = datetime.fromtimestamp(period_end, tz=timezone.utc)
+ if sub.cancel_at_period_end:
+ return SubscriptionTier.FREE, effective_at
+ if not sub.schedule:
+ return None
+ schedule_id = sub.schedule if isinstance(sub.schedule, str) else sub.schedule.id
+ schedule = await stripe.SubscriptionSchedule.retrieve_async(schedule_id)
+ return _next_phase_tier_and_start(schedule, price_to_tier)
+
+
+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.
+
+ 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
+ schedule can have phase transitions at arbitrary timestamps.
+ """
+ now = int(time.time())
+ for phase in schedule.phases or []:
+ if not isinstance(phase.start_date, int) or phase.start_date <= now:
+ continue
+ # ``phase["items"]`` because ``phase.items`` is shadowed by dict.items().
+ items = phase["items"] or []
+ if not items:
+ continue
+ price = items[0].price
+ price_id = price if isinstance(price, str) else price.id
+ if price_id in price_to_tier:
+ return price_to_tier[price_id], datetime.fromtimestamp(
+ phase.start_date, tz=timezone.utc
+ )
+ logger.warning(
+ "next_phase_tier_and_start: unknown price %s on schedule %s",
+ price_id,
+ schedule.id,
+ )
+ return None
async def get_auto_top_up(user_id: str) -> AutoTopUpConfig:
@@ -1732,6 +2182,50 @@ async def sync_subscription_from_stripe(stripe_subscription: dict) -> None:
# cancel the old sub.
await _cleanup_stale_subscriptions(customer_id, new_sub_id)
await set_subscription_tier(user.id, tier)
+ # Tier changed — bust any cached pending-change view so the next
+ # dashboard fetch reflects the new state immediately.
+ get_pending_subscription_change.cache_delete(user.id)
+
+
+async def sync_subscription_schedule_from_stripe(stripe_schedule: dict) -> None:
+ """Sync the DB tier from a ``subscription_schedule.*`` webhook event.
+
+ Stripe fires ``subscription_schedule.released`` / ``.completed`` /
+ ``.updated`` when a schedule advances phases or is detached. The regular
+ ``customer.subscription.updated`` webhook with the new price covers the
+ phase transition in most cases, but listening to schedule events is a
+ safety net that also catches releases done via the Stripe dashboard.
+
+ The schedule payload doesn't carry the active price directly — it carries
+ a ``subscription`` id that we look up to get the current item.
+
+ Webhook-ordering safety: we deliberately funnel both event sources through
+ ``sync_subscription_from_stripe`` so they share one code path and one DB
+ write. That function is idempotent — it no-ops when ``current_tier ==
+ tier`` — so concurrent or out-of-order deliveries of
+ ``subscription_schedule.*`` and ``customer.subscription.updated`` converge
+ to the same DB state regardless of which arrives first.
+ """
+ # When a schedule is released, Stripe clears `subscription` and moves the id
+ # to `released_subscription`. Fall back to that so `.released` events — the
+ # main reason we listen to schedule webhooks as a safety net — are processed.
+ sub_id = stripe_schedule.get("subscription") or stripe_schedule.get(
+ "released_subscription"
+ )
+ if not isinstance(sub_id, str) or not sub_id:
+ logger.warning(
+ "sync_subscription_schedule_from_stripe: no 'subscription' id; skipping"
+ )
+ return
+ try:
+ sub = await stripe.Subscription.retrieve_async(sub_id)
+ except stripe.StripeError:
+ logger.warning(
+ "sync_subscription_schedule_from_stripe: failed to retrieve sub %s",
+ sub_id,
+ )
+ return
+ await sync_subscription_from_stripe(dict(sub))
async def handle_subscription_payment_failure(invoice: dict) -> None:
diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.py
index a9634afcb4..d38f71d09e 100644
--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py
+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py
@@ -12,11 +12,16 @@ from prisma.models import User
from backend.data.credit import (
cancel_stripe_subscription,
create_subscription_checkout,
+ get_pending_subscription_change,
get_proration_credit_cents,
handle_subscription_payment_failure,
+ is_tier_downgrade,
+ is_tier_upgrade,
modify_stripe_subscription_for_tier,
+ release_pending_subscription_schedule,
set_subscription_tier,
sync_subscription_from_stripe,
+ sync_subscription_schedule_from_stripe,
)
@@ -310,7 +315,11 @@ def _make_user_with_stripe(stripe_customer_id: str | None = "cus_123") -> MagicM
@pytest.mark.asyncio
async def test_cancel_stripe_subscription_cancels_active():
mock_subscriptions = MagicMock()
- mock_subscriptions.data = [{"id": "sub_abc123"}]
+ mock_subscriptions.data = [
+ stripe.Subscription.construct_from(
+ {"id": "sub_abc123", "schedule": None}, "sk_test"
+ )
+ ]
mock_subscriptions.has_more = False
with (
@@ -346,7 +355,14 @@ async def test_cancel_stripe_subscription_no_customer_id_returns_false():
async def test_cancel_stripe_subscription_multi_partial_failure():
"""First modify raises → error propagates and subsequent subs are not scheduled."""
mock_subscriptions = MagicMock()
- mock_subscriptions.data = [{"id": "sub_first"}, {"id": "sub_second"}]
+ mock_subscriptions.data = [
+ stripe.Subscription.construct_from(
+ {"id": "sub_first", "schedule": None}, "sk_test"
+ ),
+ stripe.Subscription.construct_from(
+ {"id": "sub_second", "schedule": None}, "sk_test"
+ ),
+ ]
mock_subscriptions.has_more = False
with (
@@ -428,7 +444,11 @@ async def test_cancel_stripe_subscription_cancels_trialing():
active_subs.data = []
active_subs.has_more = False
trialing_subs = MagicMock()
- trialing_subs.data = [{"id": "sub_trial_123"}]
+ trialing_subs.data = [
+ stripe.Subscription.construct_from(
+ {"id": "sub_trial_123", "schedule": None}, "sk_test"
+ )
+ ]
trialing_subs.has_more = False
def list_side_effect(*args, **kwargs):
@@ -454,10 +474,18 @@ async def test_cancel_stripe_subscription_cancels_trialing():
async def test_cancel_stripe_subscription_cancels_active_and_trialing():
"""Both active AND trialing subs present → both get scheduled for cancellation, no duplicates."""
active_subs = MagicMock()
- active_subs.data = [{"id": "sub_active_1"}]
+ active_subs.data = [
+ stripe.Subscription.construct_from(
+ {"id": "sub_active_1", "schedule": None}, "sk_test"
+ )
+ ]
active_subs.has_more = False
trialing_subs = MagicMock()
- trialing_subs.data = [{"id": "sub_trial_2"}]
+ trialing_subs.data = [
+ stripe.Subscription.construct_from(
+ {"id": "sub_trial_2", "schedule": None}, "sk_test"
+ )
+ ]
trialing_subs.has_more = False
def list_side_effect(*args, **kwargs):
@@ -480,6 +508,62 @@ async def test_cancel_stripe_subscription_cancels_active_and_trialing():
assert modified_ids == {"sub_active_1", "sub_trial_2"}
+async def test_cancel_stripe_subscription_releases_attached_schedule_first():
+ """Pre-existing Subscription Schedule must be released before cancel_at_period_end.
+
+ Stripe rejects ``modify(cancel_at_period_end=True)`` with HTTP 400 when the
+ subscription has an attached schedule (e.g. user queued a BUSINESS→PRO
+ downgrade and now clicks "Downgrade to FREE"). Without the pre-release,
+ the API handler would surface a 502 to the user.
+ """
+ mock_subscriptions = MagicMock()
+ mock_subscriptions.data = [
+ stripe.Subscription.construct_from(
+ {"id": "sub_abc123", "schedule": "sub_sched_abc"}, "sk_test"
+ )
+ ]
+ mock_subscriptions.has_more = False
+
+ call_order: list[str] = []
+
+ async def record_release(schedule_id):
+ call_order.append(f"release:{schedule_id}")
+
+ def record_modify(sub_id, **kwargs):
+ call_order.append(f"modify:{sub_id}:{kwargs}")
+
+ with (
+ patch(
+ "backend.data.credit.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=_make_user_with_stripe("cus_123"),
+ ),
+ patch(
+ "backend.data.credit.stripe.Subscription.list",
+ return_value=mock_subscriptions,
+ ),
+ patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.release_async",
+ new_callable=AsyncMock,
+ side_effect=record_release,
+ ) as mock_release,
+ patch(
+ "backend.data.credit.stripe.Subscription.modify",
+ side_effect=record_modify,
+ ) as mock_modify,
+ ):
+ await cancel_stripe_subscription("user-1")
+
+ mock_release.assert_awaited_once_with("sub_sched_abc")
+ mock_modify.assert_called_once_with("sub_abc123", cancel_at_period_end=True)
+ # Release must happen before modify, else Stripe returns 400.
+ assert call_order == [
+ "release:sub_sched_abc",
+ "modify:sub_abc123:{'cancel_at_period_end': True}",
+ ]
+
+
@pytest.mark.asyncio
async def test_get_proration_credit_cents_no_stripe_customer_returns_zero():
"""Admin-granted tier users without stripe_customer_id get 0 without creating a customer."""
@@ -878,7 +962,11 @@ async def test_cancel_stripe_subscription_raises_on_cancel_error():
import stripe as stripe_mod
mock_subscriptions = MagicMock()
- mock_subscriptions.data = [{"id": "sub_abc123"}]
+ mock_subscriptions.data = [
+ stripe.Subscription.construct_from(
+ {"id": "sub_abc123", "schedule": None}, "sk_test"
+ )
+ ]
mock_subscriptions.has_more = False
with (
@@ -1099,15 +1187,21 @@ async def test_handle_subscription_payment_failure_passes_invoice_id_as_transact
@pytest.mark.asyncio
async def test_modify_stripe_subscription_for_tier_modifies_existing_sub():
"""modify_stripe_subscription_for_tier calls Subscription.modify and returns True."""
- mock_sub = {
- "id": "sub_abc",
- "items": {"data": [{"id": "si_abc"}]},
- }
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_abc",
+ "items": {"data": [{"id": "si_abc"}]},
+ "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.FREE
with (
patch(
@@ -1121,12 +1215,18 @@ async def test_modify_stripe_subscription_for_tier_modifies_existing_sub():
return_value=mock_user,
),
patch(
- "backend.data.credit.stripe.Subscription.list",
+ "backend.data.credit.stripe.Subscription.list_async",
+ new_callable=AsyncMock,
return_value=mock_list,
),
patch(
- "backend.data.credit.stripe.Subscription.modify",
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
) as mock_modify,
+ patch(
+ "backend.data.credit.set_subscription_tier",
+ new_callable=AsyncMock,
+ ) as mock_set_tier,
):
result = await modify_stripe_subscription_for_tier(
"user-1", SubscriptionTier.PRO
@@ -1138,6 +1238,66 @@ async def test_modify_stripe_subscription_for_tier_modifies_existing_sub():
items=[{"id": "si_abc", "price": "price_pro_monthly"}],
proration_behavior="create_prorations",
)
+ mock_set_tier.assert_awaited_once_with("user-1", SubscriptionTier.PRO)
+
+
+async def test_modify_stripe_subscription_for_tier_clears_cancel_at_period_end_on_upgrade():
+ """Upgrading from a sub with cancel_at_period_end=True clears the flag so the
+ upgrade isn't silently cancelled at period end and the DB tier flips immediately."""
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_upgrading",
+ "items": {"data": [{"id": "si_abc"}]},
+ "schedule": None,
+ "cancel_at_period_end": True,
+ },
+ "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_biz_monthly",
+ ),
+ 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,
+ ) as mock_set_tier,
+ ):
+ result = await modify_stripe_subscription_for_tier(
+ "user-1", SubscriptionTier.BUSINESS
+ )
+
+ assert result is True
+ mock_modify.assert_called_once_with(
+ "sub_upgrading",
+ items=[{"id": "si_abc", "price": "price_biz_monthly"}],
+ proration_behavior="create_prorations",
+ cancel_at_period_end=False,
+ )
+ mock_set_tier.assert_awaited_once_with("user-1", SubscriptionTier.BUSINESS)
@pytest.mark.asyncio
@@ -1178,6 +1338,7 @@ async def test_modify_stripe_subscription_for_tier_returns_false_when_no_sub():
mock_user = MagicMock(spec=User)
mock_user.stripe_customer_id = "cus_abc"
+ mock_user.subscription_tier = SubscriptionTier.FREE
with (
patch(
@@ -1191,7 +1352,8 @@ async def test_modify_stripe_subscription_for_tier_returns_false_when_no_sub():
return_value=mock_user,
),
patch(
- "backend.data.credit.stripe.Subscription.list",
+ "backend.data.credit.stripe.Subscription.list_async",
+ new_callable=AsyncMock,
return_value=mock_list,
),
):
@@ -1212,3 +1374,1089 @@ async def test_modify_stripe_subscription_for_tier_raises_on_missing_price_id():
):
with pytest.raises(ValueError, match="No Stripe price ID configured"):
await modify_stripe_subscription_for_tier("user-1", SubscriptionTier.PRO)
+
+
+def test_tier_order_helpers():
+ assert is_tier_upgrade(SubscriptionTier.FREE, SubscriptionTier.PRO) is True
+ assert is_tier_upgrade(SubscriptionTier.PRO, SubscriptionTier.BUSINESS) is True
+ assert is_tier_upgrade(SubscriptionTier.BUSINESS, SubscriptionTier.PRO) is False
+ assert is_tier_downgrade(SubscriptionTier.BUSINESS, SubscriptionTier.PRO) is True
+ assert is_tier_downgrade(SubscriptionTier.PRO, SubscriptionTier.FREE) is True
+ assert is_tier_downgrade(SubscriptionTier.PRO, SubscriptionTier.BUSINESS) is False
+
+
+async def test_modify_stripe_subscription_for_tier_downgrade_creates_schedule():
+ """Paid→paid downgrade (BUSINESS→PRO) creates a Subscription Schedule rather than proration."""
+ import time as time_mod
+
+ now = int(time_mod.time())
+ period_end = now + 27 * 24 * 3600
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_biz",
+ "items": {"data": [{"id": "si_biz", "price": {"id": "price_biz_monthly"}}]},
+ "current_period_start": now - 3 * 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.BUSINESS
+
+ mock_schedule = stripe.SubscriptionSchedule.construct_from(
+ {"id": "sub_sched_1"}, "k"
+ )
+
+ with (
+ patch(
+ "backend.data.credit.get_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value="price_pro_monthly",
+ ),
+ 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
+ )
+
+ assert result is True
+ # Did NOT call Subscription.modify with proration (no immediate tier change).
+ mock_modify.assert_not_called()
+ mock_schedule_create.assert_called_once_with(from_subscription="sub_biz")
+ assert mock_schedule_modify.call_count == 1
+ _, kwargs = mock_schedule_modify.call_args
+ phases = kwargs["phases"]
+ assert phases[0]["items"][0]["price"] == "price_biz_monthly"
+ 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_for_tier_upgrade_immediate_proration():
+ """PRO→BUSINESS upgrade still uses Subscription.modify with proration (no schedule)."""
+ 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,
+ },
+ "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_biz_monthly",
+ ),
+ 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.BUSINESS
+ )
+
+ assert result is True
+ mock_modify.assert_called_once_with(
+ "sub_pro",
+ items=[{"id": "si_pro", "price": "price_biz_monthly"}],
+ proration_behavior="create_prorations",
+ )
+ mock_schedule_create.assert_not_called()
+
+
+async def test_release_pending_subscription_schedule_releases_downgrade_schedule():
+ """release_pending_subscription_schedule releases the Stripe schedule if one is attached."""
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_biz",
+ "schedule": "sub_sched_1",
+ "cancel_at_period_end": False,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ with (
+ 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.SubscriptionSchedule.release_async",
+ new_callable=AsyncMock,
+ ) as mock_release,
+ patch(
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
+ ) as mock_modify,
+ ):
+ result = await release_pending_subscription_schedule("user-1")
+
+ assert result is True
+ mock_release.assert_called_once_with("sub_sched_1")
+ mock_modify.assert_not_called()
+
+
+async def test_release_pending_subscription_schedule_clears_cancel_at_period_end():
+ """release_pending_subscription_schedule reverts a pending paid→FREE cancel."""
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro",
+ "schedule": None,
+ "cancel_at_period_end": True,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ with (
+ 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.SubscriptionSchedule.release_async",
+ new_callable=AsyncMock,
+ ) as mock_release,
+ patch(
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
+ ) as mock_modify,
+ ):
+ result = await release_pending_subscription_schedule("user-1")
+
+ assert result is True
+ mock_modify.assert_called_once_with("sub_pro", cancel_at_period_end=False)
+ mock_release.assert_not_called()
+
+
+async def test_release_pending_subscription_schedule_no_pending_change_returns_false():
+ """release_pending_subscription_schedule returns False when no schedule/cancel is set."""
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro",
+ "schedule": None,
+ "cancel_at_period_end": False,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ with (
+ 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,
+ ),
+ ):
+ result = await release_pending_subscription_schedule("user-1")
+
+ assert result is False
+
+
+async def test_release_pending_subscription_schedule_no_stripe_customer_returns_false():
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = None
+
+ with patch(
+ "backend.data.credit.get_user_by_id",
+ new_callable=AsyncMock,
+ return_value=mock_user,
+ ):
+ result = await release_pending_subscription_schedule("user-1")
+
+ assert result is False
+
+
+async def test_get_pending_subscription_change_cancel_at_period_end():
+ """cancel_at_period_end=True maps to pending FREE at current_period_end."""
+ import time as time_mod
+
+ get_pending_subscription_change.cache_clear() # type: ignore[attr-defined]
+
+ now = int(time_mod.time())
+ period_end = now + 10 * 24 * 3600
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro",
+ "current_period_end": period_end,
+ "cancel_at_period_end": True,
+ "schedule": None,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ async def mock_price_id(tier: SubscriptionTier) -> str | None:
+ 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,
+ ),
+ ):
+ result = await get_pending_subscription_change("user-1")
+
+ assert result is not None
+ pending_tier, effective_at = result
+ assert pending_tier == SubscriptionTier.FREE
+ assert int(effective_at.timestamp()) == period_end
+
+
+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]
+
+ now = int(time_mod.time())
+ period_end = now + 10 * 24 * 3600
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_biz",
+ "current_period_end": period_end,
+ "cancel_at_period_end": False,
+ "schedule": "sub_sched_1",
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_schedule = stripe.SubscriptionSchedule.construct_from(
+ {
+ "id": "sub_sched_1",
+ "phases": [
+ {
+ "start_date": now - 3 * 24 * 3600,
+ "end_date": period_end,
+ "items": [{"price": "price_biz_monthly"}],
+ },
+ {
+ "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) -> str | None:
+ 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-1")
+
+ assert result is not None
+ pending_tier, effective_at = result
+ assert pending_tier == SubscriptionTier.PRO
+ assert int(effective_at.timestamp()) == period_end
+
+
+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]
+
+ now = int(time_mod.time())
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro",
+ "current_period_end": now + 10 * 24 * 3600,
+ "cancel_at_period_end": False,
+ "schedule": None,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ async def mock_price_id(tier: SubscriptionTier) -> str | None:
+ return {
+ SubscriptionTier.PRO: "price_pro",
+ SubscriptionTier.BUSINESS: "price_biz",
+ }.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,
+ ),
+ ):
+ result = await get_pending_subscription_change("user-1")
+
+ assert result is None
+
+
+async def test_sync_subscription_schedule_from_stripe_retrieves_and_delegates():
+ """subscription_schedule.released triggers a sync via the active subscription object."""
+ stripe_schedule = {"id": "sub_sched_1", "subscription": "sub_pro"}
+ retrieved_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro",
+ "customer": "cus_abc",
+ "status": "active",
+ "items": {"data": [{"price": {"id": "price_pro_monthly"}}]},
+ },
+ "k",
+ )
+
+ with (
+ patch(
+ "backend.data.credit.stripe.Subscription.retrieve_async",
+ new_callable=AsyncMock,
+ return_value=retrieved_sub,
+ ) as mock_retrieve,
+ patch(
+ "backend.data.credit.sync_subscription_from_stripe",
+ new_callable=AsyncMock,
+ ) as mock_sync,
+ ):
+ await sync_subscription_schedule_from_stripe(stripe_schedule)
+
+ mock_retrieve.assert_called_once_with("sub_pro")
+ mock_sync.assert_awaited_once()
+ forwarded = mock_sync.call_args.args[0]
+ assert forwarded["id"] == "sub_pro"
+ assert forwarded["customer"] == "cus_abc"
+
+
+async def test_sync_subscription_schedule_from_stripe_uses_released_subscription_fallback():
+ """subscription_schedule.released events clear `subscription` and set
+ `released_subscription`; the sync handler must fall back to that id."""
+ stripe_schedule = {
+ "id": "sub_sched_1",
+ "subscription": None,
+ "released_subscription": "sub_pro_released",
+ }
+ retrieved_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro_released",
+ "customer": "cus_abc",
+ "status": "active",
+ "items": {"data": [{"price": {"id": "price_pro_monthly"}}]},
+ },
+ "k",
+ )
+
+ with (
+ patch(
+ "backend.data.credit.stripe.Subscription.retrieve_async",
+ new_callable=AsyncMock,
+ return_value=retrieved_sub,
+ ) as mock_retrieve,
+ patch(
+ "backend.data.credit.sync_subscription_from_stripe",
+ new_callable=AsyncMock,
+ ) as mock_sync,
+ ):
+ await sync_subscription_schedule_from_stripe(stripe_schedule)
+
+ mock_retrieve.assert_called_once_with("sub_pro_released")
+ mock_sync.assert_awaited_once()
+
+
+async def test_sync_subscription_schedule_from_stripe_missing_sub_id_returns():
+ """A schedule event with no 'subscription' field is logged and ignored."""
+ with patch(
+ "backend.data.credit.stripe.Subscription.retrieve_async",
+ new_callable=AsyncMock,
+ ) as mock_retrieve:
+ await sync_subscription_schedule_from_stripe({"id": "sub_sched_1"})
+ mock_retrieve.assert_not_called()
+
+
+async def test_sync_subscription_from_stripe_phase_transition_updates_tier():
+ """When a schedule advances phases, Stripe fires customer.subscription.updated with
+ the new price — the existing sync handler must update the DB tier accordingly."""
+ mock_user = _make_user(tier=SubscriptionTier.BUSINESS)
+ stripe_sub = {
+ "id": "sub_pro",
+ "customer": "cus_abc",
+ "status": "active",
+ # Phase advanced: price is now PRO (was BUSINESS before).
+ "items": {"data": [{"price": {"id": "price_pro_monthly"}}]},
+ }
+
+ async def mock_price_id(tier: SubscriptionTier) -> str | None:
+ if tier == SubscriptionTier.PRO:
+ return "price_pro_monthly"
+ if tier == SubscriptionTier.BUSINESS:
+ return "price_biz_monthly"
+ 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)
+
+
+async def test_release_schedule_idempotent_on_terminal_state():
+ """SubscriptionSchedule.release raising InvalidRequestError on a terminal-state
+ schedule is treated as success; we still continue to the cancel_at_period_end clear.
+ """
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_biz",
+ "schedule": "sub_sched_terminal",
+ "cancel_at_period_end": True,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ with (
+ 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.SubscriptionSchedule.release_async",
+ new_callable=AsyncMock,
+ side_effect=stripe.InvalidRequestError(
+ "Schedule has already been released",
+ param="schedule",
+ ),
+ ) as mock_release,
+ patch(
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
+ ) as mock_modify,
+ ):
+ result = await release_pending_subscription_schedule("user-1")
+
+ # Terminal-state release is treated as idempotent success; modify still runs.
+ assert result is True
+ mock_release.assert_called_once_with("sub_sched_terminal")
+ mock_modify.assert_called_once_with("sub_biz", cancel_at_period_end=False)
+
+
+async def test_schedule_downgrade_releases_existing_schedule():
+ """_schedule_downgrade_at_period_end releases any pre-existing schedule first."""
+ import time as time_mod
+
+ now = int(time_mod.time())
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_biz",
+ "schedule": "sub_sched_old",
+ "cancel_at_period_end": False,
+ "items": {"data": [{"id": "si_biz", "price": {"id": "price_biz_monthly"}}]},
+ "current_period_start": now - 3 * 24 * 3600,
+ "current_period_end": now + 27 * 24 * 3600,
+ },
+ "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.BUSINESS
+
+ mock_new_schedule = stripe.SubscriptionSchedule.construct_from(
+ {"id": "sub_sched_new"}, "k"
+ )
+
+ with (
+ patch(
+ "backend.data.credit.get_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value="price_pro_monthly",
+ ),
+ 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.release_async",
+ new_callable=AsyncMock,
+ ) as mock_release,
+ patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.create_async",
+ new_callable=AsyncMock,
+ return_value=mock_new_schedule,
+ ) as mock_create,
+ patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.modify_async",
+ new_callable=AsyncMock,
+ ),
+ ):
+ result = await modify_stripe_subscription_for_tier(
+ "user-1", SubscriptionTier.PRO
+ )
+
+ assert result is True
+ # Existing schedule released before creating the new one.
+ mock_release.assert_called_once_with("sub_sched_old")
+ mock_create.assert_called_once_with(from_subscription="sub_biz")
+ # cancel_at_period_end was False, so Subscription.modify should not be called.
+ mock_modify.assert_not_called()
+
+
+async def test_schedule_downgrade_clears_cancel_at_period_end():
+ """_schedule_downgrade_at_period_end clears cancel_at_period_end before scheduling."""
+ import time as time_mod
+
+ now = int(time_mod.time())
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_biz",
+ "schedule": None,
+ "cancel_at_period_end": True,
+ "items": {"data": [{"id": "si_biz", "price": {"id": "price_biz_monthly"}}]},
+ "current_period_start": now - 3 * 24 * 3600,
+ "current_period_end": now + 27 * 24 * 3600,
+ },
+ "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.BUSINESS
+
+ mock_new_schedule = stripe.SubscriptionSchedule.construct_from(
+ {"id": "sub_sched_new"}, "k"
+ )
+
+ with (
+ patch(
+ "backend.data.credit.get_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value="price_pro_monthly",
+ ),
+ 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_new_schedule,
+ ) as mock_create,
+ patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.modify_async",
+ new_callable=AsyncMock,
+ ),
+ ):
+ result = await modify_stripe_subscription_for_tier(
+ "user-1", SubscriptionTier.PRO
+ )
+
+ assert result is True
+ # cancel_at_period_end cleared before new schedule is created.
+ mock_modify.assert_called_once_with("sub_biz", cancel_at_period_end=False)
+ mock_create.assert_called_once_with(from_subscription="sub_biz")
+
+
+async def test_schedule_downgrade_rolls_back_orphan_on_modify_failure():
+ """If SubscriptionSchedule.modify fails after a successful create, the
+ orphaned schedule must be released so it doesn't stay attached and block
+ future changes. The original StripeError re-raises to the caller.
+ """
+ import time as time_mod
+
+ now = int(time_mod.time())
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_biz",
+ "schedule": None,
+ "cancel_at_period_end": False,
+ "items": {"data": [{"id": "si_biz", "price": {"id": "price_biz_monthly"}}]},
+ "current_period_start": now - 3 * 24 * 3600,
+ "current_period_end": now + 27 * 24 * 3600,
+ },
+ "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.BUSINESS
+
+ mock_new_schedule = stripe.SubscriptionSchedule.construct_from(
+ {"id": "sub_sched_new"}, "k"
+ )
+
+ with (
+ patch(
+ "backend.data.credit.get_subscription_price_id",
+ new_callable=AsyncMock,
+ return_value="price_pro_monthly",
+ ),
+ 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,
+ ),
+ patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.create_async",
+ new_callable=AsyncMock,
+ return_value=mock_new_schedule,
+ ) as mock_create,
+ patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.modify_async",
+ new_callable=AsyncMock,
+ side_effect=stripe.APIConnectionError("network down"),
+ ) as mock_schedule_modify,
+ patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.release_async",
+ new_callable=AsyncMock,
+ ) as mock_release,
+ ):
+ with pytest.raises(stripe.APIConnectionError):
+ await modify_stripe_subscription_for_tier("user-1", SubscriptionTier.PRO)
+
+ mock_create.assert_called_once_with(from_subscription="sub_biz")
+ mock_schedule_modify.assert_called_once()
+ # Rollback must release the freshly-created (and now orphaned) schedule
+ # id, not the pre-existing one (there was none here).
+ mock_release.assert_called_once_with("sub_sched_new")
+
+
+async def test_release_ignoring_terminal_reraises_non_terminal_error():
+ """_release_schedule_ignoring_terminal only swallows terminal-state errors.
+ Typos / wrong ids / 404s surface so bugs aren't silently masked.
+ """
+ from backend.data.credit import _release_schedule_ignoring_terminal
+
+ with patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.release_async",
+ new_callable=AsyncMock,
+ side_effect=stripe.InvalidRequestError(
+ "No such subscription_schedule: 'sub_sched_typo'",
+ param="schedule",
+ ),
+ ):
+ with pytest.raises(stripe.InvalidRequestError):
+ await _release_schedule_ignoring_terminal("sub_sched_typo", "test_context")
+
+
+async def test_release_ignoring_terminal_swallows_terminal_error():
+ """Terminal-state messages are treated as idempotent success and return False."""
+ from backend.data.credit import _release_schedule_ignoring_terminal
+
+ with patch(
+ "backend.data.credit.stripe.SubscriptionSchedule.release_async",
+ new_callable=AsyncMock,
+ side_effect=stripe.InvalidRequestError(
+ "Schedule has already been released",
+ param="schedule",
+ ),
+ ):
+ result = await _release_schedule_ignoring_terminal(
+ "sub_sched_done", "test_context"
+ )
+
+ assert result is False
+
+
+async def test_upgrade_releases_pending_schedule():
+ """modify_stripe_subscription_for_tier upgrade path releases attached schedule first."""
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_pro",
+ "schedule": "sub_sched_pending_downgrade",
+ "cancel_at_period_end": False,
+ "items": {"data": [{"id": "si_pro", "price": {"id": "price_pro_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_biz_monthly",
+ ),
+ 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.release_async",
+ new_callable=AsyncMock,
+ ) as mock_release,
+ patch(
+ "backend.data.credit.set_subscription_tier",
+ new_callable=AsyncMock,
+ ),
+ ):
+ result = await modify_stripe_subscription_for_tier(
+ "user-1", SubscriptionTier.BUSINESS
+ )
+
+ assert result is True
+ # Pending schedule released before the upgrade modify call.
+ mock_release.assert_called_once_with("sub_sched_pending_downgrade")
+ mock_modify.assert_called_once_with(
+ "sub_pro",
+ items=[{"id": "si_pro", "price": "price_biz_monthly"}],
+ proration_behavior="create_prorations",
+ )
+
+
+async def test_next_phase_tier_and_start_logs_unknown_price(caplog):
+ """_next_phase_tier_and_start emits a warning when the next-phase price is unmapped."""
+ import logging
+ import time as time_mod
+
+ from backend.data.credit import _next_phase_tier_and_start
+
+ now = int(time_mod.time())
+ schedule = stripe.SubscriptionSchedule.construct_from(
+ {
+ "id": "sub_sched_unknown",
+ "phases": [
+ {
+ "start_date": now - 3 * 24 * 3600,
+ "end_date": now + 27 * 24 * 3600,
+ "items": [{"price": "price_current"}],
+ },
+ {
+ "start_date": now + 27 * 24 * 3600,
+ "items": [{"price": "price_unknown"}],
+ },
+ ],
+ },
+ "k",
+ )
+ price_to_tier = {"price_pro_monthly": SubscriptionTier.PRO}
+
+ with caplog.at_level(logging.WARNING, logger="backend.data.credit"):
+ result = _next_phase_tier_and_start(schedule, price_to_tier)
+
+ assert result is None
+ assert any(
+ "next_phase_tier_and_start: unknown price price_unknown" in record.message
+ and "sub_sched_unknown" in record.message
+ for record in caplog.records
+ )
+
+
+async def test_get_pending_subscription_change_raises_when_price_lookups_fail():
+ """When both LD price lookups return None, raise PendingChangeUnknown so the
+ @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]
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ async def mock_price_id(tier: SubscriptionTier) -> str | None:
+ 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,
+ ),
+ pytest.raises(PendingChangeUnknown),
+ ):
+ await get_pending_subscription_change("user-price-fail")
+
+
+async def test_release_pending_subscription_schedule_invalidates_cache_on_partial_failure():
+ """If schedule.release succeeds but cancel_at_period_end clear fails, the
+ cache must still be invalidated — otherwise the UI shows a stale pending
+ banner for up to 30s even though the schedule was actually released."""
+ get_pending_subscription_change.cache_clear() # type: ignore[attr-defined]
+
+ mock_user = MagicMock()
+ mock_user.stripe_customer_id = "cus_abc"
+
+ import time as time_mod
+
+ mock_sub = stripe.Subscription.construct_from(
+ {
+ "id": "sub_mixed",
+ "schedule": "sub_sched_to_release",
+ "cancel_at_period_end": True,
+ "current_period_end": int(time_mod.time()) + 10 * 24 * 3600,
+ },
+ "k",
+ )
+ mock_list = MagicMock()
+ mock_list.data = [mock_sub]
+
+ with (
+ 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.SubscriptionSchedule.release_async",
+ new_callable=AsyncMock,
+ return_value=MagicMock(),
+ ),
+ patch(
+ "backend.data.credit.stripe.Subscription.modify_async",
+ new_callable=AsyncMock,
+ side_effect=stripe.APIConnectionError("transient Stripe error"),
+ ),
+ patch.object(
+ get_pending_subscription_change, "cache_delete"
+ ) as mock_cache_delete,
+ ):
+ with pytest.raises(stripe.APIConnectionError):
+ await release_pending_subscription_schedule("user-partial")
+
+ mock_cache_delete.assert_called_once_with("user-partial")
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx
index 58a4b9d58b..d8aab67b22 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/SubscriptionTierSection.tsx
@@ -4,42 +4,14 @@ import { Button } from "@/components/ui/button";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import { useSubscriptionTierSection } from "./useSubscriptionTierSection";
-
-type TierInfo = {
- key: string;
- label: string;
- multiplier: string;
- description: string;
-};
-
-const TIERS: TierInfo[] = [
- {
- key: "FREE",
- label: "Free",
- multiplier: "1x",
- description: "Base AutoPilot capacity with standard rate limits",
- },
- {
- key: "PRO",
- label: "Pro",
- multiplier: "5x",
- description: "5x AutoPilot capacity — run 5× more tasks per day/week",
- },
- {
- key: "BUSINESS",
- label: "Business",
- multiplier: "20x",
- description: "20x AutoPilot capacity — ideal for teams and heavy workloads",
- },
-];
-
-const TIER_ORDER = ["FREE", "PRO", "BUSINESS", "ENTERPRISE"];
-
-function formatCost(cents: number, tierKey: string): string {
- if (tierKey === "FREE") return "Free";
- if (cents === 0) return "Pricing available soon";
- return `$${(cents / 100).toFixed(2)}/mo`;
-}
+import { PendingChangeBanner } from "./components/PendingChangeBanner/PendingChangeBanner";
+import {
+ TIERS,
+ TIER_ORDER,
+ formatCost,
+ formatPendingDate,
+ getTierLabel,
+} from "./helpers";
export function SubscriptionTierSection() {
const {
@@ -55,10 +27,14 @@ export function SubscriptionTierSection() {
isPaymentEnabled,
changeTier,
handleTierChange,
+ cancelPendingChange,
} = useSubscriptionTierSection();
const [confirmDowngradeTo, setConfirmDowngradeTo] = useState<string | null>(
null,
);
+ const [confirmReplacePendingTo, setConfirmReplacePendingTo] = useState<
+ string | null
+ >(null);
if (isLoading) {
return (
@@ -115,6 +91,34 @@ export function SubscriptionTierSection() {
await changeTier(tier);
}
+ async function confirmReplacePending() {
+ if (!confirmReplacePendingTo) return;
+ const tier = confirmReplacePendingTo;
+ setConfirmReplacePendingTo(null);
+ handleTierChange(tier, currentTier, setConfirmDowngradeTo);
+ }
+
+ const pendingTierFromSubscription = subscription.pending_tier ?? null;
+ const hasPendingChange =
+ pendingTierFromSubscription !== null &&
+ pendingTierFromSubscription !== currentTier;
+
+ function onTierButtonClick(targetTierKey: string) {
+ // If a pending change is queued and the user clicks a DIFFERENT non-current,
+ // non-pending tier, surface a confirmation so they don't silently overwrite
+ // their own scheduled change. The on-card button for the pending tier itself
+ // is already disabled; the primary cancel path is the banner.
+ if (
+ hasPendingChange &&
+ targetTierKey !== pendingTierFromSubscription &&
+ targetTierKey !== currentTier
+ ) {
+ setConfirmReplacePendingTo(targetTierKey);
+ return;
+ }
+ handleTierChange(targetTierKey, currentTier, setConfirmDowngradeTo);
+ }
+
return (
<div className="space-y-4">
<h3 className="text-lg font-medium">Subscription Plan</h3>
@@ -128,6 +132,16 @@ export function SubscriptionTierSection() {
</p>
)}
+ {hasPendingChange && pendingTierFromSubscription ? (
+ <PendingChangeBanner
+ currentTier={currentTier}
+ pendingTier={pendingTierFromSubscription}
+ pendingEffectiveAt={subscription.pending_tier_effective_at}
+ onKeepCurrent={() => void cancelPendingChange()}
+ isBusy={isPending}
+ />
+ ) : null}
+
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
{TIERS.map((tier) => {
const isCurrent = currentTier === tier.key;
@@ -137,6 +151,8 @@ export function SubscriptionTierSection() {
const isUpgrade = targetIdx > currentIdx;
const isDowngrade = targetIdx < currentIdx;
const isThisPending = pendingTier === tier.key;
+ const isScheduledTier =
+ hasPendingChange && pendingTierFromSubscription === tier.key;
return (
<div
@@ -171,22 +187,18 @@ export function SubscriptionTierSection() {
<Button
className="w-full"
variant={isUpgrade ? "default" : "outline"}
- disabled={isPending}
- onClick={() =>
- handleTierChange(
- tier.key,
- currentTier,
- setConfirmDowngradeTo,
- )
- }
+ disabled={isPending || isScheduledTier}
+ onClick={() => onTierButtonClick(tier.key)}
>
{isThisPending
? "Updating..."
- : isUpgrade
- ? `Upgrade to ${tier.label}`
- : isDowngrade
- ? `Downgrade to ${tier.label}`
- : `Switch to ${tier.label}`}
+ : isScheduledTier
+ ? "Scheduled"
+ : isUpgrade
+ ? `Upgrade to ${tier.label}`
+ : isDowngrade
+ ? `Downgrade to ${tier.label}`
+ : `Switch to ${tier.label}`}
</Button>
)}
</div>
@@ -196,9 +208,9 @@ export function SubscriptionTierSection() {
{currentTier !== "FREE" && isPaymentEnabled && (
<p className="text-sm text-neutral-500">
- Your subscription is managed through Stripe. Upgrades and paid-tier
- changes take effect immediately; downgrades to Free are scheduled for
- the end of the current billing period.
+ Your subscription is managed through Stripe. Upgrades take effect
+ immediately. Downgrades take effect at the end of your current billing
+ period.
</p>
)}
@@ -215,7 +227,7 @@ export function SubscriptionTierSection() {
<p className="text-sm text-neutral-600 dark:text-neutral-400">
{confirmDowngradeTo === "FREE"
? "Downgrading to Free will schedule your subscription to cancel at the end of your current billing period. You keep your current plan until then."
- : `Switching to ${TIERS.find((t) => t.key === confirmDowngradeTo)?.label ?? confirmDowngradeTo} will take effect immediately.`}{" "}
+ : `Switching to ${TIERS.find((t) => t.key === confirmDowngradeTo)?.label ?? confirmDowngradeTo} will take effect at the end of your current billing period. You keep your current plan until then.`}{" "}
Are you sure?
</p>
<Dialog.Footer>
@@ -235,6 +247,42 @@ export function SubscriptionTierSection() {
</Dialog.Content>
</Dialog>
+ <Dialog
+ title="Replace pending change?"
+ controlled={{
+ isOpen: !!confirmReplacePendingTo,
+ set: (open) => {
+ if (!open) setConfirmReplacePendingTo(null);
+ },
+ }}
+ >
+ <Dialog.Content>
+ <p className="text-sm text-neutral-600 dark:text-neutral-400">
+ You have a pending change to{" "}
+ {getTierLabel(pendingTierFromSubscription ?? "")}
+ {subscription.pending_tier_effective_at
+ ? ` scheduled for ${formatPendingDate(subscription.pending_tier_effective_at)}`
+ : ""}
+ . Switching to {getTierLabel(confirmReplacePendingTo ?? "")} will
+ replace it. Continue?
+ </p>
+ <Dialog.Footer>
+ <Button
+ variant="outline"
+ onClick={() => setConfirmReplacePendingTo(null)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => void confirmReplacePending()}
+ >
+ Replace pending change
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+
<Dialog
title="Confirm Upgrade"
controlled={{
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
index 086c383337..f9a7f01cd9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
@@ -71,17 +71,23 @@ function makeSubscription({
monthlyCost = 0,
tierCosts = { FREE: 0, PRO: 1999, BUSINESS: 4999, ENTERPRISE: 0 },
prorationCreditCents = 0,
+ pendingTier = null as string | null,
+ pendingTierEffectiveAt = null as Date | string | null,
}: {
tier?: string;
monthlyCost?: number;
tierCosts?: Record<string, number>;
prorationCreditCents?: number;
+ pendingTier?: string | null;
+ pendingTierEffectiveAt?: Date | string | null;
} = {}) {
return {
tier,
monthly_cost: monthlyCost,
tier_costs: tierCosts,
proration_credit_cents: prorationCreditCents,
+ pending_tier: pendingTier,
+ pending_tier_effective_at: pendingTierEffectiveAt,
};
}
@@ -92,6 +98,7 @@ function setupMocks({
mutateFn = vi.fn().mockResolvedValue({ status: 200, data: { url: "" } }),
isPending = false,
variables = undefined as { data?: { tier?: string } } | undefined,
+ refetchFn = vi.fn(),
} = {}) {
// The hook uses select: (data) => (data.status === 200 ? data.data : null)
// so the data value returned by the hook is already the transformed subscription object.
@@ -100,13 +107,14 @@ function setupMocks({
data: subscription,
isLoading,
error: queryError,
- refetch: vi.fn(),
+ refetch: refetchFn,
});
mockUseUpdateSubscriptionTier.mockReturnValue({
mutateAsync: mutateFn,
isPending,
variables,
});
+ return { refetchFn, mutateFn };
}
afterEach(() => {
@@ -355,4 +363,229 @@ describe("SubscriptionTierSection", () => {
// No toast should fire — the user simply abandoned checkout
expect(mockToast).not.toHaveBeenCalled();
});
+
+ it("renders pending-change banner when pending_tier is set", () => {
+ setupMocks({
+ subscription: makeSubscription({
+ tier: "BUSINESS",
+ pendingTier: "PRO",
+ pendingTierEffectiveAt: new Date("2026-11-15T00:00:00Z"),
+ }),
+ });
+ render(<SubscriptionTierSection />);
+ expect(screen.getByText(/scheduled to downgrade to/i)).toBeDefined();
+ // Banner "Keep Business" button — the only Keep button, since the on-card
+ // duplicate was removed in favour of the banner.
+ expect(
+ screen.getAllByRole("button", { name: /keep business/i }),
+ ).toHaveLength(1);
+ });
+
+ it("does not render pending-change banner when pending_tier is null", () => {
+ setupMocks({
+ subscription: makeSubscription({ tier: "BUSINESS", pendingTier: null }),
+ });
+ render(<SubscriptionTierSection />);
+ expect(screen.queryByText(/scheduled to downgrade/i)).toBeNull();
+ expect(screen.queryByRole("button", { name: /keep business/i })).toBeNull();
+ });
+
+ it("clicking Keep [CurrentTier] in banner submits a same-tier update and refetches", async () => {
+ // The cancel-pending route was collapsed into POST /credits/subscription as
+ // a same-tier request. Clicking "Keep BUSINESS" calls useUpdateSubscriptionTier
+ // with tier === current tier so the backend releases any pending schedule.
+ const mutateFn = vi
+ .fn()
+ .mockResolvedValue({ status: 200, data: { url: "", tier: "BUSINESS" } });
+ const refetchFn = vi.fn();
+ setupMocks({
+ subscription: makeSubscription({
+ tier: "BUSINESS",
+ pendingTier: "PRO",
+ pendingTierEffectiveAt: new Date("2026-11-15T00:00:00Z"),
+ }),
+ mutateFn,
+ refetchFn,
+ });
+ render(<SubscriptionTierSection />);
+
+ fireEvent.click(screen.getByRole("button", { name: /keep business/i }));
+
+ await waitFor(() => {
+ expect(mutateFn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({ tier: "BUSINESS" }),
+ }),
+ );
+ expect(refetchFn).toHaveBeenCalled();
+ });
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Pending subscription change cancelled.",
+ }),
+ );
+ });
+
+ it("uses end-of-period copy for paid→paid downgrade confirmation", () => {
+ setupMocks({ subscription: makeSubscription({ tier: "BUSINESS" }) });
+ render(<SubscriptionTierSection />);
+
+ fireEvent.click(screen.getByRole("button", { name: /downgrade to pro/i }));
+
+ const dialog = screen.getByRole("dialog");
+ expect(dialog.textContent).toMatch(
+ /switching to pro will take effect at the end of your current billing period/i,
+ );
+ expect(dialog.textContent).toMatch(
+ /you keep your current plan until then/i,
+ );
+ expect(dialog.textContent).not.toMatch(/take effect immediately/i);
+ });
+
+ it("shows destructive toast, tierError and still refetches when cancel-pending fails", async () => {
+ // The catch branch inside cancelPendingChange is load-bearing: it surfaces
+ // the error to the user AND re-issues a refetch so the UI reconciles if
+ // the server actually succeeded (webhook delivered after our client-side
+ // error).
+ const mutateFn = vi
+ .fn()
+ .mockRejectedValue(new Error("Stripe webhook failed"));
+ const refetchFn = vi.fn();
+ setupMocks({
+ subscription: makeSubscription({
+ tier: "BUSINESS",
+ pendingTier: "PRO",
+ pendingTierEffectiveAt: new Date("2026-11-15T00:00:00Z"),
+ }),
+ mutateFn,
+ refetchFn,
+ });
+ render(<SubscriptionTierSection />);
+
+ const keepButtons = screen.getAllByRole("button", {
+ name: /keep business/i,
+ });
+ fireEvent.click(keepButtons[0]);
+
+ await waitFor(() => {
+ expect(screen.getByRole("alert")).toBeDefined();
+ expect(screen.getByText(/stripe webhook failed/i)).toBeDefined();
+ });
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Failed to cancel pending change",
+ variant: "destructive",
+ }),
+ );
+ expect(refetchFn).toHaveBeenCalled();
+ });
+
+ it("disables the tier button that matches the pending tier so users can't overwrite their own scheduled change by mis-click", () => {
+ // User is on BUSINESS and has a pending downgrade to PRO. The "Downgrade
+ // to Pro" button must be disabled + labelled "Scheduled" so the primary
+ // cancel path stays the banner. Other tier buttons (FREE here) remain
+ // clickable — the user can still overwrite their pending change by
+ // picking a different target; backend handles that.
+ setupMocks({
+ subscription: makeSubscription({
+ tier: "BUSINESS",
+ pendingTier: "PRO",
+ pendingTierEffectiveAt: new Date("2026-11-15T00:00:00Z"),
+ }),
+ });
+ render(<SubscriptionTierSection />);
+
+ const scheduledBtn = screen.getByRole("button", { name: /scheduled/i });
+ expect(scheduledBtn).toBeDefined();
+ expect((scheduledBtn as HTMLButtonElement).disabled).toBe(true);
+
+ // The non-pending tier (FREE) button is still clickable.
+ const freeBtn = screen.getByRole("button", { name: /downgrade to free/i });
+ expect((freeBtn as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it("shows replace-pending dialog when clicking a non-pending tier while a pending change exists, and fires the mutation after confirm", async () => {
+ // User is on BUSINESS with a pending downgrade to PRO. Clicking FREE (a
+ // tier that is neither current nor the pending target) must NOT silently
+ // overwrite the pending schedule — it must open a confirmation dialog.
+ // Only after the user explicitly confirms should changeTier (→ its own
+ // downgrade confirm for paid→FREE) fire.
+ const mutateFn = vi
+ .fn()
+ .mockResolvedValue({ status: 200, data: { url: "" } });
+ setupMocks({
+ subscription: makeSubscription({
+ tier: "BUSINESS",
+ pendingTier: "PRO",
+ pendingTierEffectiveAt: new Date("2026-11-15T00:00:00Z"),
+ }),
+ mutateFn,
+ });
+ render(<SubscriptionTierSection />);
+
+ // Clicking FREE while PRO is pending surfaces the replace-pending dialog
+ // before anything mutates.
+ fireEvent.click(screen.getByRole("button", { name: /downgrade to free/i }));
+ expect(screen.getByRole("dialog")).toBeDefined();
+ expect(screen.getByText(/replace pending change/i)).toBeDefined();
+ expect(mutateFn).not.toHaveBeenCalled();
+
+ // Confirm the replace: the replace-pending dialog closes and the
+ // downgrade-to-FREE dialog takes over (because FREE is a downgrade).
+ fireEvent.click(
+ screen.getByRole("button", { name: /replace pending change/i }),
+ );
+
+ // Now the "Confirm Downgrade" dialog should be open — confirm it to fire
+ // the mutation.
+ fireEvent.click(screen.getByRole("button", { name: /confirm downgrade/i }));
+
+ await waitFor(() => {
+ expect(mutateFn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({ tier: "FREE" }),
+ }),
+ );
+ });
+ });
+
+ it("dismisses replace-pending dialog on Cancel without mutating", () => {
+ const mutateFn = vi
+ .fn()
+ .mockResolvedValue({ status: 200, data: { url: "" } });
+ setupMocks({
+ subscription: makeSubscription({
+ tier: "BUSINESS",
+ pendingTier: "PRO",
+ pendingTierEffectiveAt: new Date("2026-11-15T00:00:00Z"),
+ }),
+ mutateFn,
+ });
+ render(<SubscriptionTierSection />);
+
+ fireEvent.click(screen.getByRole("button", { name: /downgrade to free/i }));
+ expect(screen.getByRole("dialog")).toBeDefined();
+
+ fireEvent.click(screen.getByRole("button", { name: /^cancel$/i }));
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(mutateFn).not.toHaveBeenCalled();
+ });
+
+ it("renders FREE cancellation copy in banner when pending_tier is FREE", () => {
+ setupMocks({
+ subscription: makeSubscription({
+ tier: "BUSINESS",
+ pendingTier: "FREE",
+ pendingTierEffectiveAt: new Date("2026-05-15T00:00:00Z"),
+ }),
+ });
+ render(<SubscriptionTierSection />);
+ // Cancellation copy — distinct from the generic downgrade phrasing.
+ expect(
+ screen.getByText(/scheduled to cancel your subscription on/i),
+ ).toBeDefined();
+ expect(screen.getByText(/May 15, 2026/)).toBeDefined();
+ // Must NOT render the "downgrade to" phrasing on FREE cancellation.
+ expect(screen.queryByText(/scheduled to downgrade to/i)).toBeNull();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/components/PendingChangeBanner/PendingChangeBanner.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/components/PendingChangeBanner/PendingChangeBanner.tsx
new file mode 100644
index 0000000000..0088ad7666
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/components/PendingChangeBanner/PendingChangeBanner.tsx
@@ -0,0 +1,60 @@
+import { Button } from "@/components/ui/button";
+import { formatPendingDate, getTierLabel } from "../../helpers";
+
+interface Props {
+ currentTier: string;
+ pendingTier: string;
+ pendingEffectiveAt: Date | string | null | undefined;
+ onKeepCurrent: () => void;
+ isBusy: boolean;
+}
+
+export function PendingChangeBanner({
+ currentTier,
+ pendingTier,
+ pendingEffectiveAt,
+ onKeepCurrent,
+ isBusy,
+}: Props) {
+ // Backend invariant: pending_tier_effective_at is always populated when
+ // pending_tier is set. Bail early if the date is missing so the sentence
+ // always reads with a date instead of a null-fallback branch.
+ if (!pendingEffectiveAt) return null;
+
+ const pendingLabel = getTierLabel(pendingTier);
+ const currentLabel = getTierLabel(currentTier);
+ const dateText = formatPendingDate(pendingEffectiveAt);
+
+ const isCancellation = pendingTier === "FREE";
+
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ className="flex flex-col gap-2 rounded-md border border-violet-500 bg-violet-50 px-3 py-2 text-sm text-violet-800 sm:flex-row sm:items-center sm:justify-between"
+ >
+ <p>
+ {isCancellation ? (
+ <>
+ Scheduled to cancel your subscription on{" "}
+ <span className="font-semibold">{dateText}</span>.
+ </>
+ ) : (
+ <>
+ Scheduled to downgrade to{" "}
+ <span className="font-semibold">{pendingLabel}</span> on{" "}
+ <span className="font-semibold">{dateText}</span>.
+ </>
+ )}
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={isBusy}
+ onClick={onKeepCurrent}
+ >
+ {isBusy ? "Cancelling..." : `Keep ${currentLabel}`}
+ </Button>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts
new file mode 100644
index 0000000000..fde4674a8b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/helpers.ts
@@ -0,0 +1,54 @@
+export interface TierInfo {
+ key: string;
+ label: string;
+ multiplier: string;
+ description: string;
+}
+
+export const TIERS: TierInfo[] = [
+ {
+ key: "FREE",
+ label: "Free",
+ multiplier: "1x",
+ description: "Base AutoPilot capacity with standard rate limits",
+ },
+ {
+ key: "PRO",
+ label: "Pro",
+ multiplier: "5x",
+ description: "5x AutoPilot capacity — run 5× more tasks per day/week",
+ },
+ {
+ key: "BUSINESS",
+ label: "Business",
+ multiplier: "20x",
+ description: "20x AutoPilot capacity — ideal for teams and heavy workloads",
+ },
+];
+
+export const TIER_ORDER = ["FREE", "PRO", "BUSINESS", "ENTERPRISE"];
+
+export function formatCost(cents: number, tierKey: string): string {
+ if (tierKey === "FREE") return "Free";
+ if (cents === 0) return "Pricing available soon";
+ return `$${(cents / 100).toFixed(2)}/mo`;
+}
+
+export function getTierLabel(tierKey: string): string {
+ return (
+ TIERS.find((t) => t.key === tierKey)?.label ??
+ tierKey.charAt(0) + tierKey.slice(1).toLowerCase()
+ );
+}
+
+export function formatPendingDate(value: Date | string): string {
+ const date = value instanceof Date ? value : new Date(value);
+ // Pin to en-US so SSR and CSR produce the same string — passing `undefined`
+ // picks up the server's locale during prerender and the browser's locale on
+ // hydration, which triggers a React hydration mismatch warning.
+ return date.toLocaleDateString("en-US", {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ });
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts
index 862551c7e3..d51a2a6051 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts
@@ -117,6 +117,47 @@ export function useSubscriptionTierSection() {
await changeTier(tier);
}
+ async function cancelPendingChange() {
+ if (!subscription) return;
+ setTierError(null);
+ try {
+ // "Stay on my current tier" is a same-tier POST: the backend collapses
+ // cancel-pending into update-tier and releases any pending schedule.
+ // success_url/cancel_url are unused in this branch (no Stripe Checkout
+ // is created) but are sent to satisfy the request schema.
+ await doUpdateTier({
+ data: {
+ tier: subscription.tier as SubscriptionTierRequestTier,
+ success_url: `${window.location.origin}${window.location.pathname}`,
+ cancel_url: `${window.location.origin}${window.location.pathname}`,
+ },
+ });
+ await refetch();
+ toast({
+ title: "Pending subscription change cancelled.",
+ });
+ } catch (e: unknown) {
+ const msg =
+ e instanceof Error
+ ? e.message
+ : "Failed to cancel pending subscription change";
+ setTierError(msg);
+ toast({
+ title: "Failed to cancel pending change",
+ description: msg,
+ variant: "destructive",
+ });
+ // Refetch on error so the UI reconciles if the server actually
+ // succeeded (e.g. webhook delivered after our client-side error).
+ // Swallow refetch errors — we already have the primary error for display.
+ try {
+ await refetch();
+ } catch {
+ // intentional
+ }
+ }
+ }
+
const pendingTier =
isPending && variables?.data?.tier ? variables.data.tier : null;
@@ -133,5 +174,6 @@ export function useSubscriptionTierSection() {
isPaymentEnabled,
changeTier,
handleTierChange,
+ cancelPendingChange,
};
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 920348db25..f20f34a805 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -2470,7 +2470,7 @@
},
"post": {
"tags": ["v1", "credits"],
- "summary": "Start a Stripe Checkout session to upgrade subscription tier",
+ "summary": "Update subscription tier or start a Stripe Checkout session",
"operationId": "updateSubscriptionTier",
"requestBody": {
"content": {
@@ -2488,7 +2488,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/SubscriptionCheckoutResponse"
+ "$ref": "#/components/schemas/SubscriptionStatusResponse"
}
}
}
@@ -14208,12 +14208,6 @@
"enum": ["DRAFT", "PENDING", "APPROVED", "REJECTED"],
"title": "SubmissionStatus"
},
- "SubscriptionCheckoutResponse": {
- "properties": { "url": { "type": "string", "title": "Url" } },
- "type": "object",
- "required": ["url"],
- "title": "SubscriptionCheckoutResponse"
- },
"SubscriptionStatusResponse": {
"properties": {
"tier": {
@@ -14230,6 +14224,26 @@
"proration_credit_cents": {
"type": "integer",
"title": "Proration Credit Cents"
+ },
+ "pending_tier": {
+ "anyOf": [
+ { "type": "string", "enum": ["FREE", "PRO", "BUSINESS"] },
+ { "type": "null" }
+ ],
+ "title": "Pending Tier"
+ },
+ "pending_tier_effective_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Pending Tier Effective At"
+ },
+ "url": {
+ "type": "string",
+ "title": "Url",
+ "description": "Populated only when POST /credits/subscription starts a Stripe Checkout Session (FREE → paid upgrade). Empty string in all other branches — the client redirects to this URL when non-empty.",
+ "default": ""
}
},
"type": "object",