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
58 changes: 55 additions & 3 deletions apps/sim/app/api/billing/switch-plan/route.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { createLogger } from '@sim/logger'
import { getErrorMessage, toError } from '@sim/utils/errors'
import { APIError } from 'better-auth/api'
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 {
type CheckoutAdmissionClaim,
claimCheckoutAdmission,
releaseCheckoutAdmission,
} from '@/lib/billing/checkout-admission'
import { getEffectiveBillingStatus } from '@/lib/billing/core/access'
import { getOrganizationSubscription, isSubscriptionOrgScoped } from '@/lib/billing/core/billing'
import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization'
import {
getHighestPriorityPersonalSubscription,
getHighestPrioritySubscription,
} from '@/lib/billing/core/plan'
import { recordPlanSwitch } from '@/lib/billing/core/plan-switch'
import {
isSwitchBasisCurrent,
readPoolUsageSnapshot,
recordPlanSwitch,
} from '@/lib/billing/core/plan-switch'
import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
import { getPlanByName } from '@/lib/billing/plans'
import { requireStripeClient } from '@/lib/billing/stripe-client'
Expand Down Expand Up @@ -42,6 +52,7 @@ const logger = createLogger('SwitchPlan')
*/
export const POST = withRouteHandler(async (request: NextRequest) => {
const session = await getSession()
let admission: CheckoutAdmissionClaim | null = null

try {
if (!session?.user?.id) {
Expand Down Expand Up @@ -120,6 +131,24 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
}
}

// One plan change or checkout per billing reference at a time, each computed from the plan
// as it stands once admitted: a second switch must not snapshot the first one's new allowance.
try {
admission = await claimCheckoutAdmission(sub.referenceId)
} catch (error) {
if (!(error instanceof APIError)) throw error
return NextResponse.json(
{ error: 'A plan change is already in progress. Please wait a moment and try again.' },
{ status: 409 }
)
}
if (!(await isSwitchBasisCurrent(sub))) {
return NextResponse.json(
{ error: 'Your plan just changed. Refresh the page and try again.' },
{ status: 409 }
)
}

const stripe = requireStripeClient()
const stripeSubscription = await stripe.subscriptions.retrieve(sub.stripeSubscriptionId)

Expand Down Expand Up @@ -178,10 +207,22 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
targetPriceId,
})

