The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add purchased credit grants and spend them after free credits (#27367)
Etienne1d3b294eb356
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex 2103a5bbb53..574695b986a 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -375,6 +375,7 @@ export type ApplicationRegistrationVariable = {export enum BillingCreditGrantType {COMPENSATION = 'COMPENSATION',ONBOARDING_REWARD = 'ONBOARDING_REWARD',+ PURCHASE = 'PURCHASE',ROLLOVER = 'ROLLOVER',SALES = 'SALES'}diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeColors.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeColors.tsindex c18b7b88e7c..c5fd59e79ee 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeColors.ts+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeColors.ts@@ -10,4 +10,5 @@ export const CREDIT_GRANT_TYPE_COLORS: Record<[BillingCreditGrantType.SALES]: 'purple',[BillingCreditGrantType.ONBOARDING_REWARD]: 'blue',[BillingCreditGrantType.ROLLOVER]: 'green',+ [BillingCreditGrantType.PURCHASE]: 'turquoise',};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeLabels.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeLabels.tsindex 8b823d76afc..86f9d9eba22 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeLabels.ts+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeLabels.ts@@ -11,4 +11,5 @@ export const CREDIT_GRANT_TYPE_LABELS: Record<[BillingCreditGrantType.SALES]: msg`Sales`,[BillingCreditGrantType.ONBOARDING_REWARD]: msg`Onboarding reward`,[BillingCreditGrantType.ROLLOVER]: msg`Rollover`,+ [BillingCreditGrantType.PURCHASE]: msg`Purchase`,};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.tsindex 13dd2b18fb8..2d1a4055ce3 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts@@ -1,6 +1,5 @@import { BillingCreditGrantType } from '~/generated-admin/graphql';-// Rollover and onboarding grants are written by jobs; the server enforces ADMIN_GRANTABLE_CREDIT_GRANT_TYPES too.export const GRANTABLE_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [BillingCreditGrantType.COMPENSATION,BillingCreditGrantType.SALES,diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791470452911-add-purchase-to-billing-credit-grant-type.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791470452911-add-purchase-to-billing-credit-grant-type.tsnew file mode 100644index 00000000000..798912987b6--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791470452911-add-purchase-to-billing-credit-grant-type.ts@@ -0,0 +1,25 @@+import { QueryRunner } from 'typeorm';++import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';++@RegisteredInstanceCommand('2.46.0', 1791470452911)+export class AddPurchaseToBillingCreditGrantTypeFastInstanceCommand implements FastInstanceCommand {+ public async up(queryRunner: QueryRunner): Promise<void> {+ const billingCreditGrantTableRows = await queryRunner.query(+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'billingCreditGrant'`,+ );+ const isBillingCreditGrantTablePresent =+ billingCreditGrantTableRows.length > 0;++ if (!isBillingCreditGrantTablePresent) {+ return;+ }++ await queryRunner.query(+ `ALTER TYPE "core"."billingCreditGrant_type_enum" ADD VALUE IF NOT EXISTS 'PURCHASE'`,+ );+ }++ public async down(_queryRunner: QueryRunner): Promise<void> {}+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.tsindex 6bf37bd06d7..5bfcdbb23e4 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts@@ -236,6 +236,7 @@ import { AddUpgradeMigrationWorkspaceIdCreatedAtIndexConcurrentlySlowInstanceComimport { AddPayloadToPendingWakeUpFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791438611736-add-payload-to-pending-wake-up';import { MoveAgentRunSuspensionsToPendingWakeUpsSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-slow-1791438611737-move-agent-run-suspensions-to-pending-wake-ups';import { RestoreAgentEvaluationInputsFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791464994704-restore-agent-evaluation-inputs';+import { AddPurchaseToBillingCreditGrantTypeFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791470452911-add-purchase-to-billing-credit-grant-type';export const INSTANCE_COMMANDS = [AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,@@ -474,4 +475,5 @@ export const INSTANCE_COMMANDS = [AddPayloadToPendingWakeUpFastInstanceCommand,MoveAgentRunSuspensionsToPendingWakeUpsSlowInstanceCommand,RestoreAgentEvaluationInputsFastInstanceCommand,+ AddPurchaseToBillingCreditGrantTypeFastInstanceCommand,];diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.tsindex 828853e8169..bf0623f7218 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts@@ -9,6 +9,7 @@ import type Stripe from 'stripe';import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';import { PAYMENT_RECEIVED_EVENT } from 'src/engine/core-modules/event-logs/emit/events/workspace-event/billing/payment-received';+import { getCustomerIdFromInvoice } from 'src/engine/core-modules/billing-webhook/utils/get-customer-id-from-invoice.util';import { getSubscriptionIdFromInvoice } from 'src/engine/core-modules/billing-webhook/utils/get-subscription-id-from-invoice.util';import {BillingException,@@ -19,11 +20,13 @@ import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entitimport { BillingWebhookEvent } from 'src/engine/core-modules/billing/enums/billing-webhook-events.enum';import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.service';+import { BillingCreditOneTimeTopUpService } from 'src/engine/core-modules/billing/services/billing-credit-one-time-top-up.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { ResourceCreditService } from 'src/engine/core-modules/billing/services/resource-credit.service';import { StripeInvoiceService } from 'src/engine/core-modules/billing/stripe/services/stripe-invoice.service';import { deriveBillingPeriodTransition } from 'src/engine/core-modules/billing/utils/derive-billing-period-transition.util';+import { isCreditTopUpInvoice } from 'src/engine/core-modules/billing/utils/is-credit-top-up-invoice.util';import { resolveBillingTransitionBoundary } from 'src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';@@ -43,6 +46,7 @@ export class BillingWebhookInvoiceService {private readonly billingSubscriptionService: BillingSubscriptionService,private readonly billingCreditGrantService: BillingCreditGrantService,private readonly billingCreditRolloverService: BillingCreditRolloverService,+ private readonly billingCreditOneTimeTopUpService: BillingCreditOneTimeTopUpService,private readonly billingUsageService: BillingUsageService,private readonly resourceCreditService: ResourceCreditService,private readonly stripeInvoiceService: StripeInvoiceService,@@ -70,12 +74,11 @@ export class BillingWebhookInvoiceService {) {const {billing_reason: billingReason,- customer,created: invoiceCreatedAtInSeconds,} = data.object;const stripeSubscriptionId = getSubscriptionIdFromInvoice(data.object);- const stripeCustomerId = customer as string | undefined;+ const stripeCustomerId = getCustomerIdFromInvoice(data.object);if (!isDefined(stripeSubscriptionId) ||@@ -179,8 +182,12 @@ export class BillingWebhookInvoiceService {}private async processInvoicePaid(data: Stripe.InvoicePaidEvent.Data) {+ if (isCreditTopUpInvoice(data.object)) {+ return this.processCreditTopUpInvoicePaid(data.object);+ }+const stripeSubscriptionId = getSubscriptionIdFromInvoice(data.object);- const stripeCustomerId = data.object.customer as string | undefined;+ const stripeCustomerId = getCustomerIdFromInvoice(data.object);const paidInvoicePeriodEnd = data.object.period_end;if (@@ -217,6 +224,23 @@ export class BillingWebhookInvoiceService {return { stripeSubscriptionId };}+ private async processCreditTopUpInvoicePaid(invoice: Stripe.Invoice) {+ const workspaceId =+ await this.billingCreditOneTimeTopUpService.grantPurchasedCreditsForPaidInvoice(+ invoice,+ );++ if (isDefined(workspaceId)) {+ void this.eventLogEmitterService+ .createContext({ workspaceId })+ .insertWorkspaceEvent(PAYMENT_RECEIVED_EVENT, {+ amountPaid: invoice.amount_paid,+ });+ }++ return { stripeInvoiceId: invoice.id };+ }+private async finalizePastDueDraftInvoicesAfterPaidInvoice(stripeSubscriptionId: string,paidInvoicePeriodEnd: number,diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/get-customer-id-from-invoice.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/get-customer-id-from-invoice.util.spec.tsnew file mode 100644index 00000000000..ea00e95d685--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/get-customer-id-from-invoice.util.spec.ts@@ -0,0 +1,23 @@+/* @license Enterprise */++import { getCustomerIdFromInvoice } from 'src/engine/core-modules/billing-webhook/utils/get-customer-id-from-invoice.util';++describe('getCustomerIdFromInvoice', () => {+ it('reads an unexpanded customer id', () => {+ expect(getCustomerIdFromInvoice({ customer: 'cus_unexpanded' })).toBe(+ 'cus_unexpanded',+ );+ });++ it('reads the id of an expanded customer', () => {+ expect(+ getCustomerIdFromInvoice({+ customer: { id: 'cus_deleted', object: 'customer', deleted: true },+ }),+ ).toBe('cus_deleted');+ });++ it('returns undefined without a customer', () => {+ expect(getCustomerIdFromInvoice({ customer: null })).toBeUndefined();+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/get-customer-id-from-invoice.util.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/get-customer-id-from-invoice.util.tsnew file mode 100644index 00000000000..0704fa78a95--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/get-customer-id-from-invoice.util.ts@@ -0,0 +1,10 @@+/* @license Enterprise */++import type Stripe from 'stripe';++export const getCustomerIdFromInvoice = (+ invoice: Pick<Stripe.Invoice, 'customer'>,+): string | undefined =>+ typeof invoice.customer === 'string'+ ? invoice.customer+ : invoice.customer?.id;diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.exception.tsindex dacde47e371..246394b9111 100644--- a/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts@@ -36,6 +36,7 @@ export enum BillingExceptionCode {BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE = 'BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE',BILLING_UPGRADE_INVOICE_PAYMENT_FAILED = 'BILLING_UPGRADE_INVOICE_PAYMENT_FAILED',BILLING_UPGRADE_INVOICE_VOID_FAILED = 'BILLING_UPGRADE_INVOICE_VOID_FAILED',+ BILLING_CREDIT_TOP_UP_NOT_GRANTED = 'BILLING_CREDIT_TOP_UP_NOT_GRANTED',}const getBillingExceptionUserFriendlyMessage = (code: BillingExceptionCode) => {@@ -96,6 +97,8 @@ const getBillingExceptionUserFriendlyMessage = (code: BillingExceptionCode) => {return msg`Your payment method was declined. Please update it and try again.`;case BillingExceptionCode.BILLING_UPGRADE_INVOICE_VOID_FAILED:return msg`An unexpected billing error occurred. Please contact support.`;+ case BillingExceptionCode.BILLING_CREDIT_TOP_UP_NOT_GRANTED:+ return msg`Your purchased credits could not be added. Please contact support.`;default:assertUnreachable(code);}diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.module.tsindex af0392ca603..75f65d30fe7 100644--- a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts@@ -24,6 +24,7 @@ import { BillingWorkspaceMemberListener } from 'src/engine/core-modules/billing/import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.service';import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';+import { BillingCreditOneTimeTopUpService } from 'src/engine/core-modules/billing/services/billing-credit-one-time-top-up.service';import { BillingPlanService } from 'src/engine/core-modules/billing/services/billing-plan.service';import { BillingPortalWorkspaceService } from 'src/engine/core-modules/billing/services/billing-portal.workspace-service';import { BillingPriceService } from 'src/engine/core-modules/billing/services/billing-price.service';@@ -98,6 +99,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingCreditRolloverService,BillingCreditGrantService,BillingCreditService,+ BillingCreditOneTimeTopUpService,ResourceCreditService,BillingGaugeService,WorkspaceCurrentBillingSubscriptionCacheService,@@ -113,6 +115,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingCreditRolloverService,BillingCreditGrantService,BillingCreditService,+ BillingCreditOneTimeTopUpService,ResourceCreditService,],})diff --git a/packages/twenty-server/src/engine/core-modules/billing/constants/credit-top-up.constant.ts b/packages/twenty-server/src/engine/core-modules/billing/constants/credit-top-up.constant.tsnew file mode 100644index 00000000000..7b2a842d714--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/constants/credit-top-up.constant.ts@@ -0,0 +1,3 @@+/* @license Enterprise */++export const CREDIT_TOP_UP = 'CREDIT_TOP_UP';diff --git a/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.tsindex 261a2ec9c36..ad843d25f38 100644--- a/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts@@ -8,6 +8,7 @@ export enum BillingCreditGrantType {ONBOARDING_REWARD = 'ONBOARDING_REWARD',COMPENSATION = 'COMPENSATION',SALES = 'SALES',+ PURCHASE = 'PURCHASE',}registerEnumType(BillingCreditGrantType, {@@ -19,7 +20,10 @@ export const CAPPED_BILLING_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [BillingCreditGrantType.ROLLOVER,];-// ROLLOVER and ONBOARDING_REWARD belong to their jobs: by hand they would change carry-forward and the audit trail+export const PAID_BILLING_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [+ BillingCreditGrantType.PURCHASE,+];+export const ADMIN_GRANTABLE_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [BillingCreditGrantType.COMPENSATION,BillingCreditGrantType.SALES,diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-one-time-top-up.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-one-time-top-up.service.tsnew file mode 100644index 00000000000..293e4800cbc--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-one-time-top-up.service.ts@@ -0,0 +1,121 @@+/* @license Enterprise */++import { Injectable, Logger } from '@nestjs/common';++import { isDefined } from 'twenty-shared/utils';++import type Stripe from 'stripe';++import { getCustomerIdFromInvoice } from 'src/engine/core-modules/billing-webhook/utils/get-customer-id-from-invoice.util';+import {+ BillingException,+ BillingExceptionCode,+} from 'src/engine/core-modules/billing/billing.exception';+import { type BillingCreditGrantEntity } from 'src/engine/core-modules/billing/entities/billing-credit-grant.entity';+import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';+import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';+import { parseCreditTopUpInvoiceMetadata } from 'src/engine/core-modules/billing/utils/parse-credit-top-up-invoice-metadata.util';+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';++@Injectable()+export class BillingCreditOneTimeTopUpService {+ private readonly logger = new Logger(BillingCreditOneTimeTopUpService.name);++ constructor(+ private readonly billingCreditService: BillingCreditService,+ private readonly exceptionHandlerService: ExceptionHandlerService,+ @InjectWorkspaceScopedRepository(BillingCustomerEntity)+ private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,+ ) {}++ async grantPurchasedCreditsForPaidInvoice(+ invoice: Stripe.Invoice,+ ): Promise<string | null> {+ const stripeCustomerId = getCustomerIdFromInvoice(invoice);+ const { workspaceId, creditAmountMicro } = parseCreditTopUpInvoiceMetadata(+ invoice.metadata,+ );++ if (!isDefined(workspaceId)) {+ return this.reportUngrantedInvoice(+ invoice,+ 'its metadata names no workspace',+ );+ }++ if (!isDefined(creditAmountMicro)) {+ return this.reportUngrantedInvoice(+ invoice,+ `its metadata has no positive credit amount (${invoice.metadata?.creditAmountMicro})`,+ );+ }++ if (!isDefined(stripeCustomerId)) {+ return this.reportUngrantedInvoice(invoice, 'it has no customer');+ }++ const billingCustomer = await this.billingCustomerRepository.findOne(+ workspaceId,+ { where: { stripeCustomerId } },+ );++ if (!isDefined(billingCustomer)) {+ return this.reportUngrantedInvoice(+ invoice,+ `customer ${stripeCustomerId} is not the billing customer of workspace ${workspaceId}`,+ );+ }++ await this.grantPurchasedCredits({+ workspaceId,+ creditAmountMicro,+ stripeInvoiceId: invoice.id,+ stripeInvoiceNumber: invoice.number,+ });++ return workspaceId;+ }++ private async grantPurchasedCredits({+ workspaceId,+ creditAmountMicro,+ stripeInvoiceId,+ stripeInvoiceNumber,+ }: {+ workspaceId: string;+ creditAmountMicro: number;+ stripeInvoiceId: string;+ stripeInvoiceNumber: string | null;+ }): Promise<BillingCreditGrantEntity | null> {+ return this.billingCreditService.grantCredits({+ workspaceId,+ amountMicro: creditAmountMicro,+ type: BillingCreditGrantType.PURCHASE,+ reason: `Credit top-up, invoice ${stripeInvoiceNumber ?? stripeInvoiceId}`,+ idempotencyKey: buildCreditTopUpIdempotencyKey(stripeInvoiceId),+ });+ }++ private reportUngrantedInvoice(+ invoice: Stripe.Invoice,+ reason: string,+ ): null {+ const message = `Paid credit top-up invoice ${invoice.id} granted nothing: ${reason}`;++ this.logger.error(message);+ this.exceptionHandlerService.captureExceptions([+ new BillingException(+ message,+ BillingExceptionCode.BILLING_CREDIT_TOP_UP_NOT_GRANTED,+ ),+ ]);++ return null;+ }+}++const buildCreditTopUpIdempotencyKey = (stripeInvoiceId: string): string =>+ `credit-top-up:${stripeInvoiceId}`;diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.tsindex 981ed1fbb29..db92469989d 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts@@ -241,6 +241,225 @@ describe('computeCarryForwardGrants', () => {});});+ describe('spending order', () => {+ const IN_THE_NEXT_PERIOD = new Date('2026-02-20T00:00:00.000Z');+ const LATER_IN_THE_NEXT_PERIOD = new Date('2026-02-25T00:00:00.000Z');++ it('spends the grant expiring soonest before an older one that never expires', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'compensation_old',+ type: BillingCreditGrantType.COMPENSATION,+ amountMicro: 600_000,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ }),+ grant({+ grantId: 'sales_new',+ type: BillingCreditGrantType.SALES,+ amountMicro: 400_000,+ createdAt: new Date('2026-01-15T00:00:00.000Z'),+ expiresAt: IN_THE_NEXT_PERIOD,+ }),+ ],+ usageMicro: 500_000,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.COMPENSATION,+ amountMicro: 500_000,+ sourceGrantId: 'compensation_old',+ expiresAt: null,+ },+ ]);+ });++ it('carries nothing more when a redelivery replays the transition over the grants it closed', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'compensation_old',+ type: BillingCreditGrantType.COMPENSATION,+ amountMicro: 600_000,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ expiresAt: BOUNDARY,+ }),+ grant({+ grantId: 'sales_new',+ type: BillingCreditGrantType.SALES,+ amountMicro: 400_000,+ createdAt: new Date('2026-01-15T00:00:00.000Z'),+ expiresAt: BOUNDARY,+ }),+ ],+ usageMicro: 500_000,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([]);+ });++ it('spends the earlier of two deadlines first', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'sales_late',+ type: BillingCreditGrantType.SALES,+ amountMicro: 400_000,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ expiresAt: LATER_IN_THE_NEXT_PERIOD,+ }),+ grant({+ grantId: 'sales_early',+ type: BillingCreditGrantType.SALES,+ amountMicro: 400_000,+ createdAt: new Date('2026-01-15T00:00:00.000Z'),+ expiresAt: IN_THE_NEXT_PERIOD,+ }),+ ],+ usageMicro: 400_000,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.SALES,+ amountMicro: 400_000,+ sourceGrantId: 'sales_late',+ expiresAt: LATER_IN_THE_NEXT_PERIOD,+ },+ ]);+ });++ it('spends free credits before purchased ones, whatever their age', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'purchase_old',+ type: BillingCreditGrantType.PURCHASE,+ amountMicro: 1_000_000,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ }),+ grant({+ grantId: 'compensation_new',+ type: BillingCreditGrantType.COMPENSATION,+ amountMicro: 300_000,+ createdAt: new Date('2026-01-15T00:00:00.000Z'),+ }),+ ],+ usageMicro: 500_000,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.PURCHASE,+ amountMicro: 800_000,+ sourceGrantId: 'purchase_old',+ expiresAt: null,+ },+ ]);+ });++ it('spends purchased credits that expire before free credits that never do', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'compensation_1',+ type: BillingCreditGrantType.COMPENSATION,+ amountMicro: 500_000,+ }),+ grant({+ grantId: 'purchase_1',+ type: BillingCreditGrantType.PURCHASE,+ amountMicro: 500_000,+ expiresAt: IN_THE_NEXT_PERIOD,+ }),+ ],+ usageMicro: 500_000,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.COMPENSATION,+ amountMicro: 500_000,+ sourceGrantId: 'compensation_1',+ expiresAt: null,+ },+ ]);+ });++ it('carries purchased credits over in full, past the rollover cap', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: ALLOWANCE,+ liveGrants: [+ grant({+ grantId: 'purchase_1',+ type: BillingCreditGrantType.PURCHASE,+ amountMicro: 5 * ROLLOVER_CAP,+ }),+ ],+ usageMicro: 0,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.ROLLOVER,+ amountMicro: ROLLOVER_CAP,+ sourceGrantId: null,+ expiresAt: null,+ },+ {+ type: BillingCreditGrantType.PURCHASE,+ amountMicro: 5 * ROLLOVER_CAP,+ sourceGrantId: 'purchase_1',+ expiresAt: null,+ },+ ]);+ });++ it('still spends the allowance and rollovers before an expiring grant', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: ALLOWANCE,+ liveGrants: [+ grant({+ grantId: 'sales_1',+ type: BillingCreditGrantType.SALES,+ amountMicro: 500_000,+ expiresAt: IN_THE_NEXT_PERIOD,+ }),+ ],+ usageMicro: ALLOWANCE,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.SALES,+ amountMicro: 500_000,+ sourceGrantId: 'sales_1',+ expiresAt: IN_THE_NEXT_PERIOD,+ },+ ]);+ });+ });+describe('edge cases', () => {it('treats a negative allowance as zero', () => {const result = computeCarryForwardGrants({diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-credit-top-up-invoice.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-credit-top-up-invoice.util.spec.tsnew file mode 100644index 00000000000..1eb28fb99b0--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-credit-top-up-invoice.util.spec.ts@@ -0,0 +1,20 @@+/* @license Enterprise */++import { isCreditTopUpInvoice } from 'src/engine/core-modules/billing/utils/is-credit-top-up-invoice.util';++describe('isCreditTopUpInvoice', () => {+ it('recognizes an invoice tagged as a credit top-up', () => {+ expect(isCreditTopUpInvoice({ metadata: { kind: 'CREDIT_TOP_UP' } })).toBe(+ true,+ );+ });++ it('ignores an invoice with another kind', () => {+ expect(isCreditTopUpInvoice({ metadata: { kind: 'OTHER' } })).toBe(false);+ });++ it('ignores an invoice without metadata', () => {+ expect(isCreditTopUpInvoice({ metadata: null })).toBe(false);+ expect(isCreditTopUpInvoice({ metadata: {} })).toBe(false);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/parse-credit-top-up-invoice-metadata.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/parse-credit-top-up-invoice-metadata.util.spec.tsnew file mode 100644index 00000000000..ac740dafbfa--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/parse-credit-top-up-invoice-metadata.util.spec.ts@@ -0,0 +1,60 @@+/* @license Enterprise */++import { parseCreditTopUpInvoiceMetadata } from 'src/engine/core-modules/billing/utils/parse-credit-top-up-invoice-metadata.util';++const WORKSPACE_ID = '20202020-1c25-4d02-bf25-6aeccf7ea419';++describe('parseCreditTopUpInvoiceMetadata', () => {+ it('reads the workspace and the purchased amount', () => {+ expect(+ parseCreditTopUpInvoiceMetadata({+ kind: 'CREDIT_TOP_UP',+ workspaceId: WORKSPACE_ID,+ creditAmountMicro: '10000000000',+ }),+ ).toEqual({ workspaceId: WORKSPACE_ID, creditAmountMicro: 10_000_000_000 });+ });++ it('reads nothing without metadata', () => {+ expect(parseCreditTopUpInvoiceMetadata(null)).toEqual({+ workspaceId: null,+ creditAmountMicro: null,+ });+ });++ it.each([+ ['no workspace', { creditAmountMicro: '1000000' }],+ ['an empty workspace', { workspaceId: '', creditAmountMicro: '1000000' }],+ ])('reads no workspace from %s', (_label, metadata) => {+ expect(parseCreditTopUpInvoiceMetadata(metadata)).toEqual({+ workspaceId: null,+ creditAmountMicro: 1_000_000,+ });+ });++ it.each([+ ['no amount', { workspaceId: WORKSPACE_ID }],+ [+ 'a non-numeric amount',+ { workspaceId: WORKSPACE_ID, creditAmountMicro: 'ten' },+ ],+ ['a zero amount', { workspaceId: WORKSPACE_ID, creditAmountMicro: '0' }],+ [+ 'a negative amount',+ { workspaceId: WORKSPACE_ID, creditAmountMicro: '-5' },+ ],+ [+ 'a fractional amount',+ { workspaceId: WORKSPACE_ID, creditAmountMicro: '1.5' },+ ],+ [+ 'an amount beyond safe integers',+ { workspaceId: WORKSPACE_ID, creditAmountMicro: '9007199254740993' },+ ],+ ])('reads no amount from %s', (_label, metadata) => {+ expect(parseCreditTopUpInvoiceMetadata(metadata)).toEqual({+ workspaceId: WORKSPACE_ID,+ creditAmountMicro: null,+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.tsindex e54d3de6bd7..bd5ac8cdd72 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts@@ -5,6 +5,7 @@ import { isDefined } from 'twenty-shared/utils';import {BillingCreditGrantType,CAPPED_BILLING_CREDIT_GRANT_TYPES,+ PAID_BILLING_CREDIT_GRANT_TYPES,} from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';export type CarryForwardGrantInput = {@@ -33,6 +34,12 @@ type CreditBucket = {const isCappedType = (type: BillingCreditGrantType): boolean =>CAPPED_BILLING_CREDIT_GRANT_TYPES.includes(type);+const isPaidType = (type: BillingCreditGrantType): boolean =>+ PAID_BILLING_CREDIT_GRANT_TYPES.includes(type);++const getExpiryTime = (expiresAt: Date | null): number =>+ isDefined(expiresAt) ? expiresAt.getTime() : Number.POSITIVE_INFINITY;+const hasLapsedBy = ({expiresAt,boundary,@@ -50,6 +57,21 @@ const compareSpendingOrder = (a: CreditBucket, b: CreditBucket): number => {return isACapped ? -1 : 1;}+ const [aExpiryTime, bExpiryTime] = [+ getExpiryTime(a.expiresAt),+ getExpiryTime(b.expiresAt),+ ];++ if (aExpiryTime !== bExpiryTime) {+ return aExpiryTime < bExpiryTime ? -1 : 1;+ }++ const [isAPaid, isBPaid] = [isPaidType(a.type), isPaidType(b.type)];++ if (isAPaid !== isBPaid) {+ return isAPaid ? 1 : -1;+ }+const byCreatedAt = a.createdAt.getTime() - b.createdAt.getTime();if (byCreatedAt !== 0) {diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.tsindex 339462cc770..fef0781cf19 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts@@ -42,6 +42,7 @@ export const getBillingExceptionStatusCode = (case BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_CANCELED:case BillingExceptionCode.BILLING_USAGE_UNAVAILABLE:case BillingExceptionCode.BILLING_UPGRADE_INVOICE_VOID_FAILED:+ case BillingExceptionCode.BILLING_CREDIT_TOP_UP_NOT_GRANTED:return 500;default: {return assertUnreachable(exception.code);diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/is-credit-top-up-invoice.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/is-credit-top-up-invoice.util.tsnew file mode 100644index 00000000000..08257ec1586--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/is-credit-top-up-invoice.util.ts@@ -0,0 +1,9 @@+/* @license Enterprise */++import type Stripe from 'stripe';++import { CREDIT_TOP_UP } from 'src/engine/core-modules/billing/constants/credit-top-up.constant';++export const isCreditTopUpInvoice = (+ invoice: Pick<Stripe.Invoice, 'metadata'>,+): boolean => invoice.metadata?.kind === CREDIT_TOP_UP;diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/parse-credit-top-up-invoice-metadata.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/parse-credit-top-up-invoice-metadata.util.tsnew file mode 100644index 00000000000..baffbd2b3e5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/parse-credit-top-up-invoice-metadata.util.ts@@ -0,0 +1,24 @@+/* @license Enterprise */++import { isNonEmptyString } from '@sniptt/guards';+import type Stripe from 'stripe';++type CreditTopUpInvoiceMetadata = {+ workspaceId: string | null;+ creditAmountMicro: number | null;+};++export const parseCreditTopUpInvoiceMetadata = (+ metadata: Stripe.Metadata | null,+): CreditTopUpInvoiceMetadata => {+ const workspaceId = metadata?.workspaceId;+ const creditAmountMicro = Number(metadata?.creditAmountMicro);++ return {+ workspaceId: isNonEmptyString(workspaceId) ? workspaceId : null,+ creditAmountMicro:+ Number.isSafeInteger(creditAmountMicro) && creditAmountMicro > 0+ ? creditAmountMicro+ : null,+ };+};diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.tsindex 2b46c136b65..7bdd55e8462 100644--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts@@ -242,10 +242,10 @@ describe('Admin credit grant and revoke (integration)', () => {expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();});- // The panel offers three operator types, but the mutation is reachable directly and jobs write these twoit.each([BillingCreditGrantType.ROLLOVER,BillingCreditGrantType.ONBOARDING_REWARD,+ BillingCreditGrantType.PURCHASE,])('refuses to grant a %s by hand', async (type) => {const response = await grantCredits({workspaceId,diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-top-up.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-top-up.integration-spec.tsnew file mode 100644index 00000000000..8c03c49f521--- /dev/null+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-top-up.integration-spec.ts@@ -0,0 +1,157 @@+import { randomUUID } from 'node:crypto';++import { addMonths, startOfMonth } from 'date-fns';+import request from 'supertest';+import {+ getSeededBillingWorkspaceId,+ listCreditGrants,+ quitBillingFixtureRedis,+ readAllowanceCounter,+ resetBillingCreditState,+ setupResourceCreditSubscription,+ TEST_STRIPE_CUSTOMER_ID,+ warmAllowanceCounter,+} from 'test/integration/billing/utils/billing-credit-fixtures.util';+import { createMockStripeCreditTopUpInvoicePaidData } from 'test/integration/billing/utils/create-mock-stripe-credit-top-up-invoice-paid-data.util';++import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';++const client = request(`http://localhost:${APP_PORT}`);++const PERIOD_START = startOfMonth(new Date());+const PERIOD_END = addMonths(PERIOD_START, 1);++const ALLOWANCE_MICRO = 1_000_000;+const TOP_UP_MICRO = 2_000_000;++const postCreditTopUpInvoicePaid = ({+ invoiceId,+ workspaceId,+ creditAmountMicro = TOP_UP_MICRO,+ stripeCustomerId = TEST_STRIPE_CUSTOMER_ID,+}: {+ invoiceId: string;+ workspaceId: string;+ creditAmountMicro?: number;+ stripeCustomerId?: string;+}) =>+ client+ .post('/webhooks/stripe')+ .set('stripe-signature', 'correct-signature')+ .set('Content-Type', 'application/json')+ .send(+ JSON.stringify({+ type: 'invoice.paid',+ data: createMockStripeCreditTopUpInvoicePaidData({+ workspaceId,+ creditAmountMicro,+ stripeCustomerId,+ invoiceId,+ }),+ }),+ );++describe('Billing credit top-up webhook (integration)', () => {+ let workspaceId: string;++ beforeAll(async () => {+ workspaceId = await getSeededBillingWorkspaceId();+ });++ beforeEach(async () => {+ await resetBillingCreditState(workspaceId);+ await setupResourceCreditSubscription({+ workspaceId,+ periodStart: PERIOD_START,+ periodEnd: PERIOD_END,+ creditAmountMicro: ALLOWANCE_MICRO,+ });+ });++ afterEach(async () => {+ await resetBillingCreditState(workspaceId);+ });++ afterAll(async () => {+ await quitBillingFixtureRedis();+ });++ it('grants the purchased credits once the invoice is paid', async () => {+ const invoiceId = `in_test_top_up_${randomUUID()}`;++ const response = await postCreditTopUpInvoicePaid({+ invoiceId,+ workspaceId,+ });++ expect(response.status).toBe(200);++ const grants = await listCreditGrants(workspaceId);++ expect(grants).toHaveLength(1);+ expect(grants[0]).toMatchObject({+ amountMicro: TOP_UP_MICRO,+ type: BillingCreditGrantType.PURCHASE,+ expiresAt: null,+ revokedAt: null,+ reason: 'Credit top-up, invoice TEST-0001',+ idempotencyKey: `credit-top-up:${invoiceId}`,+ });+ });++ it('drops the allowance counter so a blocked workspace resumes at once', async () => {+ await warmAllowanceCounter(workspaceId, PERIOD_START, 0);++ await postCreditTopUpInvoicePaid({+ invoiceId: `in_test_top_up_${randomUUID()}`,+ workspaceId,+ });++ expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();+ });++ it('grants nothing more when Stripe redelivers the event', async () => {+ const invoiceId = `in_test_top_up_${randomUUID()}`;++ await postCreditTopUpInvoicePaid({ invoiceId, workspaceId });+ const redelivery = await postCreditTopUpInvoicePaid({+ invoiceId,+ workspaceId,+ });++ expect(redelivery.status).toBe(200);+ expect(await listCreditGrants(workspaceId)).toHaveLength(1);+ });++ it('ignores an invoice whose metadata names another workspace', async () => {+ const response = await postCreditTopUpInvoicePaid({+ invoiceId: `in_test_top_up_${randomUUID()}`,+ workspaceId: randomUUID(),+ });++ expect(response.status).toBe(200);+ expect(await listCreditGrants(workspaceId)).toHaveLength(0);+ });++ it('ignores an invoice paid by a customer the workspace does not own', async () => {+ const response = await postCreditTopUpInvoicePaid({+ invoiceId: `in_test_top_up_${randomUUID()}`,+ workspaceId,+ stripeCustomerId: 'cus_unknown_top_up',+ });++ expect(response.status).toBe(200);+ expect(await listCreditGrants(workspaceId)).toHaveLength(0);+ });++ it('ignores an invoice with no amount to grant', async () => {+ const response = await postCreditTopUpInvoicePaid({+ invoiceId: `in_test_top_up_${randomUUID()}`,+ workspaceId,+ creditAmountMicro: 0,+ });++ expect(response.status).toBe(200);+ expect(await listCreditGrants(workspaceId)).toHaveLength(0);+ });+});diff --git a/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-credit-top-up-invoice-paid-data.util.ts b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-credit-top-up-invoice-paid-data.util.tsnew file mode 100644index 00000000000..3d1736c61e5--- /dev/null+++ b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-credit-top-up-invoice-paid-data.util.ts@@ -0,0 +1,41 @@+import { CREDIT_TOP_UP } from 'src/engine/core-modules/billing/constants/credit-top-up.constant';++export type MockStripeCreditTopUpInvoicePaidData = {+ object: {+ id: string;+ object: 'invoice';+ customer: string;+ number: string | null;+ amount_paid: number;+ metadata: Record<string, string>;+ };+};++export const createMockStripeCreditTopUpInvoicePaidData = ({+ workspaceId,+ creditAmountMicro,+ stripeCustomerId = 'cus_default0',+ invoiceId = 'in_test_credit_top_up',+ invoiceNumber = 'TEST-0001',+ amountPaid = 1000,+}: {+ workspaceId: string;+ creditAmountMicro: number;+ stripeCustomerId?: string;+ invoiceId?: string;+ invoiceNumber?: string | null;+ amountPaid?: number;+}): MockStripeCreditTopUpInvoicePaidData => ({+ object: {+ id: invoiceId,+ object: 'invoice',+ customer: stripeCustomerId,+ number: invoiceNumber,+ amount_paid: amountPaid,+ metadata: {+ kind: CREDIT_TOP_UP,+ workspaceId,+ creditAmountMicro: String(creditAmountMicro),+ },+ },+});