diff --git a/apps/sim/app/api/billing/switch-plan/route.test.ts b/apps/sim/app/api/billing/switch-plan/route.test.ts index 5579e15e966..b4158e2603b 100644 --- a/apps/sim/app/api/billing/switch-plan/route.test.ts +++ b/apps/sim/app/api/billing/switch-plan/route.test.ts @@ -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) @@ -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, })) @@ -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 @@ -96,7 +130,8 @@ describe('POST /api/billing/switch-plan', () => { createMockRequest('POST', { targetPlanName: 'enterprise', workspaceId: 'workspace-1', - }) + }), + routeContext ) expect(response.status).toBe(400) @@ -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' }) + }) + }) }) diff --git a/apps/sim/app/api/billing/switch-plan/route.ts b/apps/sim/app/api/billing/switch-plan/route.ts index 925105078b0..9db9ef41d11 100644 --- a/apps/sim/app/api/billing/switch-plan/route.ts +++ b/apps/sim/app/api/billing/switch-plan/route.ts @@ -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, @@ -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' @@ -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 }) @@ -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) { diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts index 53e94bd5068..d6f43c5e1fe 100644 --- a/apps/sim/lib/auth/auth.ts +++ b/apps/sim/lib/auth/auth.ts @@ -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) diff --git a/apps/sim/lib/billing/authorization.ts b/apps/sim/lib/billing/authorization.ts index 013280687a4..94383c7f4f0 100644 --- a/apps/sim/lib/billing/authorization.ts +++ b/apps/sim/lib/billing/authorization.ts @@ -118,7 +118,12 @@ 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 { const trialing = await db .select({ plan: subscription.plan }) @@ -126,13 +131,14 @@ async function assertNoPersonalTrial(userId: string): Promise { .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 @@ -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 @@ -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 { +export async function assertPersonalCheckoutAllowed(userId: string): Promise { await assertNotBilledThroughMarketplace(userId) await assertNoBoundIncompleteSubscription(userId) - if (isOrgPlan(normalizeCheckoutPlan(plan))) { - await assertNoPersonalTrial(userId) - } + await assertNoPersonalTrial(userId) const coverage = await getOrganizationCoverageForMember(userId) diff --git a/apps/sim/lib/billing/trial.integration.ts b/apps/sim/lib/billing/trial.integration.ts index 84bc3cd2191..33bbe2b5afb 100644 --- a/apps/sim/lib/billing/trial.integration.ts +++ b/apps/sim/lib/billing/trial.integration.ts @@ -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', }) }) @@ -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() }) }) diff --git a/scripts/check-test-types.baseline.json b/scripts/check-test-types.baseline.json index b342963fbfa..93f529bc0a0 100644 --- a/scripts/check-test-types.baseline.json +++ b/scripts/check-test-types.baseline.json @@ -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 },