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
2 changes: 1 addition & 1 deletion apps/docs/content/docs/platform/costs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ Each seven-day window from the billing period's start excludes usage up to the w

### Annual billing

Pro and Max annual subscriptions have a 15% discount while retaining their advertised included credits. Team pricing uses the same per-seat rate.
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.

| Plan | Monthly billing | Annual equivalent per month | Annual price per seat |
| --- | --- | --- | --- |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const PRICING_FAQS = [
},
{
question: 'How much does Sim cost?',
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.`,
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.`,
},
{
question: 'What is a credit, and what does an agent run cost?',
Expand Down
10 changes: 1 addition & 9 deletions apps/sim/app/api/billing/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ import {
billingOrganizationMock,
billingOrganizationMockFns,
} from '@sim/testing/mocks/billing-organization.mock'
import {
billingSubscriptionMock,
billingSubscriptionMockFns,
} from '@sim/testing/mocks/billing-subscription.mock'
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { mockGetCreditBalanceForEntity } = vi.hoisted(() => ({
Expand All @@ -30,7 +27,6 @@ const mockGetSession = authMockFns.mockGetSession
const mockGetOrganizationBillingData = billingOrganizationMockFns.mockGetOrganizationBillingData
const mockGetOrganizationSubscription = billingCoreMockFns.mockGetOrganizationSubscription
const mockGetPersonalBillingSummary = billingCoreMockFns.mockGetPersonalBillingSummary
const mockResolveBillingInterval = billingSubscriptionMockFns.mockResolveBillingInterval

const PERSONAL_SUMMARY = {
type: 'individual',
Expand Down Expand Up @@ -146,10 +142,6 @@ describe('GET /api/billing', () => {
mockGetOrganizationBillingData.mockResolvedValue(ACTIVE_ORG_BILLING)
mockGetOrganizationSubscription.mockResolvedValue(ACTIVE_ORG_SUBSCRIPTION)
mockGetCreditBalanceForEntity.mockResolvedValue(17)
mockResolveBillingInterval.mockImplementation(
(subscription: { billingInterval?: string | null } | null) =>
subscription?.billingInterval === 'year' ? 'year' : 'month'
)
})

it('keeps account billing personal even when an organization ID is supplied', async () => {
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/api/billing/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import {
getOrganizationBillingBlockState,
getUpgradeWorkspaceId,
} from '@/lib/billing/core/payer-context'
import { resolveBillingInterval } from '@/lib/billing/core/subscription'
import { getCreditBalanceForEntity } from '@/lib/billing/credits/balance'
import { isPaid } from '@/lib/billing/plan-helpers'
import { resolveBillingInterval } from '@/lib/billing/subscriptions/utils'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'

const logger = createLogger('UnifiedBillingAPI')
Expand Down
54 changes: 36 additions & 18 deletions apps/sim/app/api/billing/switch-plan/route.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { db } from '@sim/db'
import { subscription as subscriptionTable } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { getErrorMessage, toError } from '@sim/utils/errors'
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { billingSwitchPlanContract } from '@/lib/api/contracts/subscription'
import { parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { getEffectiveBillingStatus } from '@/lib/billing/core/access'
import { getOrganizationSubscription } from '@/lib/billing/core/billing'
import { getOrganizationSubscription, isSubscriptionOrgScoped } from '@/lib/billing/core/billing'
import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization'
import {
getHighestPriorityPersonalSubscription,
getHighestPrioritySubscription,
} from '@/lib/billing/core/plan'
import { writeBillingInterval } from '@/lib/billing/core/subscription'
import { getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
import { recordPlanSwitch } from '@/lib/billing/core/plan-switch'
import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
import { getPlanByName } from '@/lib/billing/plans'
import { requireStripeClient } from '@/lib/billing/stripe-client'
import {
Expand Down Expand Up @@ -80,11 +77,19 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
return NextResponse.json({ error: 'No active subscription found' }, { status: 404 })
}

const billingBlocked = hostContext
? hostContext.ownerBilling.billingBlocked
: (await getEffectiveBillingStatus(userId)).billingBlocked
const { billingBlocked, billingBlockedReason } = hostContext
? hostContext.ownerBilling
: await getEffectiveBillingStatus(userId)
if (!hasUsableSubscriptionAccess(sub.status, billingBlocked)) {
return NextResponse.json({ error: 'An active subscription is required' }, { status: 400 })
return NextResponse.json(
{
error:
billingBlockedReason === 'dispute'
? 'Plan changes are paused while a payment dispute is open. Contact support to resolve it.'
: 'Your last payment failed. Update your payment method under Settings > Billing, then change your plan.',
},
{ status: 400 }
)
}

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

// An annual term's usage was covered by its tier's allowance; a lower tier mid-term would
// re-price that usage as overage, so the downgrade waits for renewal.
if (
currentInterval === 'year' &&
getPlanTierCredits(targetPlanName) < getPlanTierCredits(sub.plan)
) {
return NextResponse.json(
{
error:
'A lower tier is not available partway through an annual term. You can switch when your plan renews.',
},
{ status: 400 }
)
}

const targetPriceId =
targetInterval === 'year' ? targetPlan.annualDiscountPriceId : targetPlan.priceId

Expand Down Expand Up @@ -173,14 +193,12 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
})
}

if (!alreadyInDb) {
await db
.update(subscriptionTable)
.set({ plan: targetPlanName })
.where(eq(subscriptionTable.id, sub.id))
}

await writeBillingInterval(sub.id, targetInterval as 'month' | 'year')
await recordPlanSwitch({
subscription: sub,
targetPlanName,
targetInterval: targetInterval as 'month' | 'year',
orgScoped: await isSubscriptionOrgScoped(sub),
})

logger.info('Subscription switched successfully', {
userId,
Expand Down
13 changes: 12 additions & 1 deletion apps/sim/app/api/cron/reconcile-billing-seats/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { toRecord } from '@sim/utils/object'
import { type NextRequest, NextResponse } from 'next/server'
import { verifyCronAuth } from '@/lib/auth/internal'
import { runEnterpriseSeatTrueUps } from '@/lib/billing/enterprise-seat-true-up'
import { syncAnnualPlanUsageLimits } from '@/lib/billing/organization'
import { reconcileTeamSeatDrift } from '@/lib/billing/organizations/seat-drift'
import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events'
import { findDeadLetteredEvents } from '@/lib/core/outbox/service'
Expand Down Expand Up @@ -39,7 +40,8 @@ function describeDeadLetter(event: Awaited<ReturnType<typeof findDeadLetteredEve
/**
* Periodic billing-seat reconciliation. Self-heals Team organizations whose
* stored seat count drifted from their member count, runs the self-serve
* Enterprise seat true-up (peak sampling and closed-window invoices), and reports any
* Enterprise seat true-up (peak sampling and closed-window invoices), raises annual plan usage
* limits to their yearly allowance, and reports any
* dead-lettered Stripe seat/cancel sync events so a member who has access but
* whose seat charge never synced is surfaced for manual remediation rather than
* silently under-billed.
Expand All @@ -61,6 +63,13 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
logger.error('Enterprise seat true-up failed', { requestId, error: toError(error).message })
return null
})
const annualLimitsSynced = await syncAnnualPlanUsageLimits().catch((error: unknown) => {
logger.error('Annual plan usage-limit sync failed', {
requestId,
error: toError(error).message,
})
return null
})

const deadLettered = await findDeadLetteredEvents(BILLING_SYNC_EVENT_TYPES)
const newSince = Date.now() - NEW_DEAD_LETTER_WINDOW_MS
Expand Down Expand Up @@ -93,6 +102,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
requestId,
...drift,
seatTrueUp,
annualLimitsSynced,
deadLetteredBillingSyncs: deadLettered.length,
})

Expand All @@ -101,6 +111,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
requestId,
drift,
seatTrueUp,
annualLimitsSynced,
deadLetteredBillingSyncs: deadLettered.length,
})
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,22 @@ export function InviteModal({
const seatLimitReason = mayExceedSeatCapacity
? `Only ${availableSeats} seat${availableSeats === 1 ? '' : 's'} available — invites beyond that may fail. External collaborators and existing members do not use seats.`
: null
/**
* Tells the inviter what accepting costs, since the seat is charged then rather than now. An
* organization invite needs the seat model, which only billing admins can read; a personal
* workspace's invitee always joins as a new seat.
*/
const seatCapKind = isOrganizationInvite
? organizationBillingData?.data?.seatCapKind
: 'on-demand'
const seatChargeHint =
billingEnabled && canInvite && membership !== 'external'
? seatCapKind === 'baseline'
? 'New members past your contracted seats are billed at the next seat true-up.'
: seatCapKind === 'on-demand'
? "Each new member who accepts adds a paid seat, prorated for this period. Existing members don't add one."
: null
: null
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved

const validateEmail = useCallback(
(email: string): string | null => {
Expand Down Expand Up @@ -270,7 +286,7 @@ export function InviteModal({
value={emails}
onChange={handleEmailsChange}
validate={validateEmail}
hint={inviteDisabledReason ?? seatLimitReason}
hint={inviteDisabledReason ?? seatLimitReason ?? seatChargeHint}
placeholder={
canInvite
? 'Enter emails'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import { getErrorMessage } from '@sim/utils/errors'
import { formatDate } from '@sim/utils/formatting'
import { useRouter } from 'next/navigation'
import { useSession, useSubscription } from '@/lib/auth/client'
import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants'
import { CREDIT_MULTIPLIER, formatCreditCost } from '@/lib/billing/credits/conversion'
import { ANNUAL_DISCOUNT_RATE, ON_DEMAND_UNLIMITED } from '@/lib/billing/constants'
import { formatCreditCost } from '@/lib/billing/credits/conversion'
import {
getCoveredUsage,
getIsOnDemandActive,
Expand All @@ -29,7 +29,6 @@ import {
} from '@/lib/billing/on-demand'
import {
getDisplayPlanName,
getPlanTierCredits,
getPlanTierDollars,
isEnterprise,
isFree,
Expand Down Expand Up @@ -84,6 +83,13 @@ const INVOICE_STATUS_BADGES: Record<string, InvoiceStatusBadge> = {
void: { variant: 'gray', label: 'Void' },
}

/** A plan's effective monthly price: the annual price spread over twelve months on annual billing. */
function formatMonthlyPrice(plan: string, billingInterval: string | undefined): string {
const monthly =
getPlanTierDollars(plan) * (billingInterval === 'year' ? 1 - ANNUAL_DISCOUNT_RATE : 1)
return `$${Number.isInteger(monthly) ? monthly : monthly.toFixed(2)}`
}

function getPeriodEndLabel(isCancelledAtPeriodEnd: boolean, isTrialing: boolean): string {
if (isCancelledAtPeriodEnd) return 'Access until'
if (isTrialing) return 'Free trial ends'
Expand Down Expand Up @@ -249,7 +255,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
const planIncludedAmount =
subscription.isOrgScoped && organizationBilling
? organizationBilling.minimumBillingAmount
: getPlanTierCredits(subscription.plan) / CREDIT_MULTIPLIER
: (subscriptionData?.data?.includedUsage ?? 0)

const effectiveUsageLimit =
subscription.isOrgScoped && organizationBilling
Expand Down Expand Up @@ -293,6 +299,10 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
covered,
})

const hasUsablePaidAccess = subscription.isPaid
? hasUsableSubscriptionAccess(subscription.status, isBlocked)
: false

const permissions = getSubscriptionPermissions(
{
isFree: subscription.isFree,
Expand All @@ -302,15 +312,22 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
isPaid: subscription.isPaid,
isOrgScoped: subscription.isOrgScoped,
isEnterpriseSelfServe: enterpriseSelfServe !== null,
hasUsableAccess: hasUsablePaidAccess,
plan: subscription.plan || 'free',
status: subscription.status || 'inactive',
},
{ isTeamAdmin, userRole: userRole || 'member' }
)

const hasUsablePaidAccess = subscription.isPaid
? hasUsableSubscriptionAccess(subscription.status, isBlocked)
: false
/** A failed payment or an open dispute pauses the plan's usage. */
const hasPaymentProblem = subscription.isPaid && !hasUsablePaidAccess
const billingBlockedReason = isOrganizationScope
? organizationBilling?.billingBlockedReason
: subscriptionData?.data?.billingBlockedReason
const paymentProblemLabel =
billingBlockedReason === 'dispute'
? 'Usage is paused while a payment dispute is open. Contact support to resolve it'
: 'Payment failed. Update your payment method to resume usage'

const isTogglingOnDemand = updateUserLimit.isPending || updateOrgLimit.isPending

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

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

// A self-serve Enterprise limit cannot fall below what the contract already covers.
const usageLimitMinimum = enterpriseSelfServe
? covered
: subscription.isOrgScoped && organizationBilling
? organizationBilling.minimumBillingAmount
: getPlanTierDollars(subscription.plan)
const usageLimitMinimum = enterpriseSelfServe ? covered : planIncludedAmount
const explorePlansLabel = isOrganizationScope
? 'Explore organization plans'
: 'Explore personal plans'
Expand Down Expand Up @@ -655,8 +668,11 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
/>
) : (
<div className='flex items-center justify-between'>
<span className='text-[var(--text-body)] text-small'>Payment method</span>
<span className='text-[var(--text-body)] text-small'>
{hasPaymentProblem ? paymentProblemLabel : 'Payment method'}
</span>
<Chip
variant={hasPaymentProblem ? 'primary' : undefined}
disabled={!canManageBilling || openBillingPortal.isPending}
onClick={handleOpenBillingPortal}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ const AUTOSAVE_DELAY_MS = 1000
const USAGE_LIMIT_INFO = (
<Info side='top' className='text-[var(--text-muted)]'>
{
"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."
"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."
}
</Info>
)

interface UsageLimitFieldProps {
/** Current monthly usage limit, in dollars. */
/** Current usage limit for the billing period, in dollars. */
currentLimit: number
/** Lowest limit the plan allows, in dollars. */
minimumLimit: number
Expand All @@ -37,7 +37,7 @@ interface UsageLimitFieldProps {
}

/**
* Editable monthly usage-limit field. Seeds from the resolved limit and
* Editable usage-limit field. Seeds from the resolved limit and
* auto-saves a debounced, validated value to either the user or the
* organization — matching the Subscription tab's edit logic. When the viewer
* cannot edit (e.g. a non-admin team member) the resolved value is shown
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export interface SubscriptionState {
isOrgScoped: boolean
/** An Enterprise contract an admin opted into self-serve usage limits, seats, and payment. */
isEnterpriseSelfServe: boolean
/** Active or trialing and not billing-blocked; a past-due or blocked plan cannot change limits. */
hasUsableAccess: boolean
plan: string
status: string
}
Expand Down Expand Up @@ -67,7 +69,10 @@ export function getSubscriptionPermissions(
canManageTeam: isOrgScoped && isTeamAdmin && !isEnterprise,
canManageBilling,
canManageEnterprisePayment,
canEditUsageLimit: (canManageBilling || canManageEnterprisePayment) && !isTrialing,
canEditUsageLimit:
(canManageBilling || canManageEnterprisePayment) &&
!isTrialing &&
subscription.hasUsableAccess,
canCancelSubscription: isPaid && !isEnterprise && orgAdminOrSolo,
showTeamMemberView: orgMemberOnly,
showUpgradePlans:
Expand Down
Loading
Loading