Skip to content

Commit b7111b2

Browse files
committed
fix(billing): trial-aware usage card, personal-only trial credit base, trial_card user_id index
- The usage-limit card told a personal trial to increase a limit it cannot edit; it now says usage resumes when the trial ends. Payers carry their subscription status for this. - setUsageLimitForCredits applies the trial allowance only to a personal pool; an organization keeps its seat-priced plan base, as every other org limit path does. - 0472 indexes trial_card(user_id) for the claim lookup and the ON DELETE SET NULL cleanup.
1 parent dbe0108 commit b7111b2

9 files changed

Lines changed: 33993 additions & 23 deletions

File tree

‎apps/sim/lib/billing/core/chat-access.integration.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ describe('payerHasChatAccess', () => {
7272
const userId = await createUser()
7373
const payer = {
7474
billingEntity: { type: 'user' as const, id: userId },
75-
payerSubscription: { plan: 'free' },
75+
payerSubscription: { plan: 'free', status: null },
7676
}
7777

7878
expect(await payerHasChatAccess(payer)).toBe(false)
@@ -88,7 +88,7 @@ describe('payerHasChatAccess', () => {
8888
expect(
8989
await payerHasChatAccess({
9090
billingEntity: { type: 'user', id: userId },
91-
payerSubscription: { plan: 'pro_6000' },
91+
payerSubscription: { plan: 'pro_6000', status: 'active' },
9292
})
9393
).toBe(true)
9494
})

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ const logger = createLogger('CreditPurchase')
1111

1212
/**
1313
* Sets usage limit to planBase + creditBalance.
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.
14+
* This ensures users can use their plan's included amount plus any prepaid credits. A personal
15+
* trial's base is its fixed allowance, not the plan's.
1616
*/
1717
export async function setUsageLimitForCredits(
1818
entityType: 'user' | 'organization',
@@ -23,9 +23,10 @@ export async function setUsageLimitForCredits(
2323
): Promise<void> {
2424
const { plan } = subscription
2525
try {
26-
const basePrice = isTrialingSubscription(subscription)
27-
? PRO_TRIAL_USAGE_LIMIT_DOLLARS
28-
: getPlanPricing(plan).basePrice
26+
const basePrice =
27+
entityType === 'user' && isTrialingSubscription(subscription)
28+
? PRO_TRIAL_USAGE_LIMIT_DOLLARS
29+
: getPlanPricing(plan).basePrice
2930

3031
const seatCount = seats || 1
3132
const planBase =

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

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* from start through conversion.
55
*/
66
import { db } from '@sim/db'
7-
import { subscription, trialCard, user, userStats } from '@sim/db/schema'
7+
import { organization, subscription, trialCard, user, userStats } from '@sim/db/schema'
88
import { generateId } from '@sim/utils/id'
99
import { eq, inArray } from 'drizzle-orm'
1010
import type Stripe from 'stripe'
@@ -17,6 +17,7 @@ import {
1717
enforceOneTrialPerCardForCheckout,
1818
getProTrialCheckoutParams,
1919
} from '@/lib/billing/trial'
20+
import { resolveUsageUpgradePayload } from '@/lib/billing/usage-upgrade'
2021

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

3637
const userIds: string[] = []
38+
const organizationIds: string[] = []
3739
const fingerprints: string[] = []
3840

3941
async function createUser(options: { freeTierEligible?: boolean } = {}): Promise<string> {
@@ -122,6 +124,9 @@ afterAll(async () => {
122124
await db.delete(subscription).where(inArray(subscription.referenceId, userIds))
123125
await db.delete(user).where(inArray(user.id, userIds))
124126
}
127+
if (organizationIds.length > 0) {
128+
await db.delete(organization).where(inArray(organization.id, organizationIds))
129+
}
125130
})
126131

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

495+
it("raises an organization's limit for credits from its seat-priced plan base, even while Stripe reports it trialing", async () => {
496+
const organizationId = `trial-org-${generateId()}`
497+
await db.insert(organization).values({
498+
id: organizationId,
499+
name: 'Trial Org',
500+
slug: organizationId,
501+
orgUsageLimit: '0',
502+
})
503+
organizationIds.push(organizationId)
504+
505+
await setUsageLimitForCredits(
506+
'organization',
507+
organizationId,
508+
{ plan: PRO_PLAN, status: 'trialing' },
509+
3,
510+
1
511+
)
512+
513+
const [org] = await db
514+
.select({ orgUsageLimit: organization.orgUsageLimit })
515+
.from(organization)
516+
.where(eq(organization.id, organizationId))
517+
expect(Number(org?.orgUsageLimit)).toBe(PRO_BASE_DOLLARS * 3 + 1)
518+
})
519+
490520
it('refuses to raise the limit during a trial', async () => {
491521
const userId = await createUser()
492522
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })
@@ -499,3 +529,38 @@ describe('the trial usage limit', () => {
499529
expect(await readLimit(userId)).toBe(PRO_TRIAL_USAGE_LIMIT_DOLLARS)
500530
})
501531
})
532+
533+
describe('the usage limit card', () => {
534+
it('tells a trialing payer usage resumes when the trial ends instead of offering a limit increase', async () => {
535+
const userId = `trial-payer-${generateId()}`
536+
537+
const card = await resolveUsageUpgradePayload(userId, {
538+
billingEntity: { type: 'user', id: userId },
539+
payerSubscription: { plan: PRO_PLAN, status: 'trialing' },
540+
})
541+
542+
expect(card.action).toBe('upgrade_plan')
543+
expect(card.message).toContain('free trial')
544+
})
545+
546+
it("reads the trial from the account's subscription when the payer is not known", async () => {
547+
const userId = await createUser()
548+
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })
549+
550+
const card = await resolveUsageUpgradePayload(userId)
551+
552+
expect(card.action).toBe('upgrade_plan')
553+
expect(card.message).toContain('free trial')
554+
})
555+
556+
it('still offers a converted Pro payer a limit increase', async () => {
557+
const userId = `trial-payer-${generateId()}`
558+
559+
const card = await resolveUsageUpgradePayload(userId, {
560+
billingEntity: { type: 'user', id: userId },
561+
payerSubscription: { plan: PRO_PLAN, status: 'active' },
562+
})
563+
564+
expect(card.action).toBe('increase_limit')
565+
})
566+
})

‎apps/sim/lib/billing/usage-upgrade.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,33 @@ import type { AttributedUsageLimitsResult } from '@/lib/billing/core/attribution
66
import { getHighestPrioritySubscription } from '@/lib/billing/core/plan'
77
import type { BillingEntity } from '@/lib/billing/core/usage-log'
88
import { isEnterprise, isPaid } from '@/lib/billing/plan-helpers'
9-
import { isOrgScopedSubscription } from '@/lib/billing/subscriptions/utils'
9+
import { isOrgScopedSubscription, isTrialingSubscription } from '@/lib/billing/subscriptions/utils'
1010

1111
const logger = createLogger('UsageUpgrade')
1212

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

16+
const TRIAL_ALLOWANCE_MESSAGE =
17+
"You've used the credits included in your free trial. Usage is paused until your trial ends, when your plan's full allowance starts."
18+
1619
const MEMBER_CAP_MESSAGE =
1720
"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."
1821

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

2832
/**
2933
* The upgrade card for a payer over its usage limit: a plan upgrade for a free payer, a limit
30-
* increase for a paid one, with copy naming who can raise an organization's limit. A member
34+
* increase for a paid one, with copy naming who can raise an organization's limit. A personal
35+
* trial's allowance cannot be raised, so its card says usage resumes when the trial ends. A member
3136
* over the cap their organization set gets copy naming who can raise that cap. A known payer
3237
* decides the card without a query; otherwise the actor's current subscription decides, and a
3338
* lookup that fails falls back to the plan-upgrade card.
@@ -40,15 +45,14 @@ export async function resolveUsageUpgradePayload(
4045
if (scope === 'member') {
4146
return { reason: 'usage_limit', action: 'increase_limit', message: MEMBER_CAP_MESSAGE }
4247
}
43-
let plan: string | undefined
48+
let subscription: UsageUpgradePayer['payerSubscription'] = null
4449
let orgScoped = false
4550
try {
4651
if (payer) {
47-
plan = payer.payerSubscription?.plan
52+
subscription = payer.payerSubscription
4853
orgScoped = payer.billingEntity.type === 'organization'
4954
} else {
50-
const subscription = await getHighestPrioritySubscription(userId)
51-
plan = subscription?.plan
55+
subscription = await getHighestPrioritySubscription(userId)
5256
orgScoped = isOrgScopedSubscription(subscription, userId)
5357
}
5458
} catch (error) {
@@ -57,9 +61,13 @@ export async function resolveUsageUpgradePayload(
5761
})
5862
}
5963

64+
const plan = subscription?.plan
6065
if (!plan || !isPaid(plan)) {
6166
return { reason: 'usage_limit', action: 'upgrade_plan', message: UPGRADE_PLAN_MESSAGE }
6267
}
68+
if (!orgScoped && isTrialingSubscription(subscription)) {
69+
return { reason: 'usage_limit', action: 'upgrade_plan', message: TRIAL_ALLOWANCE_MESSAGE }
70+
}
6371
// Paid plans get `increase_limit`; the copy says who can raise it when the user cannot.
6472
const message = !orgScoped
6573
? "You've reached your usage limit for this billing period. Please increase your usage limit from billing settings to continue."

‎apps/sim/lib/workspaces/host-context.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ async function resolveWorkspaceHostContextForViewer(
4949
billingEntity: ownerBilling.organizationId
5050
? { type: 'organization', id: ownerBilling.organizationId }
5151
: { type: 'user', id: access.workspace.billedAccountUserId },
52-
payerSubscription: { plan: ownerBilling.plan },
52+
payerSubscription: { plan: ownerBilling.plan, status: ownerBilling.status },
5353
}),
5454
])
5555

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
-- Indexes trial_card(user_id). The trial-card claim reads a card's and an account's claims with
2+
-- `fingerprint = $1 OR user_id = $2`, and user_id references user(id) ON DELETE SET NULL, so each
3+
-- deleted user runs `WHERE user_id = $1`. Without this index both read the whole table, which only
4+
-- grows: a claim outlives its account.
5+
--
6+
-- Replay-safety: as 0467. The build is CONCURRENTLY below an embedded COMMIT, and a replay moves
7+
-- only an INVALID index left by a failed build aside to be dropped, keeping a valid one.
8+
DO $$
9+
BEGIN
10+
IF EXISTS (
11+
SELECT 1 FROM pg_index WHERE indexrelid = to_regclass('trial_card_user_id_idx_failed')
12+
AND (indisvalid OR indrelid <> to_regclass('trial_card'))
13+
) THEN
14+
RAISE EXCEPTION 'Refusing to drop unexpected recovery index trial_card_user_id_idx_failed';
15+
END IF;
16+
IF EXISTS (
17+
SELECT 1 FROM pg_index WHERE indexrelid = to_regclass('trial_card_user_id_idx')
18+
AND indrelid = to_regclass('trial_card') AND NOT indisvalid
19+
) THEN
20+
ALTER INDEX "trial_card_user_id_idx" RENAME TO "trial_card_user_id_idx_failed";
21+
END IF;
22+
END $$;--> statement-breakpoint
23+
COMMIT;--> statement-breakpoint
24+
SET lock_timeout = 0;--> statement-breakpoint
25+
DROP INDEX CONCURRENTLY IF EXISTS "trial_card_user_id_idx_failed";--> statement-breakpoint
26+
CREATE INDEX CONCURRENTLY IF NOT EXISTS "trial_card_user_id_idx" ON "trial_card" USING btree ("user_id");--> statement-breakpoint
27+
SET lock_timeout = '5s';

0 commit comments

Comments
 (0)