Skip to content

Commit 5350d61

Browse files
committed
feat(billing): self-serve Enterprise billing — auto-pay, quarterly seat true-ups, on-demand overage
Admins opt an Enterprise contract into self-serve with a per-seat monthly rate. On a self-serve contract: - owners and admins save a card or US bank account on Stripe's hosted setup page, and the contract switches from emailed invoices to automatic payment - members may join past the contracted seats; each quarter (each month on a monthly contract) the peak seats past the contract are invoiced in arrears at the rate the window opened with - owners and admins raise their own usage limit; usage past the included allowance is billed as overage through the existing threshold billing and period close Contracts that are not self-serve keep their hard seat and usage caps. Overage, true-up, and final invoices follow the subscription's collection method, so invoiced customers get an emailed invoice instead of an open charge nothing collects.
1 parent 5bef3d8 commit 5350d61

51 files changed

Lines changed: 36426 additions & 266 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/sim/app/api/cron/reconcile-billing-seats/route.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { toError } from '@sim/utils/errors'
44
import { toRecord } from '@sim/utils/object'
55
import { type NextRequest, NextResponse } from 'next/server'
66
import { verifyCronAuth } from '@/lib/auth/internal'
7+
import { runEnterpriseSeatTrueUps } from '@/lib/billing/enterprise-seat-true-up'
78
import { reconcileTeamSeatDrift } from '@/lib/billing/organizations/seat-drift'
89
import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events'
910
import { findDeadLetteredEvents } from '@/lib/core/outbox/service'
@@ -37,7 +38,8 @@ function describeDeadLetter(event: Awaited<ReturnType<typeof findDeadLetteredEve
3738

3839
/**
3940
* Periodic billing-seat reconciliation. Self-heals Team organizations whose
40-
* stored seat count drifted from their member count, and reports any
41+
* 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
4143
* dead-lettered Stripe seat/cancel sync events so a member who has access but
4244
* whose seat charge never synced is surfaced for manual remediation rather than
4345
* silently under-billed.
@@ -54,6 +56,11 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
5456

5557
try {
5658
const drift = await reconcileTeamSeatDrift()
59+
// A failed true-up must not hide the drift and dead-letter reports below; it retries next hour.
60+
const seatTrueUp = await runEnterpriseSeatTrueUps().catch((error: unknown) => {
61+
logger.error('Enterprise seat true-up failed', { requestId, error: toError(error).message })
62+
return null
63+
})
5764

5865
const deadLettered = await findDeadLetteredEvents(BILLING_SYNC_EVENT_TYPES)
5966
const newSince = Date.now() - NEW_DEAD_LETTER_WINDOW_MS
@@ -85,13 +92,15 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
8592
logger.info('Billing seat reconciliation completed', {
8693
requestId,
8794
...drift,
95+
seatTrueUp,
8896
deadLetteredBillingSyncs: deadLettered.length,
8997
})
9098

9199
return NextResponse.json({
92100
success: true,
93101
requestId,
94102
drift,
103+
seatTrueUp,
95104
deadLetteredBillingSyncs: deadLettered.length,
96105
})
97106
} catch (error) {
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import {
2+
getOrganizationPaymentMethodContract,
3+
startOrganizationAutoPayContract,
4+
} from '@/lib/api/contracts/organization'
5+
import {
6+
defineInternalJsonRoute,
7+
internalOrchestrationErrorPolicy,
8+
internalRateLimits,
9+
internalSessionAuth,
10+
} from '@/lib/api/server/routes'
11+
import { internalBillingReadErrorPolicy } from '@/lib/api/server/routes/billing-read'
12+
import {
13+
getEnterprisePaymentMethod,
14+
startEnterpriseAutoPaySetup,
15+
} from '@/lib/billing/application/organization-billing/enterprise-payment-method'
16+
import { organizationBillingOperations } from '@/lib/billing/application/organization-billing/operations'
17+
18+
export const dynamic = 'force-dynamic'
19+
20+
export const GET = defineInternalJsonRoute({
21+
contract: getOrganizationPaymentMethodContract,
22+
auth: internalSessionAuth,
23+
operation: organizationBillingOperations.read,
24+
rateLimit: internalRateLimits.user({ bucketName: 'organization-payment-method' }),
25+
errorPolicy: internalBillingReadErrorPolicy,
26+
mapInput: ({ params }) => ({ organizationId: params.id }),
27+
useCase: getEnterprisePaymentMethod,
28+
present: (data) => ({ success: true, data }),
29+
})
30+
31+
export const POST = defineInternalJsonRoute({
32+
contract: startOrganizationAutoPayContract,
33+
auth: internalSessionAuth,
34+
operation: organizationBillingOperations.managePaymentMethod,
35+
rateLimit: internalRateLimits.user({ bucketName: 'organization-payment-method' }),
36+
errorPolicy: internalOrchestrationErrorPolicy,
37+
mapInput: ({ params, body }) => ({ organizationId: params.id, returnUrl: body.returnUrl }),
38+
useCase: startEnterpriseAutoPaySetup,
39+
present: (data) => data,
40+
})
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { getErrorMessage } from '@sim/utils/errors'
2+
import { revertDashboardEnterpriseToInvoicing } from '@/lib/admin/dashboard'
3+
import { adminDashboardRevertToInvoicingContract } from '@/lib/api/contracts/v1/admin/dashboard'
4+
import { parseRequest } from '@/lib/api/server'
5+
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
6+
import { getAdminAuditActor } from '@/app/api/v1/admin/dashboard/actor'
7+
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
8+
import {
9+
adminBadRequestResponse,
10+
adminInvalidJsonResponse,
11+
adminValidationErrorResponse,
12+
singleResponse,
13+
} from '@/app/api/v1/admin/responses'
14+
15+
export const POST = withRouteHandler(
16+
withAdminAuthParams<{ id: string }>(async (request, context) => {
17+
const parsed = await parseRequest(adminDashboardRevertToInvoicingContract, request, context, {
18+
validationErrorResponse: adminValidationErrorResponse,
19+
invalidJsonResponse: adminInvalidJsonResponse,
20+
})
21+
if (!parsed.success) return parsed.response
22+
try {
23+
await revertDashboardEnterpriseToInvoicing(
24+
parsed.data.params.id,
25+
await getAdminAuditActor(request)
26+
)
27+
return singleResponse({ success: true as const })
28+
} catch (error) {
29+
return adminBadRequestResponse(getErrorMessage(error, 'Failed to return to invoice payment'))
30+
}
31+
})
32+
)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { getErrorMessage } from '@sim/utils/errors'
2+
import { updateDashboardEnterpriseSelfServe } from '@/lib/admin/dashboard'
3+
import { adminDashboardUpdateSelfServeContract } from '@/lib/api/contracts/v1/admin/dashboard'
4+
import { parseRequest } from '@/lib/api/server'
5+
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
6+
import { getAdminAuditActor } from '@/app/api/v1/admin/dashboard/actor'
7+
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
8+
import {
9+
adminBadRequestResponse,
10+
adminInvalidJsonResponse,
11+
adminValidationErrorResponse,
12+
singleResponse,
13+
} from '@/app/api/v1/admin/responses'
14+
15+
export const PATCH = withRouteHandler(
16+
withAdminAuthParams<{ id: string }>(async (request, context) => {
17+
const parsed = await parseRequest(adminDashboardUpdateSelfServeContract, request, context, {
18+
validationErrorResponse: adminValidationErrorResponse,
19+
invalidJsonResponse: adminInvalidJsonResponse,
20+
})
21+
if (!parsed.success) return parsed.response
22+
try {
23+
await updateDashboardEnterpriseSelfServe(
24+
parsed.data.params.id,
25+
parsed.data.body,
26+
await getAdminAuditActor(request)
27+
)
28+
return singleResponse({ success: true as const })
29+
} catch (error) {
30+
return adminBadRequestResponse(getErrorMessage(error, 'Failed to update self-serve billing'))
31+
}
32+
})
33+
)

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

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ import { buildUpgradeHref } from '@/lib/billing/upgrade-reasons'
4848
import { getBaseUrl } from '@/lib/core/utils/urls'
4949
import { AwsMarketplaceSubscriptionSection } from '@/app/workspace/[workspaceId]/settings/components/billing/components/aws-marketplace-subscription-section/aws-marketplace-subscription-section'
5050
import { CreditUsageSection } from '@/app/workspace/[workspaceId]/settings/components/billing/components/credit-usage-section/credit-usage-section'
51+
import { EnterprisePaymentMethodRow } from '@/app/workspace/[workspaceId]/settings/components/billing/components/enterprise-payment-method-row/enterprise-payment-method-row'
52+
import { EnterpriseSeatsSection } from '@/app/workspace/[workspaceId]/settings/components/billing/components/enterprise-seats-section/enterprise-seats-section'
5153
import { UsageLimitField } from '@/app/workspace/[workspaceId]/settings/components/billing/components/usage-limit-field/usage-limit-field'
5254
import { getSubscriptionPermissions } from '@/app/workspace/[workspaceId]/settings/components/billing/subscription-permissions'
5355
import { SettingsQueryErrorState } from '@/app/workspace/[workspaceId]/settings/components/settings-empty-state'
@@ -167,6 +169,9 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
167169
const openBillingPortal = useOpenBillingPortal()
168170

169171
const organizationBilling = organizationBillingData?.data
172+
const enterpriseSelfServe = isOrganizationScope
173+
? (organizationBilling?.enterpriseSelfServe ?? null)
174+
: null
170175
const upgradeWorkspaceId = isOrganizationScope
171176
? organizationBilling?.upgradeWorkspaceId
172177
: subscriptionData?.data?.upgradeWorkspaceId
@@ -296,6 +301,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
296301
isEnterprise: subscription.isEnterprise,
297302
isPaid: subscription.isPaid,
298303
isOrgScoped: subscription.isOrgScoped,
304+
isEnterpriseSelfServe: enterpriseSelfServe !== null,
299305
plan: subscription.plan || 'free',
300306
status: subscription.status || 'inactive',
301307
},
@@ -498,16 +504,19 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
498504

499505
const canManageBilling = permissions.canManageBilling
500506
const canExplorePlans = permissions.showUpgradePlans
501-
const showUsageLimit = subscription.isPaid && !subscription.isEnterprise
502-
const showOnDemand = hasUsablePaidAccess && !subscription.isEnterprise && !isTrialing
507+
const hasEditableLimit = !subscription.isEnterprise || enterpriseSelfServe !== null
508+
const showUsageLimit = subscription.isPaid && hasEditableLimit
509+
const showOnDemand = hasUsablePaidAccess && hasEditableLimit && !isTrialing
503510

504511
const usageLimitCurrent =
505512
subscription.isOrgScoped && organizationBilling
506513
? organizationBilling.totalUsageLimit
507514
: usage.limit
508515

509-
const usageLimitMinimum =
510-
subscription.isOrgScoped && organizationBilling
516+
// A self-serve Enterprise limit cannot fall below what the contract already covers.
517+
const usageLimitMinimum = enterpriseSelfServe
518+
? covered
519+
: subscription.isOrgScoped && organizationBilling
511520
? organizationBilling.minimumBillingAmount
512521
: getPlanTierDollars(subscription.plan)
513522
const explorePlansLabel = isOrganizationScope
@@ -587,7 +596,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
587596
<Switch
588597
id='on-demand-usage'
589598
checked={isOnDemandActive}
590-
disabled={isTogglingOnDemand || !canManageBilling}
599+
disabled={isTogglingOnDemand || !permissions.canEditUsageLimit}
591600
onCheckedChange={handleToggleOnDemand}
592601
/>
593602
)}
@@ -639,15 +648,22 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
639648
</div>
640649
)}
641650

642-
<div className='flex items-center justify-between'>
643-
<span className='text-[var(--text-body)] text-small'>Payment method</span>
644-
<Chip
645-
disabled={!canManageBilling || openBillingPortal.isPending}
646-
onClick={handleOpenBillingPortal}
647-
>
648-
Manage in Stripe
649-
</Chip>
650-
</div>
651+
{enterpriseSelfServe && billingOrganizationId ? (
652+
<EnterprisePaymentMethodRow
653+
organizationId={billingOrganizationId}
654+
canManage={permissions.canManageEnterprisePayment}
655+
/>
656+
) : (
657+
<div className='flex items-center justify-between'>
658+
<span className='text-[var(--text-body)] text-small'>Payment method</span>
659+
<Chip
660+
disabled={!canManageBilling || openBillingPortal.isPending}
661+
onClick={handleOpenBillingPortal}
662+
>
663+
Manage in Stripe
664+
</Chip>
665+
</div>
666+
)}
651667

652668
{!subscription.isEnterprise && (
653669
<div className='flex items-center justify-between'>
@@ -677,6 +693,13 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
677693
</SettingsSection>
678694
)}
679695

696+
{enterpriseSelfServe && (
697+
<EnterpriseSeatsSection
698+
terms={enterpriseSelfServe}
699+
billingInterval={billingInterval ?? 'year'}
700+
/>
701+
)}
702+
680703
<AwsMarketplaceSubscriptionSection organizationId={billingOrganizationId} />
681704
{isOrganizationScope && (
682705
<AwsMarketplaceSubscriptionSection
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
'use client'
2+
3+
import { Chip, OverflowText, toast } from '@sim/emcn'
4+
import { createLogger } from '@sim/logger'
5+
import { getErrorMessage } from '@sim/utils/errors'
6+
import { useQueryState } from 'nuqs'
7+
import { AUTO_PAY_RETURN_PARAM } from '@/lib/api/contracts/organization'
8+
import { autoPayReturnParam } from '@/app/workspace/[workspaceId]/settings/components/billing/search-params'
9+
import {
10+
useOrganizationPaymentMethod,
11+
useStartOrganizationAutoPay,
12+
} from '@/hooks/queries/organization-payment-method'
13+
14+
const logger = createLogger('EnterprisePaymentMethodRow')
15+
16+
interface EnterprisePaymentMethodRowProps {
17+
organizationId: string
18+
canManage: boolean
19+
}
20+
21+
/**
22+
* How a self-serve Enterprise contract pays. Saving a card or US bank account on Stripe's page
23+
* switches renewals, seat true-ups, and overage from emailed invoices to automatic payment; on
24+
* the way back the row keeps checking until Stripe's webhook has made the switch.
25+
*/
26+
export function EnterprisePaymentMethodRow({
27+
organizationId,
28+
canManage,
29+
}: EnterprisePaymentMethodRowProps) {
30+
const [returnedFromSetup] = useQueryState(autoPayReturnParam.key, autoPayReturnParam.parser)
31+
const { data, isPending, isFetching, isError } = useOrganizationPaymentMethod(organizationId, {
32+
enabled: canManage,
33+
confirmingAutoPay: returnedFromSetup,
34+
})
35+
const startAutoPay = useStartOrganizationAutoPay()
36+
37+
const autoPay = data?.collectionMethod === 'charge_automatically'
38+
39+
const describe = () => {
40+
if (!canManage) return 'Managed by organization admins'
41+
if (isError) return 'Unavailable'
42+
if (isPending) return '—'
43+
if (autoPay) return `Auto-pay · ${data?.paymentMethod?.label ?? 'payment method on file'}`
44+
if (returnedFromSetup && isFetching) return 'Confirming payment method…'
45+
return 'Paid by invoice'
46+
}
47+
48+
const handleSetUp = () => {
49+
const returnUrl = new URL(window.location.href)
50+
returnUrl.searchParams.delete(AUTO_PAY_RETURN_PARAM)
51+
startAutoPay.mutate(
52+
{ organizationId, returnUrl: returnUrl.toString() },
53+
{
54+
onSuccess: ({ url }) => {
55+
window.location.href = url
56+
},
57+
onError: (error) => {
58+
logger.error('Failed to start auto-pay setup', { error })
59+
toast.error("Couldn't open payment setup", {
60+
description: getErrorMessage(error, 'Please try again in a moment.'),
61+
})
62+
},
63+
}
64+
)
65+
}
66+
67+
return (
68+
<div className='flex items-center justify-between gap-3'>
69+
<div className='flex min-w-0 flex-col'>
70+
<span className='text-[var(--text-body)] text-small'>Payment method</span>
71+
<OverflowText label={describe()} className='text-[var(--text-muted)] text-caption' />
72+
</div>
73+
<Chip
74+
disabled={!canManage || isPending || isError || startAutoPay.isPending}
75+
onClick={handleSetUp}
76+
>
77+
{autoPay ? 'Update' : 'Set up auto-pay'}
78+
</Chip>
79+
</div>
80+
)
81+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'use client'
2+
3+
import type { OrganizationBillingSummary } from '@/lib/api/contracts/organization'
4+
import { SettingsSection } from '@/app/workspace/[workspaceId]/settings/components/settings-section/settings-section'
5+
6+
interface EnterpriseSeatsSectionProps {
7+
terms: NonNullable<OrganizationBillingSummary['enterpriseSelfServe']>
8+
billingInterval: 'month' | 'year'
9+
}
10+
11+
function SeatRow({ label, value }: { label: string; value: string }) {
12+
return (
13+
<div className='flex items-center justify-between gap-3'>
14+
<span className='text-[var(--text-body)] text-small'>{label}</span>
15+
<span className='text-[var(--text-muted)] text-small'>{value}</span>
16+
</div>
17+
)
18+
}
19+
20+
/**
21+
* Self-serve Enterprise seat terms. Additional seats are the open true-up window's peak (a quarter,
22+
* or the month on a monthly contract), which the next true-up bills.
23+
*/
24+
export function EnterpriseSeatsSection({ terms, billingInterval }: EnterpriseSeatsSectionProps) {
25+
const trueUpWindow = billingInterval === 'year' ? 'quarter' : 'month'
26+
return (
27+
<SettingsSection label='Seats'>
28+
<div className='flex flex-col gap-4'>
29+
<SeatRow label='Contracted seats' value={String(terms.contractSeats)} />
30+
<SeatRow
31+
label='Additional seat price'
32+
value={`$${(terms.seatPriceCents / 100).toFixed(2)} per seat per month`}
33+
/>
34+
<SeatRow
35+
label={`Additional seats this ${trueUpWindow}`}
36+
value={String(terms.peakExtraSeats)}
37+
/>
38+
</div>
39+
</SettingsSection>
40+
)
41+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { parseAsBoolean } from 'nuqs/server'
2+
import { AUTO_PAY_RETURN_PARAM } from '@/lib/api/contracts/organization'
3+
4+
/**
5+
* The marker Stripe's setup page returns to: the billing page keeps checking the payment method
6+
* until the webhook has switched the contract to automatic payment.
7+
*/
8+
export const autoPayReturnParam = {
9+
key: AUTO_PAY_RETURN_PARAM,
10+
parser: parseAsBoolean.withDefault(false),
11+
} as const

0 commit comments

Comments
 (0)