Skip to content

Commit 9fadfc2

Browse files
committed
fix(billing): settle trial card checks from claims, retry them, and cap trial credit grants
1 parent ffac31a commit 9fadfc2

9 files changed

Lines changed: 131 additions & 69 deletions

File tree

‎apps/sim/app/api/v1/admin/credits/route.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,6 @@ export const POST = withRouteHandler(
114114

115115
let entityType: 'user' | 'organization'
116116
let entityId: string
117-
const plan = userSubscription.plan
118117
let seats: number | null = null
119118

120119
// Route admin credits to the subscription's entity (org if org-scoped).
@@ -181,7 +180,7 @@ export const POST = withRouteHandler(
181180
newCreditBalance = Number.parseFloat(stats?.creditBalance || '0')
182181
}
183182

184-
await setUsageLimitForCredits(entityType, entityId, plan, seats, newCreditBalance)
183+
await setUsageLimitForCredits(entityType, entityId, userSubscription, seats, newCreditBalance)
185184

186185
let newUsageLimit: number
187186
if (entityType === 'organization') {

‎apps/sim/components/emails/subjects.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ export type EmailSubjectType =
1616
| 'permission-access-request-decided'
1717
| 'enterprise-subscription'
1818
| 'usage-threshold'
19+
| 'trial-usage-threshold'
20+
| 'trial-credits-exhausted'
1921
| 'free-tier-upgrade'
2022
| 'payment-failed'
2123
| 'credit-purchase'
@@ -61,6 +63,10 @@ export function getEmailSubject(type: EmailSubjectType): string {
6163
return `Your Enterprise Plan is now active on Sim`
6264
case 'usage-threshold':
6365
return `You're nearing your monthly budget on Sim`
66+
case 'trial-usage-threshold':
67+
return `You're at 80% of your trial credits on Sim`
68+
case 'trial-credits-exhausted':
69+
return `You've used your trial credits on Sim`
6470
case 'free-tier-upgrade':
6571
return `You're at 80% of your free credits on Sim`
6672
case 'payment-failed':

‎apps/sim/lib/auth/auth.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,11 @@ import {
108108
getPlans,
109109
resolvePlanFromStripeSubscription,
110110
} from '@/lib/billing/plans'
111-
import { enforceOneTrialPerCard, getProTrialCheckoutParams } from '@/lib/billing/trial'
111+
import {
112+
enforceOneTrialPerCard,
113+
enforceOneTrialPerCardForCheckout,
114+
getProTrialCheckoutParams,
115+
} from '@/lib/billing/trial'
112116
import { syncSeatsFromStripeQuantity } from '@/lib/billing/validation/seat-management'
113117
import { handleAbandonedCheckout } from '@/lib/billing/webhooks/checkout'
114118
import { handleChargeDispute, handleDisputeClosed } from '@/lib/billing/webhooks/disputes'
@@ -1648,10 +1652,21 @@ export const auth = betterAuth({
16481652
status: subscription.status,
16491653
})
16501654

1655+
// The plugin swallows this hook's errors, so a failed check must not skip the rest of
1656+
// it; `onEvent` runs the check again on the retried checkout webhook.
16511657
const keptTrial = await enforceOneTrialPerCard(
16521658
stripeSubscription,
16531659
subscription.referenceId
1654-
)
1660+
).catch((error: unknown) => {
1661+
logger.error(
1662+
'[onSubscriptionComplete] Trial card check failed; retrying via onEvent',
1663+
{
1664+
subscriptionId: subscription.id,
1665+
error: toError(error).message,
1666+
}
1667+
)
1668+
return stripeSubscription.status === 'trialing'
1669+
})
16551670

16561671
if (!planFromStripe) {
16571672
logUnresolvedStripePlan(
@@ -1899,6 +1914,10 @@ export const auth = betterAuth({
18991914
await handleSubscriptionUsageUpdate(event)
19001915
break
19011916
}
1917+
case 'checkout.session.completed': {
1918+
await enforceOneTrialPerCardForCheckout(event.data.object)
1919+
break
1920+
}
19021921
case 'checkout.session.expired': {
19031922
await handleAbandonedCheckout(event)
19041923
break

‎apps/sim/lib/billing/core/usage.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -925,7 +925,7 @@ export async function maybeSendUsageThresholdEmail(params: {
925925

926926
await sendEmail({
927927
to: email,
928-
subject: getEmailSubject('usage-threshold'),
928+
subject: getEmailSubject(trialEndsOn ? 'trial-usage-threshold' : 'usage-threshold'),
929929
html,
930930
emailType: 'notifications',
931931
})
@@ -991,7 +991,9 @@ export async function maybeSendUsageThresholdEmail(params: {
991991
to: email,
992992
subject: useFreeCopy
993993
? getEmailSubject('free-tier-exhausted')
994-
: getLimitEmailSubject('credits', 'reached'),
994+
: trialEndsOn
995+
? getEmailSubject('trial-credits-exhausted')
996+
: getLimitEmailSubject('credits', 'reached'),
995997
html,
996998
emailType: 'notifications',
997999
})

‎apps/sim/lib/billing/credits/purchase.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,30 @@ import { db } from '@sim/db'
22
import { organization, userStats } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
44
import { eq } from 'drizzle-orm'
5+
import { PRO_TRIAL_USAGE_LIMIT_DOLLARS } from '@/lib/billing/constants'
56
import { getPlanPricing } from '@/lib/billing/core/billing'
7+
import { isTrialingSubscription } from '@/lib/billing/subscriptions/utils'
68
import { toDecimal, toNumber } from '@/lib/billing/utils/decimal'
79

810
const logger = createLogger('CreditPurchase')
911

1012
/**
1113
* Sets usage limit to planBase + creditBalance.
12-
* This ensures users can use their plan's included amount plus any prepaid credits.
14+
* This ensures users can use their plan's included amount plus any prepaid credits. A trial's
15+
* base is its fixed allowance, not the plan's.
1316
*/
1417
export async function setUsageLimitForCredits(
1518
entityType: 'user' | 'organization',
1619
entityId: string,
17-
plan: string,
20+
subscription: { plan: string; status: string | null },
1821
seats: number | null,
1922
creditBalance: number
2023
): Promise<void> {
24+
const { plan } = subscription
2125
try {
22-
const { basePrice } = getPlanPricing(plan)
26+
const basePrice = isTrialingSubscription(subscription)
27+
? PRO_TRIAL_USAGE_LIMIT_DOLLARS
28+
: getPlanPricing(plan).basePrice
2329

2430
const seatCount = seats || 1
2531
const planBase =

‎apps/sim/lib/billing/trial.integration.ts‎

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type Stripe from 'stripe'
1111
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
1212
import { PRO_TRIAL_DAYS, PRO_TRIAL_USAGE_LIMIT_DOLLARS } from '@/lib/billing/constants'
1313
import { syncUsageLimitsFromSubscription, updateUserUsageLimit } from '@/lib/billing/core/usage'
14+
import { setUsageLimitForCredits } from '@/lib/billing/credits/purchase'
1415
import { enforceOneTrialPerCard, getProTrialCheckoutParams } from '@/lib/billing/trial'
1516

1617
const { stripeStub } = vi.hoisted(() => ({
@@ -282,25 +283,39 @@ describe('enforceOneTrialPerCard', () => {
282283
expect(stripeStub.subscriptions.update).toHaveBeenCalledOnce()
283284
})
284285

285-
it("ends an account's second trial without claiming its new card", async () => {
286+
it("ends an account's racing second trial and keeps the first through a redelivery", async () => {
286287
const userId = await createUser()
287-
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })
288+
const firstSubscriptionId = `sub_${generateId()}`
288289
const racingSubscriptionId = `sub_${generateId()}`
289-
await addSubscription(userId, {
290-
status: 'trialing',
291-
trialStart: new Date(),
292-
stripeSubscriptionId: racingSubscriptionId,
293-
})
294-
const fingerprint = `fp_${generateId()}`
295-
useCard(fingerprint)
290+
for (const stripeSubscriptionId of [firstSubscriptionId, racingSubscriptionId]) {
291+
await addSubscription(userId, {
292+
status: 'trialing',
293+
trialStart: new Date(),
294+
stripeSubscriptionId,
295+
})
296+
}
297+
const firstCard = `fp_${generateId()}`
296298

299+
useCard(firstCard)
297300
expect(
298-
await enforceOneTrialPerCard(trialingStripeSubscription(racingSubscriptionId, 'pm_1'), userId)
301+
await enforceOneTrialPerCard(trialingStripeSubscription(firstSubscriptionId, 'pm_1'), userId)
302+
).toBe(true)
303+
304+
useCard(`fp_${generateId()}`)
305+
expect(
306+
await enforceOneTrialPerCard(trialingStripeSubscription(racingSubscriptionId, 'pm_2'), userId)
299307
).toBe(false)
300-
expect(stripeStub.subscriptions.update).toHaveBeenCalledOnce()
308+
expect(stripeStub.subscriptions.update).toHaveBeenCalledExactlyOnceWith(
309+
racingSubscriptionId,
310+
{ trial_end: 'now' },
311+
{ idempotencyKey: `end-ineligible-trial:${racingSubscriptionId}` }
312+
)
313+
314+
useCard(firstCard)
301315
expect(
302-
await db.select().from(trialCard).where(eq(trialCard.fingerprint, fingerprint))
303-
).toHaveLength(0)
316+
await enforceOneTrialPerCard(trialingStripeSubscription(firstSubscriptionId, 'pm_1'), userId)
317+
).toBe(true)
318+
expect(stripeStub.subscriptions.update).toHaveBeenCalledOnce()
304319
})
305320

306321
it('leaves a checkout that did not start a trial alone', async () => {
@@ -340,6 +355,16 @@ describe('the trial usage limit', () => {
340355
expect(await readLimit(userId)).toBe(PRO_BASE_DOLLARS + 2)
341356
})
342357

358+
it('raises a trial limit by granted credits from the trial allowance, not the plan base', async () => {
359+
const userId = await createUser()
360+
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })
361+
await syncUsageLimitsFromSubscription(userId)
362+
363+
await setUsageLimitForCredits('user', userId, { plan: PRO_PLAN, status: 'trialing' }, null, 1)
364+
365+
expect(await readLimit(userId)).toBe(PRO_TRIAL_USAGE_LIMIT_DOLLARS + 1)
366+
})
367+
343368
it('refuses to raise the limit during a trial', async () => {
344369
const userId = await createUser()
345370
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })

‎apps/sim/lib/billing/trial.ts‎

Lines changed: 46 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { db } from '@sim/db'
22
import { subscription, trialCard, userStats } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
4-
import { and, eq, isNotNull, ne, notInArray, or } from 'drizzle-orm'
4+
import { and, asc, eq, isNotNull, notInArray, or } from 'drizzle-orm'
55
import type Stripe from 'stripe'
66
import { PRO_CREDIT_TIER, PRO_TRIAL_DAYS } from '@/lib/billing/constants'
77
import { buildPlanName } from '@/lib/billing/plan-helpers'
@@ -67,10 +67,14 @@ export async function getProTrialCheckoutParams(params: {
6767

6868
/**
6969
* Holds each card, and each account, to one Pro trial. Runs when a checkout completes: a trial
70-
* whose card already started another trial, whose account already trialed (two checkouts racing),
71-
* or whose card cannot be identified ends at once, so Stripe charges the card for the first period
72-
* as for any paid checkout. The card's claim is recorded under the subscription it started, so a
73-
* redelivered webhook finds its own claim and keeps the trial.
70+
* whose card already started another trial, whose account already has an earlier trial (two
71+
* checkouts racing), or whose card cannot be identified ends at once, so Stripe charges the card
72+
* for the first period as for any paid checkout.
73+
*
74+
* Every trial records a claim on its card, and the first claim wins: a card's winner is whichever
75+
* subscription claimed it, and an account's winner is its earliest claim. The verdict reads only
76+
* the claims, so a redelivered webhook reaches the same verdict, and a check that failed partway
77+
* is safe to run again.
7478
*
7579
* @returns whether the subscription is still in its trial
7680
*/
@@ -97,16 +101,49 @@ export async function enforceOneTrialPerCard(
97101
return false
98102
}
99103

104+
/**
105+
* Enforces {@link enforceOneTrialPerCard} for a completed checkout, from the webhook path that
106+
* Stripe retries on failure, so a check that failed in the plugin's completion hook still runs.
107+
*/
108+
export async function enforceOneTrialPerCardForCheckout(
109+
session: Stripe.Checkout.Session
110+
): Promise<void> {
111+
if (session.mode !== 'subscription' || !session.subscription || !session.client_reference_id) {
112+
return
113+
}
114+
const subscriptionId =
115+
typeof session.subscription === 'string' ? session.subscription : session.subscription.id
116+
const stripeSubscription = await requireStripeClient().subscriptions.retrieve(subscriptionId)
117+
await enforceOneTrialPerCard(stripeSubscription, session.client_reference_id)
118+
}
119+
100120
async function findTrialIneligibility(
101121
stripe: Stripe,
102122
stripeSubscription: Stripe.Subscription,
103123
userId: string
104-
): Promise<'card-unidentified' | 'account-already-trialed' | 'card-already-trialed' | null> {
105-
if (await hasEarlierTrial(userId, stripeSubscription.id)) return 'account-already-trialed'
124+
): Promise<'card-unidentified' | 'card-already-trialed' | 'account-already-trialed' | null> {
106125
const fingerprint = await getCardFingerprint(stripe, stripeSubscription.default_payment_method)
107126
if (!fingerprint) return 'card-unidentified'
108-
if (!(await claimTrialCard(fingerprint, userId, stripeSubscription.id))) {
109-
return 'card-already-trialed'
127+
128+
await db
129+
.insert(trialCard)
130+
.values({ fingerprint, userId, stripeSubscriptionId: stripeSubscription.id })
131+
.onConflictDoNothing({ target: trialCard.fingerprint })
132+
const claims = await db
133+
.select({
134+
fingerprint: trialCard.fingerprint,
135+
userId: trialCard.userId,
136+
stripeSubscriptionId: trialCard.stripeSubscriptionId,
137+
})
138+
.from(trialCard)
139+
.where(or(eq(trialCard.fingerprint, fingerprint), eq(trialCard.userId, userId)))
140+
.orderBy(asc(trialCard.createdAt), asc(trialCard.stripeSubscriptionId))
141+
142+
const cardWinner = claims.find((claim) => claim.fingerprint === fingerprint)
143+
if (cardWinner?.stripeSubscriptionId !== stripeSubscription.id) return 'card-already-trialed'
144+
const accountWinner = claims.find((claim) => claim.userId === userId)
145+
if (accountWinner?.stripeSubscriptionId !== stripeSubscription.id) {
146+
return 'account-already-trialed'
110147
}
111148
return null
112149
}
@@ -122,39 +159,3 @@ async function getCardFingerprint(
122159
: paymentMethod
123160
return resolved.card?.fingerprint ?? null
124161
}
125-
126-
async function hasEarlierTrial(userId: string, stripeSubscriptionId: string): Promise<boolean> {
127-
const [earlier] = await db
128-
.select({ id: subscription.id })
129-
.from(subscription)
130-
.where(
131-
and(
132-
eq(subscription.referenceId, userId),
133-
isNotNull(subscription.trialStart),
134-
ne(subscription.stripeSubscriptionId, stripeSubscriptionId)
135-
)
136-
)
137-
.limit(1)
138-
return Boolean(earlier)
139-
}
140-
141-
/** Claims the card for this trial; true when the claim is this subscription's. */
142-
async function claimTrialCard(
143-
fingerprint: string,
144-
userId: string,
145-
stripeSubscriptionId: string
146-
): Promise<boolean> {
147-
const [claimed] = await db
148-
.insert(trialCard)
149-
.values({ fingerprint, userId, stripeSubscriptionId })
150-
.onConflictDoNothing({ target: trialCard.fingerprint })
151-
.returning({ fingerprint: trialCard.fingerprint })
152-
if (claimed) return true
153-
154-
const [holder] = await db
155-
.select({ stripeSubscriptionId: trialCard.stripeSubscriptionId })
156-
.from(trialCard)
157-
.where(eq(trialCard.fingerprint, fingerprint))
158-
.limit(1)
159-
return holder?.stripeSubscriptionId === stripeSubscriptionId
160-
}

‎apps/sim/lib/billing/webhooks/invoices.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ async function handleCreditPurchaseSuccess(invoice: Stripe.Invoice): Promise<voi
477477
if (subscription.length > 0) {
478478
const sub = subscription[0]
479479
const newCreditBalance = await getCreditBalanceForEntity(entityType, entityId)
480-
await setUsageLimitForCredits(entityType, entityId, sub.plan, sub.seats, newCreditBalance)
480+
await setUsageLimitForCredits(entityType, entityId, sub, sub.seats, newCreditBalance)
481481
}
482482
} catch (limitError) {
483483
// Limit bump is best-effort. Customer already got credits; if the

‎apps/sim/lib/invitations/core.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,10 @@ import {
3434
} from '@/lib/billing/organizations/provision-seat'
3535
import { reconcileOrganizationSeats } from '@/lib/billing/organizations/seats'
3636
import { isPro, isTeam } from '@/lib/billing/plan-helpers'
37-
import { hasUsableSubscriptionStatus } from '@/lib/billing/subscriptions/utils'
37+
import {
38+
hasUsableSubscriptionStatus,
39+
isTrialingSubscription,
40+
} from '@/lib/billing/subscriptions/utils'
3841
import { ForbiddenOperationError } from '@/lib/core/application/forbidden'
3942
import { isBillingEnabled } from '@/lib/core/config/env-flags'
4043
import { syncWorkspaceEnvCredentials } from '@/lib/credentials/environment'
@@ -525,6 +528,7 @@ export async function getInvitationJoinPreview(
525528
if (
526529
!personalSub ||
527530
!hasUsableSubscriptionStatus(personalSub.status) ||
531+
isTrialingSubscription(personalSub) ||
528532
!(isPro(personalSub.plan) || isTeam(personalSub.plan))
529533
) {
530534
return withOutcome('blocked')

0 commit comments

Comments
 (0)