Skip to content

Commit cdcf3c9

Browse files
committed
fix(billing): address self-serve review — durable invoice return, final credit spend, seat-cap kind in UI
1 parent 5350d61 commit cdcf3c9

19 files changed

Lines changed: 215 additions & 85 deletions

File tree

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

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import {
1414
} from '@sim/emcn'
1515
import { createLogger } from '@sim/logger'
1616
import { useSession } from '@/lib/auth/client'
17-
import { isEnterprise } from '@/lib/billing/plan-helpers'
1817
import { useDeploymentShape } from '@/lib/core/config/deployment-shape'
1918
import { buildInviteFailureMessage } from '@/lib/invitations/error-messages'
2019
import { quickValidateEmail } from '@/lib/messaging/email/validation'
@@ -167,11 +166,11 @@ export function InviteModal({
167166
const usedSeats = organizationBillingData?.data?.usedSeats ?? 0
168167
const availableSeats = Math.max(0, totalSeats - usedSeats)
169168
/**
170-
* Only Enterprise plans have a fixed seat cap that gates invites. Team seats
171-
* are provisioned when an invitee accepts, and externals never take one.
169+
* Only a fixed seat cap gates invites. Team seats are provisioned when an invitee accepts, a
170+
* self-serve Enterprise contract trues up seats past its baseline, and externals never take one.
172171
*/
173-
const isEnterpriseOrg = isEnterprise(organizationBillingData?.data?.subscriptionPlan)
174-
const hasSeatData = canViewOrganizationBilling && isEnterpriseOrg && totalSeats > 0
172+
const hasFixedSeatCap = organizationBillingData?.data?.seatCapKind === 'fixed'
173+
const hasSeatData = canViewOrganizationBilling && hasFixedSeatCap && totalSeats > 0
175174
/**
176175
* Advisory only. The server decides per email and does not charge a seat for
177176
* everyone: an existing organization member is granted access directly, and an

‎apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/enterprise-payment-method-row/enterprise-payment-method-row.tsx‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,13 @@ export function EnterprisePaymentMethodRow({
2828
canManage,
2929
}: EnterprisePaymentMethodRowProps) {
3030
const [returnedFromSetup] = useQueryState(autoPayReturnParam.key, autoPayReturnParam.parser)
31-
const { data, isPending, isFetching, isError } = useOrganizationPaymentMethod(organizationId, {
32-
enabled: canManage,
33-
confirmingAutoPay: returnedFromSetup,
34-
})
31+
const { data, isPending, isError, isConfirmingAutoPay } = useOrganizationPaymentMethod(
32+
organizationId,
33+
{
34+
enabled: canManage,
35+
confirmingAutoPay: returnedFromSetup,
36+
}
37+
)
3538
const startAutoPay = useStartOrganizationAutoPay()
3639

3740
const autoPay = data?.collectionMethod === 'charge_automatically'
@@ -41,7 +44,7 @@ export function EnterprisePaymentMethodRow({
4144
if (isError) return 'Unavailable'
4245
if (isPending) return '—'
4346
if (autoPay) return `Auto-pay · ${data?.paymentMethod?.label ?? 'payment method on file'}`
44-
if (returnedFromSetup && isFetching) return 'Confirming payment method…'
47+
if (isConfirmingAutoPay) return 'Confirming payment method…'
4548
return 'Paid by invoice'
4649
}
4750

‎apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/enterprise-seats-section/enterprise-seats-section.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@ interface EnterpriseSeatsSectionProps {
88
billingInterval: 'month' | 'year'
99
}
1010

11-
function SeatRow({ label, value }: { label: string; value: string }) {
11+
interface SeatRowProps {
12+
label: string
13+
value: string
14+
}
15+
16+
function SeatRow({ label, value }: SeatRowProps) {
1217
return (
1318
<div className='flex items-center justify-between gap-3'>
1419
<span className='text-[var(--text-body)] text-small'>{label}</span>

‎apps/sim/app/workspace/[workspaceId]/settings/components/team-management/components/team-seats-overview/team-seats-overview.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ interface TeamSeatsOverviewProps {
2222
usedSeats: number
2323
/** Outstanding invites that have not been accepted yet (do not consume a seat). */
2424
pendingSeats?: number
25+
/** A self-serve Enterprise contract, whose members may outgrow its seats and true up. */
26+
seatsAreBaseline?: boolean
2527
}
2628

2729
export function TeamSeatsOverview({
@@ -31,6 +33,7 @@ export function TeamSeatsOverview({
3133
totalSeats,
3234
usedSeats,
3335
pendingSeats = 0,
36+
seatsAreBaseline = false,
3437
}: TeamSeatsOverviewProps) {
3538
if (isLoadingSubscription) {
3639
return null
@@ -58,7 +61,7 @@ export function TeamSeatsOverview({
5861

5962
const isEnterprise = checkEnterprisePlan(subscriptionData)
6063
const isSeatDataPending = !isEnterprise && totalSeats === 0
61-
const isOverLimit = totalSeats > 0 && usedSeats > totalSeats
64+
const isOverLimit = !seatsAreBaseline && totalSeats > 0 && usedSeats > totalSeats
6265
const pillCount = Math.max(totalSeats, usedSeats, 1)
6366

6467
if (isSeatDataPending) {

‎apps/sim/app/workspace/[workspaceId]/settings/components/team-management/team-management.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,7 @@ export function TeamManagement({
443443
totalSeats={totalSeats}
444444
usedSeats={usedSeats}
445445
pendingSeats={pendingSeats}
446+
seatsAreBaseline={organizationBillingData?.data?.seatCapKind === 'baseline'}
446447
/>
447448
))}
448449

‎apps/sim/hooks/queries/organization-payment-method.ts‎

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useMutation, useQuery } from '@tanstack/react-query'
1+
import { type QueryState, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
22
import { requestJson } from '@/lib/api/client/request'
33
import {
44
getOrganizationPaymentMethodContract,
@@ -7,6 +7,9 @@ import {
77
import { organizationKeys } from '@/hooks/queries/utils/organization-keys'
88

99
const ORGANIZATION_PAYMENT_METHOD_STALE_TIME = 60 * 1000
10+
/** How often, and how many times, to re-read while auto-pay waits on Stripe's webhook. */
11+
const AUTO_PAY_CONFIRM_INTERVAL_MS = 2_000
12+
const AUTO_PAY_CONFIRM_ATTEMPTS = 15
1013

1114
async function fetchOrganizationPaymentMethod(orgId: string, signal?: AbortSignal) {
1215
const response = await requestJson(getOrganizationPaymentMethodContract, {
@@ -15,31 +18,49 @@ async function fetchOrganizationPaymentMethod(orgId: string, signal?: AbortSigna
1518
})
1619
return response.data
1720
}
18-
/** How often, and how many times, to re-read while auto-pay waits on Stripe's webhook. */
19-
const AUTO_PAY_CONFIRM_INTERVAL_MS = 2_000
20-
const AUTO_PAY_CONFIRM_ATTEMPTS = 15
21+
22+
type PaymentMethodState = QueryState<Awaited<ReturnType<typeof fetchOrganizationPaymentMethod>>>
23+
24+
/** Whether the contract has not switched to auto-pay yet and tries remain, failed reads included. */
25+
function awaitsAutoPay(state: PaymentMethodState | undefined): boolean {
26+
if (!state) return true
27+
return (
28+
state.data?.collectionMethod !== 'charge_automatically' &&
29+
state.dataUpdateCount + state.errorUpdateCount < AUTO_PAY_CONFIRM_ATTEMPTS
30+
)
31+
}
2132

2233
/**
2334
* How a self-serve Enterprise organization pays. `confirmingAutoPay` keeps re-reading after the
2435
* customer returns from Stripe's setup page, until the webhook has switched the contract to
25-
* automatic payment.
36+
* automatic payment or the tries run out; `isConfirmingAutoPay` is true for that window.
2637
*/
2738
export function useOrganizationPaymentMethod(
2839
orgId: string,
2940
options: { enabled: boolean; confirmingAutoPay: boolean }
3041
) {
31-
return useQuery({
32-
queryKey: organizationKeys.paymentMethod(orgId),
42+
const queryClient = useQueryClient()
43+
const queryKey = organizationKeys.paymentMethod(orgId)
44+
const query = useQuery({
45+
queryKey,
3346
queryFn: ({ signal }) => fetchOrganizationPaymentMethod(orgId, signal),
3447
enabled: !!orgId && options.enabled,
3548
staleTime: ORGANIZATION_PAYMENT_METHOD_STALE_TIME,
36-
refetchInterval: (query) =>
37-
options.confirmingAutoPay &&
38-
query.state.data?.collectionMethod !== 'charge_automatically' &&
39-
query.state.dataUpdateCount < AUTO_PAY_CONFIRM_ATTEMPTS
49+
refetchInterval: (current) =>
50+
options.confirmingAutoPay && awaitsAutoPay(current.state)
4051
? AUTO_PAY_CONFIRM_INTERVAL_MS
4152
: false,
4253
})
54+
return {
55+
...query,
56+
isConfirmingAutoPay:
57+
options.confirmingAutoPay &&
58+
awaitsAutoPay(
59+
queryClient.getQueryState<Awaited<ReturnType<typeof fetchOrganizationPaymentMethod>>>(
60+
queryKey
61+
)
62+
),
63+
}
4364
}
4465

4566
/** Opens Stripe's setup page that saves a payment method and turns on auto-pay. */

‎apps/sim/lib/admin/dashboard-organizations.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ describe('toDashboardConfigurationUpdate', () => {
170170
desiredTerms: null,
171171
hasUnappliedIntent: true,
172172
effectiveSeatCapacity: 20,
173+
seatsUncapped: false,
173174
configurationUpdate: {
174175
id: 'config-2',
175176
status: 'pending',

‎apps/sim/lib/admin/dashboard.ts‎

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1164,7 +1164,7 @@ export async function updateDashboardEnterpriseSelfServe(
11641164
values: { enabled: boolean; seatPriceUsd?: number; usageLimitDollars?: number },
11651165
actor: AdminMutationActor
11661166
) {
1167-
const stripeSubscriptionId = await db.transaction(async (tx) => {
1167+
await db.transaction(async (tx) => {
11681168
await acquireOrganizationMutationLock(tx, organizationId)
11691169
const [org] = await tx
11701170
.select({ creditBalance: organization.creditBalance })
@@ -1243,13 +1243,7 @@ export async function updateDashboardEnterpriseSelfServe(
12431243
}
12441244
},
12451245
})
1246-
return subscriptionRow.stripeSubscriptionId
12471246
})
1248-
// A contract outside self-serve has no customer surface for its payment method, so it returns
1249-
// to emailed invoices rather than keep charging a method its customer can no longer replace.
1250-
if (!values.enabled && stripeSubscriptionId) {
1251-
await setEnterpriseInvoicePayment(stripeSubscriptionId)
1252-
}
12531247
recordAudit({
12541248
actorId: actor.id,
12551249
actorName: actor.name,
@@ -1265,17 +1259,9 @@ export async function updateDashboardEnterpriseSelfServe(
12651259
}
12661260

12671261
/**
1268-
* Returns an Enterprise contract from automatic payment to emailed invoices due in 30 days. Only
1269-
* invoices created afterwards change; the saved payment method stays on file.
1262+
* Returns a self-serve Enterprise contract from automatic payment to emailed invoices due in 30
1263+
* days. Only invoices created afterwards change; the saved payment method stays on file.
12701264
*/
1271-
async function setEnterpriseInvoicePayment(stripeSubscriptionId: string) {
1272-
await requireStripeClient().subscriptions.update(stripeSubscriptionId, {
1273-
collection_method: 'send_invoice',
1274-
days_until_due: INVOICE_DAYS_UNTIL_DUE,
1275-
})
1276-
}
1277-
1278-
/** Returns a self-serve Enterprise contract from automatic payment to emailed invoices. */
12791265
export async function revertDashboardEnterpriseToInvoicing(
12801266
organizationId: string,
12811267
actor: AdminMutationActor
@@ -1294,7 +1280,10 @@ export async function revertDashboardEnterpriseToInvoicing(
12941280
if (!subscriptionRow?.stripeSubscriptionId) {
12951281
throw new Error('Active Enterprise subscription not found')
12961282
}
1297-
await setEnterpriseInvoicePayment(subscriptionRow.stripeSubscriptionId)
1283+
await requireStripeClient().subscriptions.update(subscriptionRow.stripeSubscriptionId, {
1284+
collection_method: 'send_invoice',
1285+
days_until_due: INVOICE_DAYS_UNTIL_DUE,
1286+
})
12981287
recordAudit({
12991288
actorId: actor.id,
13001289
actorName: actor.name,

‎apps/sim/lib/api/contracts/organization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,7 @@ const organizationPlanSeatsResponseSchema = z.object({
641641
usedSeats: z.number().int().nonnegative(),
642642
membersTotal: z.number().int().nonnegative(),
643643
hasEnterprisePlan: z.boolean(),
644+
seatCapKind: z.enum(['fixed', 'baseline', 'on-demand']).nullable(),
644645
}),
645646
})
646647

‎apps/sim/lib/billing/application/organization-billing/get-organization-billing-summary.ts‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,16 @@ export interface OrganizationBillingSummaryResult {
5959
| null
6060
}
6161

62-
/** The open true-up window's peak seats past the contract; 0 before its first sample. */
63-
async function getOpenTrueUpExtraSeats(subscriptionId: string): Promise<number> {
62+
/**
63+
* The open true-up window's peak seats past the contract and the rate it bills them at, or null
64+
* before its first sample.
65+
*/
66+
async function getOpenTrueUpWindow(subscriptionId: string) {
6467
const [window] = await dbReplica
65-
.select({ peakExtraSeats: enterpriseSeatTrueUp.peakExtraSeats })
68+
.select({
69+
peakExtraSeats: enterpriseSeatTrueUp.peakExtraSeats,
70+
seatPriceCents: enterpriseSeatTrueUp.seatPriceCents,
71+
})
6672
.from(enterpriseSeatTrueUp)
6773
.where(
6874
and(
@@ -72,7 +78,7 @@ async function getOpenTrueUpExtraSeats(subscriptionId: string): Promise<number>
7278
)
7379
.orderBy(desc(enterpriseSeatTrueUp.windowStart))
7480
.limit(1)
75-
return window?.peakExtraSeats ?? 0
81+
return window ?? null
7682
}
7783

7884
function roundCurrency(value: number): number {
@@ -172,13 +178,18 @@ export const getOrganizationBillingSummary = defineAuthorizedOrganizationBilling
172178
const selfServeTerms = entitledSubscription
173179
? getEnterpriseSelfServeTerms(entitledSubscription)
174180
: null
175-
const enterpriseSelfServe =
181+
const openWindow =
176182
entitledSubscription && selfServeTerms
177-
? {
178-
...selfServeTerms,
179-
peakExtraSeats: await getOpenTrueUpExtraSeats(entitledSubscription.id),
180-
}
183+
? await getOpenTrueUpWindow(entitledSubscription.id)
181184
: null
185+
// The open window bills at the rate it opened with, which a mid-window change does not move.
186+
const enterpriseSelfServe = selfServeTerms
187+
? {
188+
...selfServeTerms,
189+
seatPriceCents: openWindow?.seatPriceCents ?? selfServeTerms.seatPriceCents,
190+
peakExtraSeats: openWindow?.peakExtraSeats ?? 0,
191+
}
192+
: null
182193
// A hard-capped Enterprise contract includes exactly its configured limit.
183194
const minimumBillingAmount = !entitledSubscription
184195
? 0

0 commit comments

Comments
 (0)