Skip to content

Commit 9ded3fc

Browse files
authored
fix(billing): annual plans include a year of credits, plan switches rebase the usage limit (#10386)
* fix(billing): annual plans include a year of credits, plan switches rebase the usage limit, billing page matches the server * fix(billing): plan pricing input accepts a subscription without a plan * fix(billing): prorate annual Team seat allowance, rescale raised limits on plan switch, hold annual downgrades to renewal * fix(billing): close a switched period at its own allowance, keep a year's seat-months until it closes, dispute-aware copy * fix(billing): seat-months follow seat changes immediately, one race-safe limit rebase, test schemas carry the allowance columns * fix(billing): fractional seat-months, chosen headroom kept on upgrades, allowance and limit writes in one transaction * fix(billing): price fractional seat-months to the cent
1 parent 7504567 commit 9ded3fc

56 files changed

Lines changed: 35223 additions & 280 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/docs/content/docs/platform/costs.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ Each seven-day window from the billing period's start excludes usage up to the w
195195

196196
### Annual billing
197197

198-
Pro and Max annual subscriptions have a 15% discount while retaining their advertised included credits. Team pricing uses the same per-seat rate.
198+
Pro and Max annual subscriptions have a 15% discount while retaining their advertised included credits. An annual billing period is the whole year, so it includes twelve months of credits up front (72,000 per seat on Pro, 300,000 on Max), usable any time during the year. Team pricing uses the same per-seat rate.
199199

200200
| Plan | Monthly billing | Annual equivalent per month | Annual price per seat |
201201
| --- | --- | --- | --- |

‎apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ const PRICING_FAQS = [
3030
},
3131
{
3232
question: 'How much does Sim cost?',
33-
answer: `Pro is $${PRO_CREDIT_TIER.dollars} per user per month with ${formatCredits(PRO_CREDIT_TIER.credits)} credits a month and a weekly refresh of ${formatCredits(PRO_CREDIT_TIER.weeklyRefreshCredits)} more. Max is $${MAX_CREDIT_TIER.dollars} per user per month with ${formatCredits(MAX_CREDIT_TIER.credits)} credits a month and a weekly refresh of ${formatCredits(MAX_CREDIT_TIER.weeklyRefreshCredits)}. Annual billing costs ${ANNUAL_DISCOUNT_RATE * 100}% less for the same credits. Enterprise pricing is custom.`,
33+
answer: `Pro is $${PRO_CREDIT_TIER.dollars} per user per month with ${formatCredits(PRO_CREDIT_TIER.credits)} credits a month and a weekly refresh of ${formatCredits(PRO_CREDIT_TIER.weeklyRefreshCredits)} more. Max is $${MAX_CREDIT_TIER.dollars} per user per month with ${formatCredits(MAX_CREDIT_TIER.credits)} credits a month and a weekly refresh of ${formatCredits(MAX_CREDIT_TIER.weeklyRefreshCredits)}. Annual billing costs ${ANNUAL_DISCOUNT_RATE * 100}% less for the same credits, and includes all twelve months of credits up front to use any time during the year. Enterprise pricing is custom.`,
3434
},
3535
{
3636
question: 'What is a credit, and what does an agent run cost?',

‎apps/sim/app/api/billing/route.test.ts‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@ import {
44
billingOrganizationMock,
55
billingOrganizationMockFns,
66
} from '@sim/testing/mocks/billing-organization.mock'
7-
import {
8-
billingSubscriptionMock,
9-
billingSubscriptionMockFns,
10-
} from '@sim/testing/mocks/billing-subscription.mock'
7+
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
118
import { beforeEach, describe, expect, it, vi } from 'vitest'
129

1310
const { mockGetCreditBalanceForEntity } = vi.hoisted(() => ({
@@ -30,7 +27,6 @@ const mockGetSession = authMockFns.mockGetSession
3027
const mockGetOrganizationBillingData = billingOrganizationMockFns.mockGetOrganizationBillingData
3128
const mockGetOrganizationSubscription = billingCoreMockFns.mockGetOrganizationSubscription
3229
const mockGetPersonalBillingSummary = billingCoreMockFns.mockGetPersonalBillingSummary
33-
const mockResolveBillingInterval = billingSubscriptionMockFns.mockResolveBillingInterval
3430

3531
const PERSONAL_SUMMARY = {
3632
type: 'individual',
@@ -146,10 +142,6 @@ describe('GET /api/billing', () => {
146142
mockGetOrganizationBillingData.mockResolvedValue(ACTIVE_ORG_BILLING)
147143
mockGetOrganizationSubscription.mockResolvedValue(ACTIVE_ORG_SUBSCRIPTION)
148144
mockGetCreditBalanceForEntity.mockResolvedValue(17)
149-
mockResolveBillingInterval.mockImplementation(
150-
(subscription: { billingInterval?: string | null } | null) =>
151-
subscription?.billingInterval === 'year' ? 'year' : 'month'
152-
)
153145
})
154146

155147
it('keeps account billing personal even when an organization ID is supplied', async () => {

‎apps/sim/app/api/billing/route.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ import {
1818
getOrganizationBillingBlockState,
1919
getUpgradeWorkspaceId,
2020
} from '@/lib/billing/core/payer-context'
21-
import { resolveBillingInterval } from '@/lib/billing/core/subscription'
2221
import { getCreditBalanceForEntity } from '@/lib/billing/credits/balance'
2322
import { isPaid } from '@/lib/billing/plan-helpers'
23+
import { resolveBillingInterval } from '@/lib/billing/subscriptions/utils'
2424
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
2525

2626
const logger = createLogger('UnifiedBillingAPI')

‎apps/sim/app/api/billing/switch-plan/route.ts‎

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,19 @@
11
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
2-
import { db } from '@sim/db'
3-
import { subscription as subscriptionTable } from '@sim/db/schema'
42
import { createLogger } from '@sim/logger'
53
import { getErrorMessage, toError } from '@sim/utils/errors'
6-
import { eq } from 'drizzle-orm'
74
import { type NextRequest, NextResponse } from 'next/server'
85
import { billingSwitchPlanContract } from '@/lib/api/contracts/subscription'
96
import { parseRequest } from '@/lib/api/server'
107
import { getSession } from '@/lib/auth'
118
import { getEffectiveBillingStatus } from '@/lib/billing/core/access'
12-
import { getOrganizationSubscription } from '@/lib/billing/core/billing'
9+
import { getOrganizationSubscription, isSubscriptionOrgScoped } from '@/lib/billing/core/billing'
1310
import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization'
1411
import {
1512
getHighestPriorityPersonalSubscription,
1613
getHighestPrioritySubscription,
1714
} from '@/lib/billing/core/plan'
18-
import { writeBillingInterval } from '@/lib/billing/core/subscription'
19-
import { getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
15+
import { recordPlanSwitch } from '@/lib/billing/core/plan-switch'
16+
import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
2017
import { getPlanByName } from '@/lib/billing/plans'
2118
import { requireStripeClient } from '@/lib/billing/stripe-client'
2219
import {
@@ -80,11 +77,19 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
8077
return NextResponse.json({ error: 'No active subscription found' }, { status: 404 })
8178
}
8279

83-
const billingBlocked = hostContext
84-
? hostContext.ownerBilling.billingBlocked
85-
: (await getEffectiveBillingStatus(userId)).billingBlocked
80+
const { billingBlocked, billingBlockedReason } = hostContext
81+
? hostContext.ownerBilling
82+
: await getEffectiveBillingStatus(userId)
8683
if (!hasUsableSubscriptionAccess(sub.status, billingBlocked)) {
87-
return NextResponse.json({ error: 'An active subscription is required' }, { status: 400 })
84+
return NextResponse.json(
85+
{
86+
error:
87+
billingBlockedReason === 'dispute'
88+
? 'Plan changes are paused while a payment dispute is open. Contact support to resolve it.'
89+
: 'Your last payment failed. Update your payment method under Settings > Billing, then change your plan.',
90+
},
91+
{ status: 400 }
92+
)
8893
}
8994

9095
if (isEnterprise(sub.plan) || isEnterprise(targetPlanName)) {
@@ -130,6 +135,21 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
130135
const currentInterval = subscriptionItem.price?.recurring?.interval
131136
const targetInterval = interval ?? currentInterval ?? 'month'
132137

138+
// An annual term's usage was covered by its tier's allowance; a lower tier mid-term would
139+
// re-price that usage as overage, so the downgrade waits for renewal.
140+
if (
141+
currentInterval === 'year' &&
142+
getPlanTierCredits(targetPlanName) < getPlanTierCredits(sub.plan)
143+
) {
144+
return NextResponse.json(
145+
{
146+
error:
147+
'A lower tier is not available partway through an annual term. You can switch when your plan renews.',
148+
},
149+
{ status: 400 }
150+
)
151+
}
152+
133153
const targetPriceId =
134154
targetInterval === 'year' ? targetPlan.annualDiscountPriceId : targetPlan.priceId
135155

@@ -173,14 +193,12 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
173193
})
174194
}
175195

176-
if (!alreadyInDb) {
177-
await db
178-
.update(subscriptionTable)
179-
.set({ plan: targetPlanName })
180-
.where(eq(subscriptionTable.id, sub.id))
181-
}
182-
183-
await writeBillingInterval(sub.id, targetInterval as 'month' | 'year')
196+
await recordPlanSwitch({
197+
subscription: sub,
198+
targetPlanName,
199+
targetInterval: targetInterval as 'month' | 'year',
200+
orgScoped: await isSubscriptionOrgScoped(sub),
201+
})
184202

185203
logger.info('Subscription switched successfully', {
186204
userId,

‎apps/sim/app/api/cron/reconcile-billing-seats/route.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { toRecord } from '@sim/utils/object'
55
import { type NextRequest, NextResponse } from 'next/server'
66
import { verifyCronAuth } from '@/lib/auth/internal'
77
import { runEnterpriseSeatTrueUps } from '@/lib/billing/enterprise-seat-true-up'
8+
import { syncAnnualPlanUsageLimits } from '@/lib/billing/organization'
89
import { reconcileTeamSeatDrift } from '@/lib/billing/organizations/seat-drift'
910
import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events'
1011
import { findDeadLetteredEvents } from '@/lib/core/outbox/service'
@@ -39,7 +40,8 @@ function describeDeadLetter(event: Awaited<ReturnType<typeof findDeadLetteredEve
3940
/**
4041
* Periodic billing-seat reconciliation. Self-heals Team organizations whose
4142
* stored seat count drifted from their member count, runs the self-serve
42-
* Enterprise seat true-up (peak sampling and closed-window invoices), and reports any
43+
* Enterprise seat true-up (peak sampling and closed-window invoices), raises annual plan usage
44+
* limits to their yearly allowance, and reports any
4345
* dead-lettered Stripe seat/cancel sync events so a member who has access but
4446
* whose seat charge never synced is surfaced for manual remediation rather than
4547
* silently under-billed.
@@ -61,6 +63,13 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
6163
logger.error('Enterprise seat true-up failed', { requestId, error: toError(error).message })
6264
return null
6365
})
66+
const annualLimitsSynced = await syncAnnualPlanUsageLimits().catch((error: unknown) => {
67+
logger.error('Annual plan usage-limit sync failed', {
68+
requestId,
69+
error: toError(error).message,
70+
})
71+
return null
72+
})
6473

6574
const deadLettered = await findDeadLetteredEvents(BILLING_SYNC_EVENT_TYPES)
6675
const newSince = Date.now() - NEW_DEAD_LETTER_WINDOW_MS
@@ -93,6 +102,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
93102
requestId,
94103
...drift,
95104
seatTrueUp,
105+
annualLimitsSynced,
96106
deadLetteredBillingSyncs: deadLettered.length,
97107
})
98108

@@ -101,6 +111,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
101111
requestId,
102112
drift,
103113
seatTrueUp,
114+
annualLimitsSynced,
104115
deadLetteredBillingSyncs: deadLettered.length,
105116
})
106117
} catch (error) {

‎apps/sim/app/workspace/[workspaceId]/components/invite-modal/invite-modal.tsx‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,22 @@ export function InviteModal({
183183
const seatLimitReason = mayExceedSeatCapacity
184184
? `Only ${availableSeats} seat${availableSeats === 1 ? '' : 's'} available — invites beyond that may fail. External collaborators and existing members do not use seats.`
185185
: null
186+
/**
187+
* Tells the inviter what accepting costs, since the seat is charged then rather than now. An
188+
* organization invite needs the seat model, which only billing admins can read; a personal
189+
* workspace's invitee always joins as a new seat.
190+
*/
191+
const seatCapKind = isOrganizationInvite
192+
? organizationBillingData?.data?.seatCapKind
193+
: 'on-demand'
194+
const seatChargeHint =
195+
billingEnabled && canInvite && membership !== 'external'
196+
? seatCapKind === 'baseline'
197+
? 'New members past your contracted seats are billed at the next seat true-up.'
198+
: seatCapKind === 'on-demand'
199+
? "Each new member who accepts adds a paid seat, prorated for this period. Existing members don't add one."
200+
: null
201+
: null
186202

187203
const validateEmail = useCallback(
188204
(email: string): string | null => {
@@ -270,7 +286,7 @@ export function InviteModal({
270286
value={emails}
271287
onChange={handleEmailsChange}
272288
validate={validateEmail}
273-
hint={inviteDisabledReason ?? seatLimitReason}
289+
hint={inviteDisabledReason ?? seatLimitReason ?? seatChargeHint}
274290
placeholder={
275291
canInvite
276292
? 'Enter emails'

‎apps/sim/app/workspace/[workspaceId]/settings/components/billing/billing.tsx‎

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ import { getErrorMessage } from '@sim/utils/errors'
1919
import { formatDate } from '@sim/utils/formatting'
2020
import { useRouter } from 'next/navigation'
2121
import { useSession, useSubscription } from '@/lib/auth/client'
22-
import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants'
23-
import { CREDIT_MULTIPLIER, formatCreditCost } from '@/lib/billing/credits/conversion'
22+
import { ANNUAL_DISCOUNT_RATE, ON_DEMAND_UNLIMITED } from '@/lib/billing/constants'
23+
import { formatCreditCost } from '@/lib/billing/credits/conversion'
2424
import {
2525
getCoveredUsage,
2626
getIsOnDemandActive,
@@ -29,7 +29,6 @@ import {
2929
} from '@/lib/billing/on-demand'
3030
import {
3131
getDisplayPlanName,
32-
getPlanTierCredits,
3332
getPlanTierDollars,
3433
isEnterprise,
3534
isFree,
@@ -84,6 +83,13 @@ const INVOICE_STATUS_BADGES: Record<string, InvoiceStatusBadge> = {
8483
void: { variant: 'gray', label: 'Void' },
8584
}
8685

86+
/** A plan's effective monthly price: the annual price spread over twelve months on annual billing. */
87+
function formatMonthlyPrice(plan: string, billingInterval: string | undefined): string {
88+
const monthly =
89+
getPlanTierDollars(plan) * (billingInterval === 'year' ? 1 - ANNUAL_DISCOUNT_RATE : 1)
90+
return `$${Number.isInteger(monthly) ? monthly : monthly.toFixed(2)}`
91+
}
92+
8793
function getPeriodEndLabel(isCancelledAtPeriodEnd: boolean, isTrialing: boolean): string {
8894
if (isCancelledAtPeriodEnd) return 'Access until'
8995
if (isTrialing) return 'Free trial ends'
@@ -249,7 +255,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
249255
const planIncludedAmount =
250256
subscription.isOrgScoped && organizationBilling
251257
? organizationBilling.minimumBillingAmount
252-
: getPlanTierCredits(subscription.plan) / CREDIT_MULTIPLIER
258+
: (subscriptionData?.data?.includedUsage ?? 0)
253259

254260
const effectiveUsageLimit =
255261
subscription.isOrgScoped && organizationBilling
@@ -293,6 +299,10 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
293299
covered,
294300
})
295301

302+
const hasUsablePaidAccess = subscription.isPaid
303+
? hasUsableSubscriptionAccess(subscription.status, isBlocked)
304+
: false
305+
296306
const permissions = getSubscriptionPermissions(
297307
{
298308
isFree: subscription.isFree,
@@ -302,15 +312,22 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
302312
isPaid: subscription.isPaid,
303313
isOrgScoped: subscription.isOrgScoped,
304314
isEnterpriseSelfServe: enterpriseSelfServe !== null,
315+
hasUsableAccess: hasUsablePaidAccess,
305316
plan: subscription.plan || 'free',
306317
status: subscription.status || 'inactive',
307318
},
308319
{ isTeamAdmin, userRole: userRole || 'member' }
309320
)
310321

311-
const hasUsablePaidAccess = subscription.isPaid
312-
? hasUsableSubscriptionAccess(subscription.status, isBlocked)
313-
: false
322+
/** A failed payment or an open dispute pauses the plan's usage. */
323+
const hasPaymentProblem = subscription.isPaid && !hasUsablePaidAccess
324+
const billingBlockedReason = isOrganizationScope
325+
? organizationBilling?.billingBlockedReason
326+
: subscriptionData?.data?.billingBlockedReason
327+
const paymentProblemLabel =
328+
billingBlockedReason === 'dispute'
329+
? 'Usage is paused while a payment dispute is open. Contact support to resolve it'
330+
: 'Payment failed. Update your payment method to resume usage'
314331

315332
const isTogglingOnDemand = updateUserLimit.isPending || updateOrgLimit.isPending
316333

@@ -479,7 +496,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
479496
? 'Choose a new plan for this organization'
480497
: subscription.isEnterprise
481498
? 'Custom pricing'
482-
: `$${getPlanTierDollars(subscription.plan)} per user/month, ${billingPeriod}`
499+
: `${formatMonthlyPrice(subscription.plan, billingInterval)}${isOrganizationScope ? ' per user' : ''}/month, ${billingPeriod}`
483500

484501
const periodEnd = isOrganizationScope
485502
? (organizationBilling?.billingPeriodEnd ?? null)
@@ -514,11 +531,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
514531
: usage.limit
515532

516533
// A self-serve Enterprise limit cannot fall below what the contract already covers.
517-
const usageLimitMinimum = enterpriseSelfServe
518-
? covered
519-
: subscription.isOrgScoped && organizationBilling
520-
? organizationBilling.minimumBillingAmount
521-
: getPlanTierDollars(subscription.plan)
534+
const usageLimitMinimum = enterpriseSelfServe ? covered : planIncludedAmount
522535
const explorePlansLabel = isOrganizationScope
523536
? 'Explore organization plans'
524537
: 'Explore personal plans'
@@ -655,8 +668,11 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
655668
/>
656669
) : (
657670
<div className='flex items-center justify-between'>
658-
<span className='text-[var(--text-body)] text-small'>Payment method</span>
671+
<span className='text-[var(--text-body)] text-small'>
672+
{hasPaymentProblem ? paymentProblemLabel : 'Payment method'}
673+
</span>
659674
<Chip
675+
variant={hasPaymentProblem ? 'primary' : undefined}
660676
disabled={!canManageBilling || openBillingPortal.isPending}
661677
onClick={handleOpenBillingPortal}
662678
>

‎apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/usage-limit-field/usage-limit-field.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ const AUTOSAVE_DELAY_MS = 1000
1818
const USAGE_LIMIT_INFO = (
1919
<Info side='top' className='text-[var(--text-muted)]'>
2020
{
21-
"Max usage to consume per month, set in credits — Sim's usage unit (1,000 credits = $5). By default, it's your plan's included usage, but you can set it beyond."
21+
"Max usage to consume per billing period, set in credits — Sim's usage unit (1,000 credits = $5). By default, it's your plan's included usage (a year's worth on annual billing, or the trial allowance during a trial), but you can set it beyond."
2222
}
2323
</Info>
2424
)
2525

2626
interface UsageLimitFieldProps {
27-
/** Current monthly usage limit, in dollars. */
27+
/** Current usage limit for the billing period, in dollars. */
2828
currentLimit: number
2929
/** Lowest limit the plan allows, in dollars. */
3030
minimumLimit: number
@@ -37,7 +37,7 @@ interface UsageLimitFieldProps {
3737
}
3838

3939
/**
40-
* Editable monthly usage-limit field. Seeds from the resolved limit and
40+
* Editable usage-limit field. Seeds from the resolved limit and
4141
* auto-saves a debounced, validated value to either the user or the
4242
* organization — matching the Subscription tab's edit logic. When the viewer
4343
* cannot edit (e.g. a non-admin team member) the resolved value is shown

‎apps/sim/app/workspace/[workspaceId]/settings/components/billing/subscription-permissions.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ export interface SubscriptionState {
3232
isOrgScoped: boolean
3333
/** An Enterprise contract an admin opted into self-serve usage limits, seats, and payment. */
3434
isEnterpriseSelfServe: boolean
35+
/** Active or trialing and not billing-blocked; a past-due or blocked plan cannot change limits. */
36+
hasUsableAccess: boolean
3537
plan: string
3638
status: string
3739
}
@@ -67,7 +69,10 @@ export function getSubscriptionPermissions(
6769
canManageTeam: isOrgScoped && isTeamAdmin && !isEnterprise,
6870
canManageBilling,
6971
canManageEnterprisePayment,
70-
canEditUsageLimit: (canManageBilling || canManageEnterprisePayment) && !isTrialing,
72+
canEditUsageLimit:
73+
(canManageBilling || canManageEnterprisePayment) &&
74+
!isTrialing &&
75+
subscription.hasUsableAccess,
7176
canCancelSubscription: isPaid && !isEnterprise && orgAdminOrSolo,
7277
showTeamMemberView: orgMemberOnly,
7378
showUpgradePlans:

0 commit comments

Comments
 (0)