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
114 changes: 110 additions & 4 deletions apps/sim/app/api/billing/switch-plan/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,26 @@ import { authMockFns, createMockRequest, resetEnvFlagsMock, setEnvFlags } from '
import { billingAccessMock, billingAccessMockFns } from '@sim/testing/mocks/billing-access.mock'
import { billingCoreMock, billingCoreMockFns } from '@sim/testing/mocks/billing-core.mock'
import { billingOrganizationMock } from '@sim/testing/mocks/billing-organization.mock'
import { billingPlanMock } from '@sim/testing/mocks/billing-plan.mock'
import { billingPlanMock, billingPlanMockFns } from '@sim/testing/mocks/billing-plan.mock'
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock'
import { stripeClientMock } from '@sim/testing/mocks/stripe.mock'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'

const { mockCanManageWorkspaceBilling, mockGetWorkspaceHostContextForViewer } = vi.hoisted(() => ({
const {
mockCanManageWorkspaceBilling,
mockGetWorkspaceHostContextForViewer,
mockClaimCheckoutAdmission,
mockReleaseCheckoutAdmission,
mockReadSwitchBasis,
mockRecordPlanSwitch,
} = vi.hoisted(() => ({
mockCanManageWorkspaceBilling: vi.fn(),
mockGetWorkspaceHostContextForViewer: vi.fn(),
mockClaimCheckoutAdmission: vi.fn(),
mockReleaseCheckoutAdmission: vi.fn(),
mockReadSwitchBasis: vi.fn(),
mockRecordPlanSwitch: vi.fn(),
}))

vi.mock('@/lib/billing/core/access', () => billingAccessMock)
Expand All @@ -22,6 +34,26 @@ vi.mock('@/lib/billing/core/plan', () => billingPlanMock)

vi.mock('@/lib/billing/core/subscription', () => billingSubscriptionMock)

vi.mock('@/lib/billing/stripe-client', () => stripeClientMock)

vi.mock('@/lib/billing/checkout-admission', () => ({
claimCheckoutAdmission: mockClaimCheckoutAdmission,
releaseCheckoutAdmission: mockReleaseCheckoutAdmission,
}))

vi.mock('@/lib/billing/plans', () => ({
getPlanByName: (name: string) => ({
name,
priceId: 'price-month',
annualDiscountPriceId: 'price-year',
}),
}))

vi.mock('@/lib/billing/core/plan-switch', () => ({
readSwitchBasis: mockReadSwitchBasis,
recordPlanSwitch: mockRecordPlanSwitch,
}))

vi.mock('@/lib/billing/workspace-permissions', () => ({
canManageWorkspaceBilling: mockCanManageWorkspaceBilling,
}))
Expand All @@ -34,7 +66,9 @@ vi.mock('@/lib/workspaces/host-context', () => ({

import { POST } from '@/app/api/billing/switch-plan/route'

const { mockGetOrganizationSubscription } = billingCoreMockFns
const { mockGetOrganizationSubscription, mockIsSubscriptionOrgScoped } = billingCoreMockFns

const routeContext = { params: Promise.resolve({}) }

const { mockGetEffectiveBillingStatus } = billingAccessMockFns

Expand Down Expand Up @@ -96,7 +130,8 @@ describe('POST /api/billing/switch-plan', () => {
createMockRequest('POST', {
targetPlanName: 'enterprise',
workspaceId: 'workspace-1',
})
}),
routeContext
)

expect(response.status).toBe(400)
Expand All @@ -105,4 +140,75 @@ describe('POST /api/billing/switch-plan', () => {
})
expect(mockGetEffectiveBillingStatus).not.toHaveBeenCalled()
})

describe('during a Pro free trial', () => {
const personalPro = (status: string) => ({
id: 'subscription-1',
referenceId: 'viewer-1',
plan: 'pro_6000',
status,
stripeSubscriptionId: 'stripe-subscription-1',
})
const mockStripeUpdate = vi.fn()

beforeEach(() => {
mockGetEffectiveBillingStatus.mockResolvedValue({
billingBlocked: false,
billingBlockedReason: null,
blockedByOrgOwner: false,
})
mockIsSubscriptionOrgScoped.mockResolvedValue(false)
mockClaimCheckoutAdmission.mockResolvedValue({ claimToken: 'claim-1' })
stripeClientMock.requireStripeClient.mockReturnValue({
subscriptions: {
retrieve: vi.fn().mockResolvedValue({
status: 'trialing',
items: {
data: [{ id: 'item-1', price: { id: 'price-1', recurring: { interval: 'month' } } }],
},
}),
update: mockStripeUpdate,
},
})
})

it.each([
{ label: 'a tier change', targetPlanName: 'pro_25000', interval: undefined },
{ label: 'an interval change', targetPlanName: 'pro_6000', interval: 'year' },
])('refuses $label before touching Stripe', async (switchCase) => {
billingPlanMockFns.mockGetHighestPrioritySubscription.mockResolvedValue(
personalPro('trialing')
)

const response = await POST(
createMockRequest('POST', {
targetPlanName: switchCase.targetPlanName,
interval: switchCase.interval,
}),
routeContext
)

expect(response.status).toBe(409)
await expect(response.json()).resolves.toMatchObject({
error: expect.stringContaining('free trial ends'),
})
expect(stripeClientMock.requireStripeClient).not.toHaveBeenCalled()
})

it('refuses a switch Stripe still holds in trial while the row has moved on', async () => {
const subscription = personalPro('active')
billingPlanMockFns.mockGetHighestPrioritySubscription.mockResolvedValue(subscription)
mockReadSwitchBasis.mockResolvedValue({ subscription, pool: undefined })

const response = await POST(
createMockRequest('POST', { targetPlanName: 'pro_6000', interval: 'year' }),
routeContext
)

expect(response.status).toBe(409)
expect(mockStripeUpdate).not.toHaveBeenCalled()
expect(mockRecordPlanSwitch).not.toHaveBeenCalled()
expect(mockReleaseCheckoutAdmission).toHaveBeenCalledWith({ claimToken: 'claim-1' })
})
})
})
15 changes: 14 additions & 1 deletion apps/sim/app/api/billing/switch-plan/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { type NextRequest, NextResponse } from 'next/server'
import { billingSwitchPlanContract } from '@/lib/api/contracts/subscription'
import { parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { TRIAL_PLAN_CHANGE_MESSAGE } from '@/lib/billing/authorization'
import {
type CheckoutAdmissionClaim,
claimCheckoutAdmission,
Expand All @@ -19,13 +20,14 @@ import {
getHighestPrioritySubscription,
} from '@/lib/billing/core/plan'
import { readSwitchBasis, recordPlanSwitch } from '@/lib/billing/core/plan-switch'
import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
import { getPlanTierCredits, getPlanType, isEnterprise, isPro } from '@/lib/billing/plan-helpers'
import { getPlanByName } from '@/lib/billing/plans'
import { requireStripeClient } from '@/lib/billing/stripe-client'
import {
hasUsableSubscriptionAccess,
hasUsableSubscriptionStatus,
isOrgScopedSubscription,
isTrialingSubscription,
} from '@/lib/billing/subscriptions/utils'
import { canManageWorkspaceBilling } from '@/lib/billing/workspace-permissions'
import { isBillingEnabled } from '@/lib/core/config/env-flags'
Expand Down Expand Up @@ -106,6 +108,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
)
}

// A Pro trial's fixed allowance is counted per billing period, and a price change restarts the
// period, so a switch during the trial would start the cap over. Pro is only ever personal.
const isProPlan = isPro(sub.plan)
if (isProPlan && isTrialingSubscription(sub)) {
return NextResponse.json({ error: TRIAL_PLAN_CHANGE_MESSAGE }, { status: 409 })
}

const targetPlan = getPlanByName(targetPlanName)
if (!targetPlan) {
return NextResponse.json({ error: 'Target plan not found' }, { status: 400 })
Expand Down Expand Up @@ -156,6 +165,10 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
if (!hasUsableSubscriptionStatus(stripeSubscription.status)) {
return NextResponse.json({ error: 'Stripe subscription is not active' }, { status: 400 })
}
// The row can trail Stripe: a trial whose start webhook has not landed is still a trial.
if (isProPlan && isTrialingSubscription(stripeSubscription)) {
return NextResponse.json({ error: TRIAL_PLAN_CHANGE_MESSAGE }, { status: 409 })
}

const subscriptionItem = stripeSubscription.items.data[0]
if (!subscriptionItem) {
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1225,7 +1225,7 @@ export const auth = betterAuth({
const checkoutAdmissionClaim = await claimCheckoutAdmission(referenceId)
try {
if (isPersonalCheckoutRequest(requestBody, sessionUserId)) {
await assertPersonalCheckoutAllowed(sessionUserId, requestBody.plan)
await assertPersonalCheckoutAllowed(sessionUserId)
}
} catch (error) {
await releaseCheckoutAdmission(checkoutAdmissionClaim)
Expand Down
29 changes: 16 additions & 13 deletions apps/sim/lib/billing/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,21 +118,27 @@ export function assertSelfServeCheckoutRequest(body: {
}
}

/** Refuse an organization-plan upgrade while the account's own Pro plan is still in its free trial. */
/**
* Refuse any plan change while the account's own Pro plan is in its free trial. A trial's allowance
* is a fixed cap counted per billing period, and a price change restarts Stripe's period, so a
* change during the trial would start the cap over. A Team upgrade would also keep the trial,
* running the team free without the trial's cap.
*/
async function assertNoPersonalTrial(userId: string): Promise<void> {
const trialing = await db
.select({ plan: subscription.plan })
.from(subscription)
.where(and(eq(subscription.referenceId, userId), eq(subscription.status, 'trialing')))
if (!trialing.some((row) => isPro(row.plan))) return

logger.warn('Blocking team upgrade - personal plan is in its free trial', { userId })
throw new APIError('CONFLICT', {
message:
'Your Pro free trial has to end before you can move to a Team plan. End it from Settings > Billing (restore it first if you canceled it), or wait for it to end, then upgrade.',
})
logger.warn('Blocking plan change - personal plan is in its free trial', { userId })
throw new APIError('CONFLICT', { message: TRIAL_PLAN_CHANGE_MESSAGE })
}

/** Why a plan change is refused during a free trial, and how to get past it. */
export const TRIAL_PLAN_CHANGE_MESSAGE =
'Your plan can change once your Pro free trial ends. End the trial from Settings > Billing (restore it first if you canceled it), or wait for it to end, then change your plan.'

/**
* Classify a `/subscription/upgrade` request as a personal checkout using
* the same reference resolution as the Better Auth Stripe plugin
Expand Down Expand Up @@ -161,9 +167,8 @@ export function isPersonalCheckoutRequest(
*
* Blocks an account AWS Marketplace bills, a bound, incomplete Stripe
* subscription, a member already covered by an entitled organization
* subscription, and a Team upgrade of a Pro free trial: Stripe keeps the trial
* across the price change, so the team would run free without the trial's
* capped allowance. Throws {@link APIError} with a user-facing message; the
* subscription, and any plan change during a Pro free trial
* ({@link assertNoPersonalTrial}). Throws {@link APIError} with a user-facing message; the
* checkout UI surfaces it as-is.
*
* Called from the Better Auth `hooks.before` middleware, NOT from
Expand All @@ -174,12 +179,10 @@ export function isPersonalCheckoutRequest(
* Fails closed: when coverage cannot be determined, the checkout is
* rejected rather than risking a duplicate subscription.
*/
export async function assertPersonalCheckoutAllowed(userId: string, plan?: unknown): Promise<void> {
export async function assertPersonalCheckoutAllowed(userId: string): Promise<void> {
await assertNotBilledThroughMarketplace(userId)
await assertNoBoundIncompleteSubscription(userId)
if (isOrgPlan(normalizeCheckoutPlan(plan))) {
await assertNoPersonalTrial(userId)
}
await assertNoPersonalTrial(userId)

const coverage = await getOrganizationCoverageForMember(userId)

Expand Down
8 changes: 4 additions & 4 deletions apps/sim/lib/billing/trial.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,12 +566,12 @@ describe('the usage limit card', () => {
})
})

describe('a Team upgrade during a Pro trial', () => {
it('is refused while the personal Pro plan is still trialing', async () => {
describe('a personal checkout during a Pro trial', () => {
it('is refused while the personal Pro plan is still trialing, so the trial cap never restarts', async () => {
const userId = await createUser()
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })

await expect(assertPersonalCheckoutAllowed(userId, 'team_8000')).rejects.toMatchObject({
await expect(assertPersonalCheckoutAllowed(userId)).rejects.toMatchObject({
status: 'CONFLICT',
})
})
Expand All @@ -580,6 +580,6 @@ describe('a Team upgrade during a Pro trial', () => {
const userId = await createUser()
await addSubscription(userId, { status: 'active' })

await expect(assertPersonalCheckoutAllowed(userId, 'team_8000')).resolves.toBeUndefined()
await expect(assertPersonalCheckoutAllowed(userId)).resolves.toBeUndefined()
})
})
3 changes: 0 additions & 3 deletions scripts/check-test-types.baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,6 @@
"apps/sim/app/api/billing/route.test.ts": {
"TS2554": 4
},
"apps/sim/app/api/billing/switch-plan/route.test.ts": {
"TS2554": 1
},
"apps/sim/app/api/billing/update-cost/route.test.ts": {
"TS2554": 50
},
Expand Down
Loading