AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(platform): address review comments on subscription billing
Zamil Majdy642c72e5e545
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex 5c98673b32..3b4b928c4a 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -662,6 +662,7 @@ class SubscriptionStatusResponse(BaseModel):@v1_router.get(path="/credits/subscription",summary="Get subscription tier, current cost, and all tier costs",+ operation_id="getSubscriptionStatus",tags=["credits"],dependencies=[Security(requires_user)],)@@ -689,6 +690,7 @@ async def get_subscription_status(@v1_router.post(path="/credits/subscription",summary="Upgrade or downgrade subscription tier",+ operation_id="updateSubscriptionTier",tags=["credits"],dependencies=[Security(requires_user)],)diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.pyindex f19bf65ede..1ed235a3a1 100644--- a/autogpt_platform/backend/backend/copilot/rate_limit.py+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py@@ -118,6 +118,8 @@ async def check_rate_limit(Fails open: if Redis is unavailable, allows the request."""# Lazy subscription deduction — idempotent, only writes once per month.+ # get_user_by_id and get_feature_flag_value are both cached (TTL 5 min / LD+ # streaming), so the fast path (subscription already paid) adds no DB round-trips.try:from backend.data.credit import ensure_subscription_paiddiff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex a7a2287c29..c22b0b3972 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -32,7 +32,7 @@ from backend.data.notifications import NotificationEventModel, RefundRequestDatafrom backend.data.user import get_user_by_id, get_user_email_by_idfrom backend.notifications.notifications import queue_notification_asyncfrom backend.util.exceptions import InsufficientBalanceError-from backend.util.feature_flag import Flag, is_feature_enabled+from backend.util.feature_flag import Flag, get_feature_flag_value, is_feature_enabledfrom backend.util.json import SafeJson, dumpsfrom backend.util.models import Paginationfrom backend.util.retry import func_retry@@ -1260,9 +1260,10 @@ async def set_auto_top_up(user_id: str, config: AutoTopUpConfig):tier = user.subscription_tier or SubscriptionTier.FREEsub_cost = await get_subscription_cost(user_id, tier)if sub_cost > 0 and config.amount < sub_cost:+ cost_fmt = f"${sub_cost / 100:.2f}/mo"raise ValueError(- f"Auto top-up amount must be at least {sub_cost} credits to maintain "- f"your {tier.value} subscription. Set amount >= {sub_cost} or downgrade to Free."+ f"Auto top-up amount must be at least {cost_fmt} to maintain "+ f"your {tier.value} subscription. Set amount >= {cost_fmt} or downgrade to Free.")await User.prisma().update(where={"id": user_id},@@ -1287,9 +1288,11 @@ async def set_subscription_tier(user_id: str, tier: SubscriptionTier) -> None:if sub_cost > 0:auto_top_up = await get_auto_top_up(user_id)if auto_top_up.amount < sub_cost:+ cost_fmt = f"${sub_cost / 100:.2f}/mo"raise ValueError(- f"Auto top-up must be configured with amount >= {sub_cost} credits "- f"before upgrading to {tier.value}. Current amount: {auto_top_up.amount}."+ f"Auto top-up must be configured with amount >= {cost_fmt} "+ f"before upgrading to {tier.value}. "+ f"Current amount: ${auto_top_up.amount / 100:.2f}/mo.")await User.prisma().update(@@ -1322,8 +1325,6 @@ async def get_auto_top_up(user_id: str) -> AutoTopUpConfig:async def get_subscription_cost(user_id: str, tier: SubscriptionTier) -> int:"""Return monthly subscription cost in credits from LD. 0 = free or disabled."""- from backend.util.feature_flag import get_feature_flag_value-flag_map = {SubscriptionTier.PRO: Flag.SUBSCRIPTION_COST_PRO,SubscriptionTier.BUSINESS: Flag.SUBSCRIPTION_COST_BUSINESS,diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.pynew file mode 100644index 0000000000..9eec8e0619--- /dev/null+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py@@ -0,0 +1,182 @@+"""+Tests for subscription tier billing: ensure_subscription_paid idempotency,+BetaUserCredit grant offset, and tier-change validation.+"""++from unittest.mock import AsyncMock, patch++import pytest+from prisma.enums import CreditTransactionType, SubscriptionTier+from prisma.models import CreditTransaction, User, UserBalance++from backend.data.credit import (+ BetaUserCredit,+ ensure_subscription_paid,+ set_subscription_tier,+)+from backend.data.user import get_user_by_id+from backend.util.test import SpinTestServer++SUB_TEST_USER_ID = "sub-test-user"+SUB_COST = 500 # $5.00 in cents+++async def setup_sub_test_user(+ tier: SubscriptionTier = SubscriptionTier.FREE,+ balance: int = 1000,+ top_up_amount: int = 0,+ top_up_threshold: int = 0,+) -> None:+ await CreditTransaction.prisma().delete_many(where={"userId": SUB_TEST_USER_ID})+ await UserBalance.prisma().delete_many(where={"userId": SUB_TEST_USER_ID})+ await User.prisma().delete_many(where={"id": SUB_TEST_USER_ID})++ await User.prisma().create(+ data={+ "id": SUB_TEST_USER_ID,+ "email": f"{SUB_TEST_USER_ID}@example.com",+ "name": "Sub Test User",+ "subscriptionTier": tier,+ "topUpConfig": {+ "amount": top_up_amount,+ "threshold": top_up_threshold,+ },+ }+ )+ await UserBalance.prisma().create(+ data={"userId": SUB_TEST_USER_ID, "balance": balance}+ )+ get_user_by_id.cache_delete(SUB_TEST_USER_ID) # type: ignore[attr-defined]+++async def cleanup_sub_test_user() -> None:+ await CreditTransaction.prisma().delete_many(where={"userId": SUB_TEST_USER_ID})+ await UserBalance.prisma().delete_many(where={"userId": SUB_TEST_USER_ID})+ await User.prisma().delete_many(where={"id": SUB_TEST_USER_ID})+ get_user_by_id.cache_delete(SUB_TEST_USER_ID) # type: ignore[attr-defined]++[email protected](loop_scope="session")+async def test_ensure_subscription_paid_idempotent(server: SpinTestServer):+ """Second call within the same month must not create a second transaction."""+ await setup_sub_test_user(tier=SubscriptionTier.PRO, balance=2000)++ with patch(+ "backend.data.credit.get_feature_flag_value",+ new=AsyncMock(return_value=SUB_COST),+ ):+ await ensure_subscription_paid(SUB_TEST_USER_ID)+ await ensure_subscription_paid(SUB_TEST_USER_ID)++ txns = await CreditTransaction.prisma().find_many(+ where={"userId": SUB_TEST_USER_ID, "type": CreditTransactionType.SUBSCRIPTION}+ )+ assert len(txns) == 1, f"Expected 1 SUBSCRIPTION txn, got {len(txns)}"+ assert txns[0].amount == -SUB_COST++ await cleanup_sub_test_user()++[email protected](loop_scope="session")+async def test_ensure_subscription_paid_free_tier_skips(server: SpinTestServer):+ """FREE tier (cost=0) must not create any subscription transaction."""+ await setup_sub_test_user(tier=SubscriptionTier.FREE, balance=500)++ with patch(+ "backend.data.credit.get_feature_flag_value",+ new=AsyncMock(return_value=0),+ ):+ await ensure_subscription_paid(SUB_TEST_USER_ID)++ txns = await CreditTransaction.prisma().find_many(+ where={"userId": SUB_TEST_USER_ID, "type": CreditTransactionType.SUBSCRIPTION}+ )+ assert len(txns) == 0++ await cleanup_sub_test_user()++[email protected](loop_scope="session")+async def test_beta_user_credit_grant_offsets_subscription(server: SpinTestServer):+ """BetaUserCredit grant must equal refill_amount + subscription_cost so the+ monthly subscription deduction does not reduce the user's effective usage budget."""+ from datetime import datetime, timezone++ refill = 1000+ beta_credit = BetaUserCredit(refill)++ await setup_sub_test_user(tier=SubscriptionTier.PRO, balance=0)++ # Force the balance updatedAt to old date so monthly refill triggers+ from datetime import timedelta++ old_date = datetime.now(timezone.utc) - timedelta(days=35)+ await UserBalance.prisma().update(+ where={"userId": SUB_TEST_USER_ID},+ data={"updatedAt": old_date, "balance": 0},+ )+ get_user_by_id.cache_delete(SUB_TEST_USER_ID) # type: ignore[attr-defined]++ with patch(+ "backend.data.credit.get_feature_flag_value",+ new=AsyncMock(return_value=SUB_COST),+ ):+ balance = await beta_credit.get_credits(SUB_TEST_USER_ID)++ # The grant should cover refill + sub cost; balance should be at least refill_amount+ assert balance >= refill, (+ f"After grant+subscription deduction, balance {balance} < refill {refill}. "+ "Beta grant must offset subscription cost."+ )++ await cleanup_sub_test_user()++[email protected](loop_scope="session")+async def test_set_subscription_tier_requires_auto_top_up(server: SpinTestServer):+ """Upgrading to PRO without sufficient auto top-up must raise ValueError."""+ await setup_sub_test_user(+ tier=SubscriptionTier.FREE,+ balance=2000,+ top_up_amount=100, # $1 — less than SUB_COST $5+ top_up_threshold=50,+ )++ with patch(+ "backend.data.credit.get_feature_flag_value",+ new=AsyncMock(return_value=SUB_COST),+ ):+ with pytest.raises(ValueError, match=r"\$5\.00/mo"):+ await set_subscription_tier(SUB_TEST_USER_ID, SubscriptionTier.PRO)++ await cleanup_sub_test_user()++[email protected](loop_scope="session")+async def test_set_subscription_tier_upgrade_charges_immediately(+ server: SpinTestServer,+):+ """Successful upgrade to PRO must immediately create a SUBSCRIPTION transaction."""+ await setup_sub_test_user(+ tier=SubscriptionTier.FREE,+ balance=2000,+ top_up_amount=SUB_COST + 100, # Sufficient+ top_up_threshold=50,+ )++ # Patch auto top-up Stripe call so the test does not need Stripe credentials.+ with patch(+ "backend.data.credit.get_feature_flag_value",+ new=AsyncMock(return_value=SUB_COST),+ ), patch(+ "backend.data.credit.UserCredit._top_up_credits",+ new=AsyncMock(),+ ):+ await set_subscription_tier(SUB_TEST_USER_ID, SubscriptionTier.PRO)++ txns = await CreditTransaction.prisma().find_many(+ where={"userId": SUB_TEST_USER_ID, "type": CreditTransactionType.SUBSCRIPTION}+ )+ assert len(txns) == 1, f"Expected 1 SUBSCRIPTION txn on upgrade, got {len(txns)}"++ await cleanup_sub_test_user()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.tsxindex 214e9445db..076a535254 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@@ -36,12 +36,29 @@ function formatCost(cents: number): string {return `$${(cents / 100).toFixed(2)}/mo`;}-export function SubscriptionTierSection() {- const { subscription, isLoading, isPending, changeTier } =- useSubscriptionTierSection();+interface Props {+ autoTopUpConfig: { amount: number; threshold: number } | null;+}++export function SubscriptionTierSection({ autoTopUpConfig }: Props) {+ const { subscription, isLoading, error, isPending, changeTier } =+ useSubscriptionTierSection(autoTopUpConfig);const [tierError, setTierError] = useState<string | null>(null);- if (isLoading || !subscription) return null;+ if (isLoading) return null;++ if (error) {+ return (+ <div className="space-y-4">+ <h3 className="text-lg font-medium">Subscription Plan</h3>+ <p className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-800 dark:bg-red-900/20 dark:text-red-400">+ {error}+ </p>+ </div>+ );+ }++ if (!subscription) return null;async function handleTierChange(tierKey: string) {setTierError(null);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.tsindex d1af19763a..23fb1f5b6c 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@@ -7,30 +7,22 @@ export type SubscriptionStatus = {tier_costs: Record<string, number>;};-export type AutoTopUpConfig = {- amount: number;- threshold: number;-};+type AutoTopUpConfig = { amount: number; threshold: number } | null;-export function useSubscriptionTierSection() {+export function useSubscriptionTierSection(autoTopUpConfig: AutoTopUpConfig) {const api = useMemo(() => new AutoGPTServerAPI(), []);const [subscription, setSubscription] = useState<SubscriptionStatus | null>(null,);- const [autoTopUp, setAutoTopUp] = useState<AutoTopUpConfig | null>(null);const [isLoading, setIsLoading] = useState(true);const [error, setError] = useState<string | null>(null);const [isPending, setIsPending] = useState(false);const fetchSubscription = useCallback(async () => {try {- const [sub, topUp] = await Promise.all([- api.getSubscription(),- api.getAutoTopUpConfig(),- ]);+ const sub = await api.getSubscription();setSubscription(sub);- setAutoTopUp(topUp);} catch (e) {setError("Failed to load subscription info");} finally {@@ -46,7 +38,10 @@ export function useSubscriptionTierSection() {async (tier: string): Promise<string | null> => {const targetCost = subscription?.tier_costs[tier] ?? 0;- if (targetCost > 0 && (!autoTopUp || autoTopUp.amount < targetCost)) {+ if (+ targetCost > 0 &&+ (!autoTopUpConfig || autoTopUpConfig.amount < targetCost)+ ) {return `Auto top-up amount must be at least $${(targetCost / 100).toFixed(2)} to subscribe to this tier. Configure it below first.`;}@@ -63,12 +58,11 @@ export function useSubscriptionTierSection() {setIsPending(false);}},- [api, subscription, autoTopUp],+ [api, subscription, autoTopUpConfig],);return {subscription,- autoTopUp,isLoading,error,isPending,diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsxindex fb565c048b..7e77b29285 100644--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx@@ -144,7 +144,7 @@ export default function CreditsPage() {{/* Subscription Tier */}<div className="mb-8">- <SubscriptionTierSection />+ <SubscriptionTierSection autoTopUpConfig={autoTopUpConfig} /></div><div className="grid grid-cols-1 gap-8 lg:grid-cols-2">diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 341d08fa2a..2a32a20b1a 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -1789,7 +1789,7 @@"get": {"tags": ["v1", "credits"],"summary": "Get subscription tier, current cost, and all tier costs",- "operationId": "getV1Get subscription tier, current cost, and all tier costs",+ "operationId": "getSubscriptionStatus","responses": {"200": {"description": "Successful Response",@@ -1810,7 +1810,7 @@"post": {"tags": ["v1", "credits"],"summary": "Upgrade or downgrade subscription tier",- "operationId": "postV1Upgrade or downgrade subscription tier",+ "operationId": "updateSubscriptionTier","requestBody": {"content": {"application/json": {