Repository navigation
feat(billing): self-serve Enterprise billing — auto-pay, quarterly seat true-ups, on-demand overage #10374
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
waleedlatif1
wants to merge
5
commits into
staging
Choose a base branch
from
feat/enterprise-self-serve-billing
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+36,647
−276
Open
feat(billing): self-serve Enterprise billing — auto-pay, quarterly seat true-ups, on-demand overage #10374
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5f97496
feat(billing): self-serve Enterprise billing — auto-pay, quarterly se…
waleedlatif1 515041f
fix(billing): address self-serve review — durable invoice return, fin…
waleedlatif1 923e55b
fix(billing): spend final prepaid credit after a lagging close, open-…
waleedlatif1 c42155c
fix(billing): recheck self-serve under the contract lease before auto…
waleedlatif1 7b2d48b
fix(billing): keep a payment block while another auto-charged invoice…
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
apps/sim/app/api/organizations/[id]/payment-method/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import { | ||
| getOrganizationPaymentMethodContract, | ||
| startOrganizationAutoPayContract, | ||
| } from '@/lib/api/contracts/organization' | ||
| import { | ||
| defineInternalJsonRoute, | ||
| internalOrchestrationErrorPolicy, | ||
| internalRateLimits, | ||
| internalSessionAuth, | ||
| } from '@/lib/api/server/routes' | ||
| import { internalBillingReadErrorPolicy } from '@/lib/api/server/routes/billing-read' | ||
| import { | ||
| getEnterprisePaymentMethod, | ||
| startEnterpriseAutoPaySetup, | ||
| } from '@/lib/billing/application/organization-billing/enterprise-payment-method' | ||
| import { organizationBillingOperations } from '@/lib/billing/application/organization-billing/operations' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| export const GET = defineInternalJsonRoute({ | ||
| contract: getOrganizationPaymentMethodContract, | ||
| auth: internalSessionAuth, | ||
| operation: organizationBillingOperations.read, | ||
| rateLimit: internalRateLimits.user({ bucketName: 'organization-payment-method' }), | ||
| errorPolicy: internalBillingReadErrorPolicy, | ||
| mapInput: ({ params }) => ({ organizationId: params.id }), | ||
| useCase: getEnterprisePaymentMethod, | ||
| present: (data) => ({ success: true, data }), | ||
| }) | ||
|
|
||
| export const POST = defineInternalJsonRoute({ | ||
| contract: startOrganizationAutoPayContract, | ||
| auth: internalSessionAuth, | ||
| operation: organizationBillingOperations.managePaymentMethod, | ||
| rateLimit: internalRateLimits.user({ bucketName: 'organization-payment-method' }), | ||
| errorPolicy: internalOrchestrationErrorPolicy, | ||
| mapInput: ({ params, body }) => ({ organizationId: params.id, returnUrl: body.returnUrl }), | ||
| useCase: startEnterpriseAutoPaySetup, | ||
| present: (data) => data, | ||
| }) |
32 changes: 32 additions & 0 deletions
32
apps/sim/app/api/v1/admin/dashboard/organizations/[id]/invoice-payment/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { getErrorMessage } from '@sim/utils/errors' | ||
| import { revertDashboardEnterpriseToInvoicing } from '@/lib/admin/dashboard' | ||
| import { adminDashboardRevertToInvoicingContract } from '@/lib/api/contracts/v1/admin/dashboard' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { getAdminAuditActor } from '@/app/api/v1/admin/dashboard/actor' | ||
| import { withAdminAuthParams } from '@/app/api/v1/admin/middleware' | ||
| import { | ||
| adminBadRequestResponse, | ||
| adminInvalidJsonResponse, | ||
| adminValidationErrorResponse, | ||
| singleResponse, | ||
| } from '@/app/api/v1/admin/responses' | ||
|
|
||
| export const POST = withRouteHandler( | ||
| withAdminAuthParams<{ id: string }>(async (request, context) => { | ||
| const parsed = await parseRequest(adminDashboardRevertToInvoicingContract, request, context, { | ||
| validationErrorResponse: adminValidationErrorResponse, | ||
| invalidJsonResponse: adminInvalidJsonResponse, | ||
| }) | ||
| if (!parsed.success) return parsed.response | ||
| try { | ||
| await revertDashboardEnterpriseToInvoicing( | ||
| parsed.data.params.id, | ||
| await getAdminAuditActor(request) | ||
| ) | ||
| return singleResponse({ success: true as const }) | ||
| } catch (error) { | ||
| return adminBadRequestResponse(getErrorMessage(error, 'Failed to return to invoice payment')) | ||
| } | ||
| }) | ||
| ) |
33 changes: 33 additions & 0 deletions
33
apps/sim/app/api/v1/admin/dashboard/organizations/[id]/self-serve/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import { getErrorMessage } from '@sim/utils/errors' | ||
| import { updateDashboardEnterpriseSelfServe } from '@/lib/admin/dashboard' | ||
| import { adminDashboardUpdateSelfServeContract } from '@/lib/api/contracts/v1/admin/dashboard' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { getAdminAuditActor } from '@/app/api/v1/admin/dashboard/actor' | ||
| import { withAdminAuthParams } from '@/app/api/v1/admin/middleware' | ||
| import { | ||
| adminBadRequestResponse, | ||
| adminInvalidJsonResponse, | ||
| adminValidationErrorResponse, | ||
| singleResponse, | ||
| } from '@/app/api/v1/admin/responses' | ||
|
|
||
| export const PATCH = withRouteHandler( | ||
| withAdminAuthParams<{ id: string }>(async (request, context) => { | ||
| const parsed = await parseRequest(adminDashboardUpdateSelfServeContract, request, context, { | ||
| validationErrorResponse: adminValidationErrorResponse, | ||
| invalidJsonResponse: adminInvalidJsonResponse, | ||
| }) | ||
| if (!parsed.success) return parsed.response | ||
| try { | ||
| await updateDashboardEnterpriseSelfServe( | ||
| parsed.data.params.id, | ||
| parsed.data.body, | ||
| await getAdminAuditActor(request) | ||
| ) | ||
| return singleResponse({ success: true as const }) | ||
| } catch (error) { | ||
| return adminBadRequestResponse(getErrorMessage(error, 'Failed to update self-serve billing')) | ||
| } | ||
| }) | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
84 changes: 84 additions & 0 deletions
84
...onents/billing/components/enterprise-payment-method-row/enterprise-payment-method-row.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| 'use client' | ||
|
|
||
| import { Chip, OverflowText, toast } from '@sim/emcn' | ||
| import { createLogger } from '@sim/logger' | ||
| import { getErrorMessage } from '@sim/utils/errors' | ||
| import { useQueryState } from 'nuqs' | ||
| import { AUTO_PAY_RETURN_PARAM } from '@/lib/api/contracts/organization' | ||
| import { autoPayReturnParam } from '@/app/workspace/[workspaceId]/settings/components/billing/search-params' | ||
| import { | ||
| useOrganizationPaymentMethod, | ||
| useStartOrganizationAutoPay, | ||
| } from '@/hooks/queries/organization-payment-method' | ||
|
|
||
| const logger = createLogger('EnterprisePaymentMethodRow') | ||
|
|
||
| interface EnterprisePaymentMethodRowProps { | ||
| organizationId: string | ||
| canManage: boolean | ||
| } | ||
|
|
||
| /** | ||
| * How a self-serve Enterprise contract pays. Saving a card or US bank account on Stripe's page | ||
| * switches renewals, seat true-ups, and overage from emailed invoices to automatic payment; on | ||
| * the way back the row keeps checking until Stripe's webhook has made the switch. | ||
| */ | ||
| export function EnterprisePaymentMethodRow({ | ||
| organizationId, | ||
| canManage, | ||
| }: EnterprisePaymentMethodRowProps) { | ||
| const [returnedFromSetup] = useQueryState(autoPayReturnParam.key, autoPayReturnParam.parser) | ||
| const { data, isPending, isError, isConfirmingAutoPay } = useOrganizationPaymentMethod( | ||
| organizationId, | ||
| { | ||
| enabled: canManage, | ||
| confirmingAutoPay: returnedFromSetup, | ||
| } | ||
| ) | ||
| const startAutoPay = useStartOrganizationAutoPay() | ||
|
|
||
| const autoPay = data?.collectionMethod === 'charge_automatically' | ||
|
|
||
| const describe = () => { | ||
| if (!canManage) return 'Managed by organization admins' | ||
| if (isError) return 'Unavailable' | ||
| if (isPending) return '—' | ||
| if (autoPay) return `Auto-pay · ${data?.paymentMethod?.label ?? 'payment method on file'}` | ||
| if (isConfirmingAutoPay) return 'Confirming payment method…' | ||
| return 'Paid by invoice' | ||
| } | ||
|
|
||
| const handleSetUp = () => { | ||
| const returnUrl = new URL(window.location.href) | ||
| returnUrl.searchParams.delete(AUTO_PAY_RETURN_PARAM) | ||
| startAutoPay.mutate( | ||
| { organizationId, returnUrl: returnUrl.toString() }, | ||
| { | ||
| onSuccess: ({ url }) => { | ||
| window.location.href = url | ||
| }, | ||
| onError: (error) => { | ||
| logger.error('Failed to start auto-pay setup', { error }) | ||
| toast.error("Couldn't open payment setup", { | ||
| description: getErrorMessage(error, 'Please try again in a moment.'), | ||
| }) | ||
| }, | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| return ( | ||
| <div className='flex items-center justify-between gap-3'> | ||
| <div className='flex min-w-0 flex-col'> | ||
| <span className='text-[var(--text-body)] text-small'>Payment method</span> | ||
| <OverflowText label={describe()} className='text-[var(--text-muted)] text-caption' /> | ||
| </div> | ||
| <Chip | ||
| disabled={!canManage || isPending || isError || startAutoPay.isPending} | ||
| onClick={handleSetUp} | ||
| > | ||
| {autoPay ? 'Update' : 'Set up auto-pay'} | ||
| </Chip> | ||
| </div> | ||
| ) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.