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
27 changes: 11 additions & 16 deletions apps/sim/app/api/billing/switch-plan/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ import {
getHighestPriorityPersonalSubscription,
getHighestPrioritySubscription,
} from '@/lib/billing/core/plan'
import {
isSwitchBasisCurrent,
readPoolUsageSnapshot,
recordPlanSwitch,
} from '@/lib/billing/core/plan-switch'
import { readSwitchBasis, 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 @@ -142,7 +138,12 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
{ status: 409 }
)
}
if (!(await isSwitchBasisCurrent(sub))) {
const orgScoped = await isSubscriptionOrgScoped(sub)
const basis = await readSwitchBasis(sub, {
type: orgScoped ? 'organization' : 'user',
id: sub.referenceId,
})
if (!basis) {
return NextResponse.json(
{ error: 'Your plan just changed. Refresh the page and try again.' },
{ status: 409 }
Expand Down Expand Up @@ -207,15 +208,9 @@ 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 pool was read before the Stripe update, since its webhook can move the live limit first.
// A retry finds Stripe already switched, so that read is not from before the switch.
const previous = alreadyOnStripePrice ? undefined : basis.pool
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
// 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
Expand All @@ -242,7 +237,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
: undefined

await recordPlanSwitch({
subscription: sub,
subscription: basis.subscription,
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
targetPlanName,
targetInterval: targetInterval as 'month' | 'year',
orgScoped,
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/billing/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ async function assertNoPersonalTrial(userId: string): Promise<void> {
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.',
'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.',
})
}

Expand Down
32 changes: 32 additions & 0 deletions apps/sim/lib/billing/core/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,38 @@ export async function getBillingEntityBlockStatus(
}
}

/**
* Whether any account a payer's unblock clears is still marked blocked for `reason`: the user's
* own row, or any member's row of an organization. Unlike {@link getBillingEntityBlockStatus},
* which reads an organization through its owner, this sees members a fan-out blocked while the
* owner's row was cleared some other way (by another organization's recovery, or an ownership
* transfer to an unmarked member).
*/
export async function hasBillingBlockFor(
payer: { type: 'user' | 'organization'; id: string },
reason: NonNullable<BillingEntityBlockStatus['billingBlockedReason']>,
executor: DbOrTx = db
): Promise<boolean> {
const blockedFor = and(
eq(userStats.billingBlocked, true),
eq(userStats.billingBlockedReason, reason)
)
const [row] =
payer.type === 'user'
? await executor
.select({ userId: userStats.userId })
.from(userStats)
.where(and(eq(userStats.userId, payer.id), blockedFor))
.limit(1)
: await executor
.select({ userId: userStats.userId })
.from(member)
.innerJoin(userStats, eq(userStats.userId, member.userId))
.where(and(eq(member.organizationId, payer.id), blockedFor))
.limit(1)
return row !== undefined
}

/**
* Gets the effective billing blocked status for a user.
* If the user belongs to an organization, also checks whether the org owner is blocked.
Expand Down
6 changes: 5 additions & 1 deletion apps/sim/lib/billing/core/chat-access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ export async function payerHasPaidAccess(
verdict: options.onBalanceUnavailable,
error: getErrorMessage(error),
})
if (options.onBalanceUnavailable === 'throw') throw error
if (options.onBalanceUnavailable === 'throw') {
throw new Error("Couldn't verify the plan for Sim's hosted key. Try again in a moment.", {
cause: error,
})
}
return true
}
}
Expand Down
135 changes: 79 additions & 56 deletions apps/sim/lib/billing/core/plan-switch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ interface SwitchedSubscription extends OrgAllowanceInput {
* limit already at the new amount is untouched too: the Stripe webhook's floor sync can raise it
* there first. An unlimited limit stays unlimited.
*
* `previous` is the pool read before Stripe applied the change ({@link readPoolUsageSnapshot}).
* `previous` is the pool read before Stripe applied the change ({@link readSwitchBasis}).
* Given it, the headroom comes from that limit and that credit balance, so neither a webhook that
* raised the live limit first nor credit granted meanwhile changes the headroom the payer chose;
* a snapshot predates any webhook, so a limit in it at the new amount is chosen headroom.
Expand Down Expand Up @@ -80,53 +80,66 @@ export async function rebaseUsageLimit(
}
}

/**
* Whether a subscription still holds the plan and billing interval a switch was computed from.
* Read under the switch's admission claim: a switch that finished between this request's first
* read and its claim moved the plan, and computing from the stale read would count the new
* allowance as headroom the payer chose.
*/
export async function isSwitchBasisCurrent(basis: SwitchedSubscription): Promise<boolean> {
const [row] = await db
.select({
plan: subscriptionTable.plan,
billingInterval: subscriptionTable.billingInterval,
metadata: subscriptionTable.metadata,
})
.from(subscriptionTable)
.where(eq(subscriptionTable.id, basis.id))
.limit(1)
return (
row !== undefined &&
row.plan === basis.plan &&
resolveBillingInterval(row) === resolveBillingInterval(basis)
)
}

/** A usage pool's limit and prepaid credit as stored, read together before a plan switch. */
export interface PoolUsageSnapshot {
limit: string | null
creditBalance: string
}

/** Reads a pool's {@link PoolUsageSnapshot} before a plan switch, for {@link rebaseUsageLimit}. */
export async function readPoolUsageSnapshot(pool: {
type: 'user' | 'organization'
id: string
}): Promise<PoolUsageSnapshot | undefined> {
const [row] =
pool.type === 'organization'
? await db
.select({ limit: organization.orgUsageLimit, creditBalance: organization.creditBalance })
.from(organization)
.where(eq(organization.id, pool.id))
.limit(1)
: await db
.select({ limit: userStats.currentUsageLimit, creditBalance: userStats.creditBalance })
.from(userStats)
.where(eq(userStats.userId, pool.id))
.limit(1)
return row
/** What a plan switch computes from: the subscription and its usage pool, read in one snapshot. */
export interface SwitchBasis {
subscription: typeof subscriptionTable.$inferSelect
pool: PoolUsageSnapshot | undefined
}

/**
* Reads a plan switch's {@link SwitchBasis} under its admission claim, in one snapshot. Null when
* the payer, plan or interval no longer matches `basis`: a switch that finished between this
* request's first read and its claim moved it, and computing from the stale read would count the
* new allowance as headroom the payer chose, or rebase the wrong pool. A seat sync takes no claim, so the seats and allowance
* come from this read too, consistent with the pool limit they produced.
*/
export async function readSwitchBasis(
basis: SwitchedSubscription,
pool: { type: 'user' | 'organization'; id: string }
): Promise<SwitchBasis | null> {
return db.transaction(
async (tx) => {
const [current] = await tx
.select()
.from(subscriptionTable)
.where(eq(subscriptionTable.id, basis.id))
.limit(1)
if (
!current ||
current.referenceId !== basis.referenceId ||
current.plan !== basis.plan ||
resolveBillingInterval(current) !== resolveBillingInterval(basis)
) {
return null
}
const [poolRow] =
pool.type === 'organization'
? await tx
.select({
limit: organization.orgUsageLimit,
creditBalance: organization.creditBalance,
})
.from(organization)
.where(eq(organization.id, pool.id))
.limit(1)
: await tx
.select({
limit: userStats.currentUsageLimit,
creditBalance: userStats.creditBalance,
})
.from(userStats)
.where(eq(userStats.userId, pool.id))
.limit(1)
return { subscription: current, pool: poolRow }
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
},
{ isolationLevel: 'repeatable read', accessMode: 'read only' }
)
}

/**
Expand All @@ -141,6 +154,12 @@ export async function readPoolUsageSnapshot(pool: {
* written with the interval: until the subscription webhook lands, the old period with the new
* interval would price a year of usage against a month's allowance, and threshold billing would
* collect overage the old year's close then finds it never owed.
*
* Seats come from the subscription row as locked here, since a seat sync takes no switch claim and
* can land while Stripe applies the change; the old plan and interval always come from
* `subscription`, since the subscription webhook can record the new plan first. The old allowance
* is priced for the seats the limit read was taken with: `subscription`'s, which `previous` was
* read with, or the locked row's for the live limit.
*/
export async function recordPlanSwitch(params: {
subscription: SwitchedSubscription
Expand All @@ -155,22 +174,26 @@ export async function recordPlanSwitch(params: {
const trialing = !orgScoped && isTrialingSubscription(subscription)
const previousInterval = resolveBillingInterval(subscription)
const restartedPeriod = previousInterval !== targetInterval ? period : undefined
const target = {
...subscription,
plan: targetPlanName,
billingInterval: targetInterval,
...(restartedPeriod ? { periodStart: restartedPeriod.start } : {}),
}
const previousBase = orgScoped
? getOrgIncludedUsageDollars(subscription)
: getPlanPricing(subscription).basePrice
const nextBase = orgScoped ? getOrgIncludedUsageDollars(target) : getPlanPricing(target).basePrice
const includedUsage = (sub: SwitchedSubscription) =>
orgScoped ? getOrgIncludedUsageDollars(sub) : getPlanPricing(sub).basePrice
const headroomScale =
previousInterval === targetInterval ? 1 : targetInterval === 'year' ? 12 : 1 / 12

// One transaction: a retry of a half-recorded switch finds the plan already matching and would
// never rebase the limit.
await db.transaction(async (tx) => {
const [locked] = await tx
.select()
.from(subscriptionTable)
.where(eq(subscriptionTable.id, subscription.id))
.for('update')
const current = locked ?? subscription
const target = {
...current,
plan: targetPlanName,
billingInterval: targetInterval,
...(restartedPeriod ? { periodStart: restartedPeriod.start } : {}),
}
if (subscription.plan !== targetPlanName || restartedPeriod) {
await tx
.update(subscriptionTable)
Expand All @@ -189,8 +212,10 @@ export async function recordPlanSwitch(params: {
pool: orgScoped
? { type: 'organization', id: subscription.referenceId }
: { type: 'user', id: subscription.referenceId },
previousIncluded: previousBase,
nextIncluded: nextBase,
previousIncluded: includedUsage(
previous ? subscription : { ...subscription, seats: current.seats }
),
nextIncluded: includedUsage(target),
headroomScale,
previous,
},
Expand All @@ -203,7 +228,5 @@ export async function recordPlanSwitch(params: {
fromPlan: subscription.plan,
toPlan: targetPlanName,
interval: targetInterval,
previousBase,
nextBase,
})
}
Loading
Loading