Skip to content

Commit 238704a

Browse files
committed
fix(billing): annual plans include a year of credits, plan switches rebase the usage limit, billing page matches the server
1 parent 6b87cf8 commit 238704a

41 files changed

Lines changed: 619 additions & 205 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: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,18 @@
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'
15+
import { recordPlanSwitch } from '@/lib/billing/core/plan-switch'
1916
import { getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
2017
import { getPlanByName } from '@/lib/billing/plans'
2118
import { requireStripeClient } from '@/lib/billing/stripe-client'
@@ -84,7 +81,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
8481
? hostContext.ownerBilling.billingBlocked
8582
: (await getEffectiveBillingStatus(userId)).billingBlocked
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+
'Your last payment failed. Update your payment method under Settings > Billing, then change your plan.',
88+
},
89+
{ status: 400 }
90+
)
8891
}
8992

9093
if (isEnterprise(sub.plan) || isEnterprise(targetPlanName)) {
@@ -173,14 +176,12 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
173176
})
174177
}
175178

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')
179+
await recordPlanSwitch({
180+
subscription: sub,
181+
targetPlanName,
182+
targetInterval: targetInterval as 'month' | 'year',
183+
orgScoped: await isSubscriptionOrgScoped(sub),
184+
})
184185

185186
logger.info('Subscription switched successfully', {
186187
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: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,13 @@ 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+
/** Tells the inviter what accepting costs, since the seat is charged then rather than now. */
187+
const seatChargeHint =
188+
billingEnabled && canInvite && membership !== 'external' && !hasFixedSeatCap
189+
? organizationBillingData?.data?.seatCapKind === 'baseline'
190+
? 'Members past your contracted seats are billed at the next quarterly true-up.'
191+
: 'Each member who accepts adds a paid seat to your plan, prorated for this period.'
192+
: null
186193

187194
const validateEmail = useCallback(
188195
(email: string): string | null => {
@@ -270,7 +277,7 @@ export function InviteModal({
270277
value={emails}
271278
onChange={handleEmailsChange}
272279
validate={validateEmail}
273-
hint={inviteDisabledReason ?? seatLimitReason}
280+
hint={inviteDisabledReason ?? seatLimitReason ?? seatChargeHint}
274281
placeholder={
275282
canInvite
276283
? 'Enter emails'

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

Lines changed: 25 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,15 @@ 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 pauses the plan's usage until the payment method is fixed. */
323+
const hasPaymentProblem = subscription.isPaid && !hasUsablePaidAccess
314324

315325
const isTogglingOnDemand = updateUserLimit.isPending || updateOrgLimit.isPending
316326

@@ -479,7 +489,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
479489
? 'Choose a new plan for this organization'
480490
: subscription.isEnterprise
481491
? 'Custom pricing'
482-
: `$${getPlanTierDollars(subscription.plan)} per user/month, ${billingPeriod}`
492+
: `${formatMonthlyPrice(subscription.plan, billingInterval)}${isOrganizationScope ? ' per user' : ''}/month, ${billingPeriod}`
483493

484494
const periodEnd = isOrganizationScope
485495
? (organizationBilling?.billingPeriodEnd ?? null)
@@ -514,11 +524,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
514524
: usage.limit
515525

516526
// 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)
527+
const usageLimitMinimum = enterpriseSelfServe ? covered : planIncludedAmount
522528
const explorePlansLabel = isOrganizationScope
523529
? 'Explore organization plans'
524530
: 'Explore personal plans'
@@ -655,8 +661,13 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
655661
/>
656662
) : (
657663
<div className='flex items-center justify-between'>
658-
<span className='text-[var(--text-body)] text-small'>Payment method</span>
664+
<span className='text-[var(--text-body)] text-small'>
665+
{hasPaymentProblem
666+
? 'Payment failed. Update your payment method to resume usage'
667+
: 'Payment method'}
668+
</span>
659669
<Chip
670+
variant={hasPaymentProblem ? 'primary' : undefined}
660671
disabled={!canManageBilling || openBillingPortal.isPending}
661672
onClick={handleOpenBillingPortal}
662673
>

‎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)