const orgScoped = await isSubscriptionOrgScoped(sub)
// Read before Stripe applies the switch, since its webhook can move the live limit first. A
// retry finds Stripe already switched, so it has no pre-switch reading to take.
const previous = alreadyOnStripePrice
? undefined
: await readPoolUsageSnapshot({
type: orgScoped ? 'organization' : 'user',
id: sub.referenceId,
})
// The item's period after the switch: Stripe's response, or the retrieved item on a retry
// that finds Stripe already on the target price.
let switchedItem: typeof subscriptionItem | undefined = subscriptionItem
if (!alreadyOnStripePrice) {
const currentQuantity = subscriptionItem.quantity ?? 1

await stripe.subscriptions.update(sub.stripeSubscriptionId, {
const updated = await stripe.subscriptions.update(sub.stripeSubscriptionId, {
items: [
{
id: subscriptionItem.id,
Expand All @@ -191,13 +232,22 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
],
proration_behavior: 'always_invoice',
})
switchedItem = updated.items.data.find((item) => item.id === subscriptionItem.id)
}
const period = switchedItem
? {
start: new Date(switchedItem.current_period_start * 1000),
end: new Date(switchedItem.current_period_end * 1000),
}
: undefined

await recordPlanSwitch({
subscription: sub,
targetPlanName,
targetInterval: targetInterval as 'month' | 'year',
orgScoped: await isSubscriptionOrgScoped(sub),
orgScoped,
period,
previous,
})

logger.info('Subscription switched successfully', {
Expand Down Expand Up @@ -248,5 +298,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
{ error: getErrorMessage(error, 'Failed to switch plan') },
{ status: 500 }
)
} finally {
if (admission) await releaseCheckoutAdmission(admission)
}
})
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { getErrorMessage } from '@sim/utils/errors'
import { formatDate } from '@sim/utils/formatting'
import { useRouter } from 'next/navigation'
import { useSession, useSubscription } from '@/lib/auth/client'
import { ANNUAL_DISCOUNT_RATE, ON_DEMAND_UNLIMITED } from '@/lib/billing/constants'
import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants'
import { formatCreditCost } from '@/lib/billing/credits/conversion'
import {
getCoveredUsage,
Expand All @@ -28,6 +28,7 @@ import {
isOnDemandOffDisabled,
} from '@/lib/billing/on-demand'
import {
formatMonthlyPlanPrice,
getDisplayPlanName,
getPlanTierDollars,
isEnterprise,
Expand Down Expand Up @@ -84,13 +85,6 @@ const INVOICE_STATUS_BADGES: Record<string, InvoiceStatusBadge> = {
void: { variant: 'gray', label: 'Void' },
}

/** A plan's effective monthly price: the annual price spread over twelve months on annual billing. */
function formatMonthlyPrice(plan: string, billingInterval: string | undefined): string {
const monthly =
getPlanTierDollars(plan) * (billingInterval === 'year' ? 1 - ANNUAL_DISCOUNT_RATE : 1)
return `$${Number.isInteger(monthly) ? monthly : monthly.toFixed(2)}`
}

function getPeriodEndLabel(isCancelledAtPeriodEnd: boolean, isTrialing: boolean): string {
if (isCancelledAtPeriodEnd) return 'Access until'
if (isTrialing) return 'Free trial ends'
Expand Down Expand Up @@ -498,7 +492,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
? 'Choose a new plan for this organization'
: subscription.isEnterprise
? 'Custom pricing'
: `${formatMonthlyPrice(subscription.plan, billingInterval)}${isOrganizationScope ? ' per user' : ''}/month, ${billingPeriod}`
: `${formatMonthlyPlanPrice(getPlanTierDollars(subscription.plan), billingInterval === 'year')}${isOrganizationScope ? ' per user' : ''}/month, ${billingPeriod}`

const periodEnd = isOrganizationScope
? (organizationBilling?.billingPeriodEnd ?? null)
Expand Down
1 change: 1 addition & 0 deletions apps/sim/hooks/queries/subscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ export function useEndProTrial() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: () => requestJson(billingEndTrialContract, { body: {} }),
// Settled, not success: a lost response can hide a charge that went through.
onSettled: () =>
Promise.all([
queryClient.invalidateQueries({ queryKey: subscriptionKeys.all }),
Expand Down
6 changes: 5 additions & 1 deletion apps/sim/lib/api-key/byok.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,11 @@ async function resolveHostedModelKey(
userProvidedKey: string | undefined,
billingAttribution: UsageUpgradePayer | undefined
): Promise<{ apiKey: string; isBYOK: boolean }> {
if (!(await mayUseHostedKey(workspaceId, billingAttribution))) {
const hostedKeyAllowed = await mayUseHostedKey(workspaceId, billingAttribution).catch((error) => {
if (userProvidedKey) return false
throw error
})
if (!hostedKeyAllowed) {
if (userProvidedKey) return { apiKey: userProvidedKey, isBYOK: true }
throw new HostedKeyRequiresPaidPlanError(model)
}
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 @@ -1221,7 +1221,7 @@ export const auth = betterAuth({
const checkoutAdmissionClaim = await claimCheckoutAdmission(referenceId)
try {
if (isPersonalCheckoutRequest(requestBody, sessionUserId)) {
await assertPersonalCheckoutAllowed(sessionUserId)
await assertPersonalCheckoutAllowed(sessionUserId, requestBody.plan)
}
} catch (error) {
await releaseCheckoutAdmission(checkoutAdmissionClaim)
Expand Down
29 changes: 23 additions & 6 deletions apps/sim/lib/billing/application/pro-trial.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Stripe from 'stripe'
import { getHighestPriorityPersonalSubscription } from '@/lib/billing/core/plan'
import { requireStripeClient } from '@/lib/billing/stripe-client'
import { isTrialingSubscription } from '@/lib/billing/subscriptions/utils'
Expand Down Expand Up @@ -40,15 +41,31 @@ export const endProTrial: OperationUseCase<
!subscription ||
subscription.referenceId !== userId ||
!isTrialingSubscription(subscription) ||
!subscription.stripeSubscriptionId
!subscription.stripeSubscriptionId ||
subscription.cancelAtPeriodEnd
) {
throw new OrchestrationError('conflict', 'There is no free trial to end on this account')
}
await requireStripeClient().subscriptions.update(
subscription.stripeSubscriptionId,
{ trial_end: 'now' },
{ idempotencyKey: `end-trial-early:${subscription.stripeSubscriptionId}` }
)
try {
// A failed first charge leaves the trial running instead of starting a past-due plan. The
// key absorbs a double click but not a retry a minute later, since Stripe replays a stored
// decline for a day and the payer may have just fixed their card.
await requireStripeClient().subscriptions.update(
subscription.stripeSubscriptionId,
{ trial_end: 'now', payment_behavior: 'error_if_incomplete' },
{
idempotencyKey: `end-trial-early:${subscription.stripeSubscriptionId}:${Math.floor(Date.now() / 60_000)}`,
}
)
} catch (error) {
if (error instanceof Stripe.errors.StripeCardError) {
throw new OrchestrationError(
'conflict',
'Your card could not be charged. Update your payment method, then try again.'
)
}
throw error
}
return { success: true }
},
}
28 changes: 24 additions & 4 deletions apps/sim/lib/billing/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
assertNoUnresolvedEnterpriseIssuance,
EnterpriseIssuanceInProgressError,
} from '@/lib/billing/enterprise-outbox'
import { isOrgPlan } from '@/lib/billing/plan-helpers'
import { isOrgPlan, isPro } from '@/lib/billing/plan-helpers'
import { isOrgScopedSubscription } from '@/lib/billing/subscriptions/utils'

const logger = createLogger('BillingAuthorization')
Expand Down Expand Up @@ -74,6 +74,21 @@ async function assertNotBilledThroughMarketplace(referenceId: string): Promise<v
})
}

/** Refuse an organization-plan upgrade while the account's own Pro plan is still in its free trial. */
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')))
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
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 the trial now from Settings > Billing, then upgrade.',
})
}

/**
* Classify a `/subscription/upgrade` request as a personal checkout using
* the same reference resolution as the Better Auth Stripe plugin
Expand Down Expand Up @@ -101,8 +116,10 @@ export function isPersonalCheckoutRequest(
* Guard for personal (user-referenced) checkouts on `/subscription/upgrade`.
*
* Blocks an account AWS Marketplace bills, a bound, incomplete Stripe
* subscription, and a member already covered by an entitled organization
* subscription. Throws {@link APIError} with a user-facing message; the
* 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
* checkout UI surfaces it as-is.
*
* Called from the Better Auth `hooks.before` middleware, NOT from
Expand All @@ -113,9 +130,12 @@ 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): Promise<void> {
export async function assertPersonalCheckoutAllowed(userId: string, plan?: unknown): Promise<void> {
await assertNotBilledThroughMarketplace(userId)
await assertNoBoundIncompleteSubscription(userId)
if (typeof plan === 'string' && isOrgPlan(plan)) {
await assertNoPersonalTrial(userId)
}

const coverage = await getOrganizationCoverageForMember(userId)

Expand Down
3 changes: 3 additions & 0 deletions apps/sim/lib/billing/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,6 @@ export const USAGE_UNAVAILABLE_MESSAGE =
* contracts, and the overage, true-up, and final invoices billed on top of them.
*/
export const INVOICE_DAYS_UNTIL_DUE = 30

/** Average calendar month in milliseconds, for pricing a billing period by its months. */
export const AVERAGE_MONTH_MS = 30.44 * 24 * 60 * 60 * 1000
8 changes: 5 additions & 3 deletions apps/sim/lib/billing/core/chat-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ interface PaidAccessOptions {
/**
* The verdict for a free payer whose credit balance cannot be read. Chat admits, because a
* database blip must not lock a paying customer out and every turn is bounded by the usage
* check that follows. A hosted key denies, because nothing after acquisition bounds it.
* check that follows. A hosted key throws: nothing after acquisition bounds it, and a refusal
* would read as the payer's plan, which disables a schedule at once.
*/
onBalanceUnavailable: 'admit' | 'deny'
onBalanceUnavailable: 'admit' | 'throw'
}

/**
Expand Down Expand Up @@ -44,7 +45,8 @@ export async function payerHasPaidAccess(
verdict: options.onBalanceUnavailable,
error: getErrorMessage(error),
})
return options.onBalanceUnavailable === 'admit'
if (options.onBalanceUnavailable === 'throw') throw error
return true
}
}

Expand Down
19 changes: 13 additions & 6 deletions apps/sim/lib/billing/core/hosted-key-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,16 @@ export function isHostedKeyPaidPlanFailure(message: string | null | undefined):
export class HostedKeyRequiresPaidPlanError extends HttpError {
readonly statusCode = 402

/** @param subject - what asked for the key: a tool's name or a model id */
constructor(subject: string) {
/**
* @param subject - what asked for the key: a tool's name or a model id
* @param options.byok - whether the payer's own key can stand in; Web Search has none
*/
constructor(subject: string, options: { byok?: boolean } = {}) {
const upgrade = `Upgrade your plan (Pro starts with a ${PRO_TRIAL_DAYS}-day free trial for new subscribers)`
super(
`${subject} ${HOSTED_KEY_PAID_PLAN_PHRASE}. Upgrade your plan (Pro starts with a ${PRO_TRIAL_DAYS}-day free trial for new subscribers), or add your own API key under Settings > BYOK.`
options.byok === false
? `${subject} ${HOSTED_KEY_PAID_PLAN_PHRASE}. ${upgrade}.`
: `${subject} ${HOSTED_KEY_PAID_PLAN_PHRASE}. ${upgrade}, or add your own API key under Settings > BYOK.`
)
this.name = 'HostedKeyRequiresPaidPlanError'
}
Expand All @@ -35,8 +41,9 @@ export class HostedKeyRequiresPaidPlanError extends HttpError {
/**
* Whether a run may spend on Sim's hosted provider keys, for models and tools alike: only a payer
* with paid access ({@link payerHasPaidAccess}) may. The payer is the run's admitted attribution,
* or the workspace's payer for a surface that carries none; a workspace without a payer, or a free
* payer whose credit balance cannot be read, is refused.
* or the workspace's payer for a surface that carries none; a workspace without a payer is refused.
* A free payer whose credit balance cannot be read throws, so the run fails as a fault and not as
* the payer's plan.
*/
export async function mayUseHostedKey(
workspaceId: string | null | undefined,
Expand All @@ -59,5 +66,5 @@ export async function mayUseHostedKey(
}
}

return payer !== null && payerHasPaidAccess(payer, { onBalanceUnavailable: 'deny' })
return payer !== null && payerHasPaidAccess(payer, { onBalanceUnavailable: 'throw' })
}
Loading
Loading