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
4 changes: 2 additions & 2 deletions apps/sim/lib/billing/core/chat-access.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ describe('payerHasChatAccess', () => {
const userId = await createUser()
const payer = {
billingEntity: { type: 'user' as const, id: userId },
payerSubscription: { plan: 'free' },
payerSubscription: { plan: 'free', status: null },
}

expect(await payerHasChatAccess(payer)).toBe(false)
Expand All @@ -88,7 +88,7 @@ describe('payerHasChatAccess', () => {
expect(
await payerHasChatAccess({
billingEntity: { type: 'user', id: userId },
payerSubscription: { plan: 'pro_6000' },
payerSubscription: { plan: 'pro_6000', status: 'active' },
})
).toBe(true)
})
Expand Down
11 changes: 6 additions & 5 deletions apps/sim/lib/billing/credits/purchase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ const logger = createLogger('CreditPurchase')

/**
* Sets usage limit to planBase + creditBalance.
* This ensures users can use their plan's included amount plus any prepaid credits. A trial's
* base is its fixed allowance, not the plan's.
* This ensures users can use their plan's included amount plus any prepaid credits. A personal
* trial's base is its fixed allowance, not the plan's.
*/
export async function setUsageLimitForCredits(
entityType: 'user' | 'organization',
Expand All @@ -23,9 +23,10 @@ export async function setUsageLimitForCredits(
): Promise<void> {
const { plan } = subscription
try {
const basePrice = isTrialingSubscription(subscription)
? PRO_TRIAL_USAGE_LIMIT_DOLLARS
: getPlanPricing(plan).basePrice
const basePrice =
entityType === 'user' && isTrialingSubscription(subscription)
? PRO_TRIAL_USAGE_LIMIT_DOLLARS
: getPlanPricing(plan).basePrice

const seatCount = seats || 1
const planBase =
Expand Down
67 changes: 66 additions & 1 deletion apps/sim/lib/billing/trial.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* from start through conversion.
*/
import { db } from '@sim/db'
import { subscription, trialCard, user, userStats } from '@sim/db/schema'
import { organization, subscription, trialCard, user, userStats } from '@sim/db/schema'
import { generateId } from '@sim/utils/id'
import { eq, inArray } from 'drizzle-orm'
import type Stripe from 'stripe'
Expand All @@ -17,6 +17,7 @@ import {
enforceOneTrialPerCardForCheckout,
getProTrialCheckoutParams,
} from '@/lib/billing/trial'
import { resolveUsageUpgradePayload } from '@/lib/billing/usage-upgrade'

const { stripeStub } = vi.hoisted(() => ({
stripeStub: {
Expand All @@ -34,6 +35,7 @@ const PRO_PLAN = 'pro_6000'
const PRO_BASE_DOLLARS = 30

const userIds: string[] = []
const organizationIds: string[] = []
const fingerprints: string[] = []

async function createUser(options: { freeTierEligible?: boolean } = {}): Promise<string> {
Expand Down Expand Up @@ -122,6 +124,9 @@ afterAll(async () => {
await db.delete(subscription).where(inArray(subscription.referenceId, userIds))
await db.delete(user).where(inArray(user.id, userIds))
}
if (organizationIds.length > 0) {
await db.delete(organization).where(inArray(organization.id, organizationIds))
}
})

describe('getProTrialCheckoutParams', () => {
Expand Down Expand Up @@ -487,6 +492,31 @@ describe('the trial usage limit', () => {
expect(await readLimit(userId)).toBe(PRO_TRIAL_USAGE_LIMIT_DOLLARS + 1)
})

it("raises an organization's limit for credits from its seat-priced plan base, even while Stripe reports it trialing", async () => {
const organizationId = `trial-org-${generateId()}`
await db.insert(organization).values({
id: organizationId,
name: 'Trial Org',
slug: organizationId,
orgUsageLimit: '0',
})
organizationIds.push(organizationId)

await setUsageLimitForCredits(
'organization',
organizationId,
{ plan: PRO_PLAN, status: 'trialing' },
3,
1
)

const [org] = await db
.select({ orgUsageLimit: organization.orgUsageLimit })
.from(organization)
.where(eq(organization.id, organizationId))
expect(Number(org?.orgUsageLimit)).toBe(PRO_BASE_DOLLARS * 3 + 1)
})

it('refuses to raise the limit during a trial', async () => {
const userId = await createUser()
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })
Expand All @@ -499,3 +529,38 @@ describe('the trial usage limit', () => {
expect(await readLimit(userId)).toBe(PRO_TRIAL_USAGE_LIMIT_DOLLARS)
})
})

describe('the usage limit card', () => {
it('tells a trialing payer usage resumes when the trial ends instead of offering a limit increase', async () => {
const userId = `trial-payer-${generateId()}`

const card = await resolveUsageUpgradePayload(userId, {
billingEntity: { type: 'user', id: userId },
payerSubscription: { plan: PRO_PLAN, status: 'trialing' },
})

expect(card.action).toBe('upgrade_plan')
expect(card.message).toContain('free trial')
})

it("reads the trial from the account's subscription when the payer is not known", async () => {
const userId = await createUser()
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })

const card = await resolveUsageUpgradePayload(userId)

expect(card.action).toBe('upgrade_plan')
expect(card.message).toContain('free trial')
})

it('still offers a converted Pro payer a limit increase', async () => {
const userId = `trial-payer-${generateId()}`

const card = await resolveUsageUpgradePayload(userId, {
billingEntity: { type: 'user', id: userId },
payerSubscription: { plan: PRO_PLAN, status: 'active' },
})

expect(card.action).toBe('increase_limit')
})
})
27 changes: 18 additions & 9 deletions apps/sim/lib/billing/usage-upgrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,33 @@ import type { AttributedUsageLimitsResult } from '@/lib/billing/core/attribution
import { getHighestPrioritySubscription } from '@/lib/billing/core/plan'
import type { BillingEntity } from '@/lib/billing/core/usage-log'
import { isEnterprise, isPaid } from '@/lib/billing/plan-helpers'
import { isOrgScopedSubscription } from '@/lib/billing/subscriptions/utils'
import { isOrgScopedSubscription, isTrialingSubscription } from '@/lib/billing/subscriptions/utils'

const logger = createLogger('UsageUpgrade')

const UPGRADE_PLAN_MESSAGE =
"You've reached your usage limit. Please upgrade your plan to continue."

const TRIAL_ALLOWANCE_MESSAGE =
"You've used the credits included in your free trial. Usage is paused until your trial ends, when your plan's full allowance starts."

const MEMBER_CAP_MESSAGE =
"You've reached the usage limit your organization set for you this billing period. Only an organization owner or admin can raise it — please ask them to continue."

/**
* The payer a run is billed to, as the upgrade card needs it: its billing entity and its
* subscription's plan. An attribution snapshot is one; a direct-v1 run's mid-run verdict carries one.
* subscription's plan and status. An attribution snapshot is one; a direct-v1 run's mid-run
* verdict carries one.
*/
export interface UsageUpgradePayer {
readonly billingEntity: Readonly<BillingEntity>
readonly payerSubscription: { readonly plan: string } | null
readonly payerSubscription: { readonly plan: string; readonly status: string | null } | null
}

/**
* The upgrade card for a payer over its usage limit: a plan upgrade for a free payer, a limit
* increase for a paid one, with copy naming who can raise an organization's limit. A member
* increase for a paid one, with copy naming who can raise an organization's limit. A personal
* trial's allowance cannot be raised, so its card says usage resumes when the trial ends. A member
* over the cap their organization set gets copy naming who can raise that cap. A known payer
* decides the card without a query; otherwise the actor's current subscription decides, and a
* lookup that fails falls back to the plan-upgrade card.
Expand All @@ -40,26 +45,30 @@ export async function resolveUsageUpgradePayload(
if (scope === 'member') {
return { reason: 'usage_limit', action: 'increase_limit', message: MEMBER_CAP_MESSAGE }
}
let plan: string | undefined
let subscription: UsageUpgradePayer['payerSubscription'] = null
let orgScoped = false
try {
if (payer) {
plan = payer.payerSubscription?.plan
subscription = payer.payerSubscription
orgScoped = payer.billingEntity.type === 'organization'
} else {
const subscription = await getHighestPrioritySubscription(userId)
plan = subscription?.plan
orgScoped = isOrgScopedSubscription(subscription, userId)
const current = await getHighestPrioritySubscription(userId)
subscription = current
orgScoped = isOrgScopedSubscription(current, userId)
}
} catch (error) {
logger.warn('Failed to determine subscription plan, defaulting to upgrade_plan', {
error: getErrorMessage(error),
})
}

const plan = subscription?.plan
if (!plan || !isPaid(plan)) {
return { reason: 'usage_limit', action: 'upgrade_plan', message: UPGRADE_PLAN_MESSAGE }
}
if (!orgScoped && isTrialingSubscription(subscription)) {
return { reason: 'usage_limit', action: 'upgrade_plan', message: TRIAL_ALLOWANCE_MESSAGE }
}
// Paid plans get `increase_limit`; the copy says who can raise it when the user cannot.
const message = !orgScoped
? "You've reached your usage limit for this billing period. Please increase your usage limit from billing settings to continue."
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/workspaces/host-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ async function resolveWorkspaceHostContextForViewer(
billingEntity: ownerBilling.organizationId
? { type: 'organization', id: ownerBilling.organizationId }
: { type: 'user', id: access.workspace.billedAccountUserId },
payerSubscription: { plan: ownerBilling.plan },
payerSubscription: { plan: ownerBilling.plan, status: ownerBilling.status },
}),
])

Expand Down
27 changes: 27 additions & 0 deletions packages/db/migrations/0472_trial_card_user_id_idx.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
-- Indexes trial_card(user_id). The trial-card claim reads a card's and an account's claims with
-- `fingerprint = $1 OR user_id = $2`, and user_id references user(id) ON DELETE SET NULL, so each
-- deleted user runs `WHERE user_id = $1`. Without this index both read the whole table, which only
-- grows: a claim outlives its account.
--
-- Replay-safety: as 0467. The build is CONCURRENTLY below an embedded COMMIT, and a replay moves
-- only an INVALID index left by a failed build aside to be dropped, keeping a valid one.
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM pg_index WHERE indexrelid = to_regclass('trial_card_user_id_idx_failed')
AND (indisvalid OR indrelid <> to_regclass('trial_card'))
) THEN
RAISE EXCEPTION 'Refusing to drop unexpected recovery index trial_card_user_id_idx_failed';
END IF;
IF EXISTS (
SELECT 1 FROM pg_index WHERE indexrelid = to_regclass('trial_card_user_id_idx')
AND indrelid = to_regclass('trial_card') AND NOT indisvalid
) THEN
ALTER INDEX "trial_card_user_id_idx" RENAME TO "trial_card_user_id_idx_failed";
END IF;
END $$;--> statement-breakpoint
COMMIT;--> statement-breakpoint
SET lock_timeout = 0;--> statement-breakpoint
DROP INDEX CONCURRENTLY IF EXISTS "trial_card_user_id_idx_failed";--> statement-breakpoint
CREATE INDEX CONCURRENTLY IF NOT EXISTS "trial_card_user_id_idx" ON "trial_card" USING btree ("user_id");--> statement-breakpoint
SET lock_timeout = '5s';
Loading