diff --git a/apps/sim/lib/billing/application/pro-trial.ts b/apps/sim/lib/billing/application/pro-trial.ts index a12d7a4738e..0ad21ed1773 100644 --- a/apps/sim/lib/billing/application/pro-trial.ts +++ b/apps/sim/lib/billing/application/pro-trial.ts @@ -1,3 +1,4 @@ +import { createLogger } from '@sim/logger' import Stripe from 'stripe' import { getHighestPriorityPersonalSubscription } from '@/lib/billing/core/plan' import { requireStripeClient } from '@/lib/billing/stripe-client' @@ -7,6 +8,25 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import type { UserAccountOperation } from '@/lib/users/application/operations' import { authorizeAccountPreferences } from '@/lib/users/application/preferences-authorization' +const logger = createLogger('ProTrial') + +/** + * Stripe invalid-request codes that refuse the first charge itself rather than reporting a fault + * in the request: an amount past the card currency's maximum, or a subscription past Stripe's + * per-subscription invoice limit. + */ +const STRIPE_CHARGE_REFUSAL_CODES: ReadonlySet = new Set(['amount_too_large', 'rate_limit']) + +/** Whether Stripe refused to charge now, which leaves the trial running and is worth a retry later. */ +function isStripeChargeRefusal(error: unknown): error is Stripe.errors.StripeError { + if (error instanceof Stripe.errors.StripeRateLimitError) return true + return ( + error instanceof Stripe.errors.StripeInvalidRequestError && + error.code !== undefined && + STRIPE_CHARGE_REFUSAL_CODES.has(error.code) + ) +} + /** Session-only: ending a trial charges the account's own card, so no delegation may do it. */ function defineProTrialOperation(id: Id) { const operation = { @@ -64,6 +84,19 @@ export const endProTrial: OperationUseCase< 'Your card could not be charged. Update your payment method, then try again.' ) } + if (isStripeChargeRefusal(error)) { + logger.warn('Stripe refused to end a trial early', { + stripeSubscriptionId: subscription.stripeSubscriptionId, + type: error.type, + code: error.code, + error: error.message, + }) + throw new OrchestrationError( + 'conflict', + "We couldn't end your trial early right now. Your trial keeps running, so you can try again later or let it end on its own.", + { cause: error } + ) + } throw error } return { success: true } diff --git a/apps/sim/lib/billing/free-plan.integration.ts b/apps/sim/lib/billing/free-plan.integration.ts index 1fcf366dd77..0ead08a6c60 100644 --- a/apps/sim/lib/billing/free-plan.integration.ts +++ b/apps/sim/lib/billing/free-plan.integration.ts @@ -451,6 +451,58 @@ describe('endProTrial', () => { ) }) + it.each([ + { + label: 'a charge past the card currency limit', + refusal: new Stripe.errors.StripeInvalidRequestError({ + type: 'invalid_request_error', + code: 'amount_too_large', + message: 'Amount must be no more than the currency maximum.', + }), + }, + { + label: "a subscription past Stripe's daily invoice limit", + refusal: new Stripe.errors.StripeInvalidRequestError({ + type: 'invalid_request_error', + code: 'rate_limit', + message: 'You have exceeded the daily invoice limit for this subscription.', + }), + }, + { + label: 'a Stripe rate limit', + refusal: new Stripe.errors.StripeRateLimitError({ + type: 'rate_limit_error', + message: 'Too many requests hit the API too quickly.', + }), + }, + ])('reports $label as a payer error and keeps the trial', async ({ refusal }) => { + const userId = await createUser() + await addSubscription(userId, 'trialing') + stripeStub.subscriptions.update.mockRejectedValueOnce(refusal) + + await expect( + endProTrial.execute({ principal: asSession(userId), input: {} }) + ).rejects.toMatchObject({ + code: 'conflict', + message: expect.stringContaining('trial keeps running'), + }) + }) + + it('still fails on a Stripe request fault that is not a refusal', async () => { + const userId = await createUser() + await addSubscription(userId, 'trialing') + const fault = new Stripe.errors.StripeInvalidRequestError({ + type: 'invalid_request_error', + code: 'resource_missing', + message: 'No such subscription.', + }) + stripeStub.subscriptions.update.mockRejectedValueOnce(fault) + + await expect(endProTrial.execute({ principal: asSession(userId), input: {} })).rejects.toBe( + fault + ) + }) + it('refuses an account whose plan is already paid', async () => { const userId = await createUser() await addSubscription(userId, 'active')