Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions apps/sim/lib/billing/application/pro-trial.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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<string> = 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<const Id extends string>(id: Id) {
const operation = {
Expand Down Expand Up @@ -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 }
Expand Down
52 changes: 52 additions & 0 deletions apps/sim/lib/billing/free-plan.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Loading