The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(billing): implement credit rollover from one billing period to another (#16802)
Félix Malfait7021a51747ae
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex c072df28fbf..ff0e0ef5d95 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -418,6 +418,8 @@ export type BillingMeteredProductUsageOutput = {periodEnd: Scalars['DateTime'];periodStart: Scalars['DateTime'];productKey: BillingProductKey;+ rolloverCredits: Scalars['Float'];+ totalGrantedCredits: Scalars['Float'];unitPriceCents: Scalars['Float'];usedCredits: Scalars['Float'];};@@ -5467,7 +5469,7 @@ export type BillingPortalSessionQuery = { __typename?: 'Query', billingPortalSesexport type GetMeteredProductsUsageQueryVariables = Exact<{ [key: string]: never; }>;-export type GetMeteredProductsUsageQuery = { __typename?: 'Query', getMeteredProductsUsage: Array<{ __typename?: 'BillingMeteredProductUsageOutput', productKey: BillingProductKey, usedCredits: number, grantedCredits: number, unitPriceCents: number }> };+export type GetMeteredProductsUsageQuery = { __typename?: 'Query', getMeteredProductsUsage: Array<{ __typename?: 'BillingMeteredProductUsageOutput', productKey: BillingProductKey, usedCredits: number, grantedCredits: number, rolloverCredits: number, totalGrantedCredits: number, unitPriceCents: number }> };export type ListPlansQueryVariables = Exact<{ [key: string]: never; }>;@@ -9311,6 +9313,8 @@ export const GetMeteredProductsUsageDocument = gql`productKeyusedCreditsgrantedCredits+ rolloverCredits+ totalGrantedCreditsunitPriceCents}}diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.tsindex 264c776d327..c0b13c2a247 100644--- a/packages/twenty-front/src/generated/graphql.ts+++ b/packages/twenty-front/src/generated/graphql.ts@@ -418,6 +418,8 @@ export type BillingMeteredProductUsageOutput = {periodEnd: Scalars['DateTime'];periodStart: Scalars['DateTime'];productKey: BillingProductKey;+ rolloverCredits: Scalars['Float'];+ totalGrantedCredits: Scalars['Float'];unitPriceCents: Scalars['Float'];usedCredits: Scalars['Float'];};diff --git a/packages/twenty-front/src/modules/billing/components/SettingsBillingCreditsSection.tsx b/packages/twenty-front/src/modules/billing/components/SettingsBillingCreditsSection.tsxindex 67b24288af8..5f9fa7bc5de 100644--- a/packages/twenty-front/src/modules/billing/components/SettingsBillingCreditsSection.tsx+++ b/packages/twenty-front/src/modules/billing/components/SettingsBillingCreditsSection.tsx@@ -44,15 +44,20 @@ export const SettingsBillingCreditsSection = ({const { getWorkflowNodeExecutionUsage } = useGetWorkflowNodeExecutionUsage();- const { usedCredits, grantedCredits, unitPriceCents } =- getWorkflowNodeExecutionUsage();-- const progressBarValue = (usedCredits / grantedCredits) * 100;+ const {+ usedCredits,+ grantedCredits,+ rolloverCredits,+ totalGrantedCredits,+ unitPriceCents,+ } = getWorkflowNodeExecutionUsage();++ const progressBarValue = (usedCredits / totalGrantedCredits) * 100;const displayedProgressBarValue = progressBarValue < 3 ? 3 : progressBarValue;const intervalLabel = getIntervalLabel(isMonthlyPlan);- const extraCreditsUsed = Math.max(0, usedCredits - grantedCredits);+ const extraCreditsUsed = Math.max(0, usedCredits - totalGrantedCredits);const costPer1kExtraCredits = (unitPriceCents / 100) * 1000;@@ -74,7 +79,7 @@ export const SettingsBillingCreditsSection = ({<SubscriptionInfoContainer><SettingsBillingLabelValueItemlabel={t`Credits Used`}- value={`${formatNumber(usedCredits)}/${formatNumber(grantedCredits, { abbreviate: true, decimals: 2 })}`}+ value={`${formatNumber(usedCredits)}/${formatNumber(totalGrantedCredits, { abbreviate: true, decimals: 2 })}`}/><ProgressBarvalue={displayedProgressBarValue}@@ -87,6 +92,32 @@ export const SettingsBillingCreditsSection = ({{!isTrialing && (<>+ <StyledLineSeparator />+ <SettingsBillingLabelValueItem+ label={t`Base Credits`}+ value={formatNumber(grantedCredits, {+ abbreviate: true,+ decimals: 2,+ })}+ />+ {rolloverCredits > 0 && (+ <SettingsBillingLabelValueItem+ label={t`Rollover Credits`}+ value={formatNumber(rolloverCredits, {+ abbreviate: true,+ decimals: 2,+ })}+ />+ )}+ {rolloverCredits > 0 && (+ <SettingsBillingLabelValueItem+ label={t`Total Available`}+ value={formatNumber(totalGrantedCredits, {+ abbreviate: true,+ decimals: 2,+ })}+ />+ )}<StyledLineSeparator /><SettingsBillingLabelValueItemlabel={t`Extra Credits Used`}diff --git a/packages/twenty-front/src/modules/billing/graphql/queries/getMeteredProductsUsage.ts b/packages/twenty-front/src/modules/billing/graphql/queries/getMeteredProductsUsage.tsindex cefd8ef1f4b..36965aaae53 100644--- a/packages/twenty-front/src/modules/billing/graphql/queries/getMeteredProductsUsage.ts+++ b/packages/twenty-front/src/modules/billing/graphql/queries/getMeteredProductsUsage.ts@@ -6,6 +6,8 @@ export const GET_METERED_PRODUCTS_USAGE = gql`productKeyusedCreditsgrantedCredits+ rolloverCredits+ totalGrantedCreditsunitPriceCents}}diff --git a/packages/twenty-server/package.json b/packages/twenty-server/package.jsonindex ae628a2edf2..d16bb49e592 100644--- a/packages/twenty-server/package.json+++ b/packages/twenty-server/package.json@@ -164,7 +164,7 @@"rxjs": "7.8.1","semver": "7.6.3","sharp": "0.32.6",- "stripe": "17.3.1",+ "stripe": "19.3.1","transliteration": "2.3.5","tsconfig-paths": "^4.2.0","tsdav": "^2.1.5",diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/__mocks__/stripe-subscription-updated-events.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/__mocks__/stripe-subscription-updated-events.tsindex 638307d8a83..c342d88e2b0 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/__mocks__/stripe-subscription-updated-events.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/__mocks__/stripe-subscription-updated-events.ts@@ -12,9 +12,14 @@ export const mockStripeSubscriptionUpdatedEventWithoutUpdatedItem: Stripe.Custombilling_cycle_anchor: 1745007630,billing_cycle_anchor_config: null,automatic_tax: {+ disabled_reason: null,enabled: false,liability: null,},+ billing_mode: {+ type: 'flexible',+ flexible: {},+ },billing_thresholds: null,cancel_at: null,cancel_at_period_end: false,@@ -27,15 +32,12 @@ export const mockStripeSubscriptionUpdatedEventWithoutUpdatedItem: Stripe.Customcollection_method: 'charge_automatically',created: 1745007630,currency: 'usd',- current_period_end: 1747599630,- current_period_start: 1745007630,customer: 'cus_S9eiHiQ8lNbIkL',days_until_due: null,default_payment_method: null,default_source: null,default_tax_rates: [],description: null,- discount: null,discounts: [],ended_at: null,invoice_settings: {@@ -52,13 +54,14 @@ export const mockStripeSubscriptionUpdatedEventWithoutUpdatedItem: Stripe.Customobject: 'subscription_item',billing_thresholds: null,created: 1745007631,+ current_period_end: 1747599630,+ current_period_start: 1745007630,discounts: [],metadata: {},plan: {id: 'price_1RFLOkQjnlxerLN3WzE0SNgt',object: 'plan',active: true,- aggregate_usage: null,amount: 1500,amount_decimal: '1500',billing_scheme: 'per_unit',@@ -90,7 +93,6 @@ export const mockStripeSubscriptionUpdatedEventWithoutUpdatedItem: Stripe.Customnickname: null,product: 'prod_S9eiEm1mzxUNjJ',recurring: {- aggregate_usage: null,interval: 'month',interval_count: 1,meter: null,@@ -166,9 +168,14 @@ export const mockStripeSubscriptionUpdatedEventWithUpdatedItemOnly: Stripe.Custobilling_cycle_anchor: 1745007630,billing_cycle_anchor_config: null,automatic_tax: {+ disabled_reason: null,enabled: false,liability: null,},+ billing_mode: {+ type: 'flexible',+ flexible: {},+ },billing_thresholds: null,cancel_at: null,cancel_at_period_end: false,@@ -181,15 +188,12 @@ export const mockStripeSubscriptionUpdatedEventWithUpdatedItemOnly: Stripe.Custocollection_method: 'charge_automatically',created: 1745007630,currency: 'usd',- current_period_end: 1747599630,- current_period_start: 1745007630,customer: 'cus_S9eiHiQ8lNbIkL',days_until_due: null,default_payment_method: null,default_source: null,default_tax_rates: [],description: null,- discount: null,discounts: [],ended_at: null,invoice_settings: {@@ -206,13 +210,14 @@ export const mockStripeSubscriptionUpdatedEventWithUpdatedItemOnly: Stripe.Custoobject: 'subscription_item',billing_thresholds: null,created: 1745007631,+ current_period_end: 1747599630,+ current_period_start: 1745007630,discounts: [],metadata: {},plan: {id: 'price_1RFLOkQjnlxerLN3WzE0SNgt',object: 'plan',active: true,- aggregate_usage: null,amount: 1500,amount_decimal: '1500',billing_scheme: 'per_unit',@@ -244,7 +249,6 @@ export const mockStripeSubscriptionUpdatedEventWithUpdatedItemOnly: Stripe.Custonickname: null,product: 'prod_S9eiEm1mzxUNjJ',recurring: {- aggregate_usage: null,interval: 'month',interval_count: 1,meter: null,@@ -303,13 +307,14 @@ export const mockStripeSubscriptionUpdatedEventWithUpdatedItemOnly: Stripe.Custoobject: 'subscription_item',billing_thresholds: null,created: 1745007631,+ current_period_end: 1747599630,+ current_period_start: 1745007630,discounts: [],metadata: {},plan: {id: 'price_1RFLOkQjnlxerLN3WzE0SNgt',object: 'plan',active: true,- aggregate_usage: null,amount: 1500,amount_decimal: '1500',billing_scheme: 'per_unit',@@ -341,7 +346,6 @@ export const mockStripeSubscriptionUpdatedEventWithUpdatedItemOnly: Stripe.Custonickname: null,product: 'prod_S9eiEm1mzxUNjJ',recurring: {- aggregate_usage: null,interval: 'month',interval_count: 1,meter: null,@@ -387,9 +391,14 @@ export const mockStripeSubscriptionUpdatedEventWithDeletedItem: Stripe.CustomerSbilling_cycle_anchor: 1745007630,billing_cycle_anchor_config: null,automatic_tax: {+ disabled_reason: null,enabled: false,liability: null,},+ billing_mode: {+ type: 'flexible',+ flexible: {},+ },billing_thresholds: null,cancel_at: null,cancel_at_period_end: false,@@ -402,15 +411,12 @@ export const mockStripeSubscriptionUpdatedEventWithDeletedItem: Stripe.CustomerScollection_method: 'charge_automatically',created: 1745007630,currency: 'usd',- current_period_end: 1747599630,- current_period_start: 1745007630,customer: 'cus_S9eiHiQ8lNbIkL',days_until_due: null,default_payment_method: null,default_source: null,default_tax_rates: [],description: null,- discount: null,discounts: [],ended_at: null,invoice_settings: {@@ -427,13 +433,14 @@ export const mockStripeSubscriptionUpdatedEventWithDeletedItem: Stripe.CustomerSobject: 'subscription_item',billing_thresholds: null,created: 1745007631,+ current_period_end: 1747599630,+ current_period_start: 1745007630,discounts: [],metadata: {},plan: {id: 'price_1RFLOkQjnlxerLN3WzE0SNgt',object: 'plan',active: true,- aggregate_usage: null,amount: 1500,amount_decimal: '1500',billing_scheme: 'per_unit',@@ -465,7 +472,6 @@ export const mockStripeSubscriptionUpdatedEventWithDeletedItem: Stripe.CustomerSnickname: null,product: 'prod_S9eiEm1mzxUNjJ',recurring: {- aggregate_usage: null,interval: 'month',interval_count: 1,meter: null,@@ -524,13 +530,14 @@ export const mockStripeSubscriptionUpdatedEventWithDeletedItem: Stripe.CustomerSobject: 'subscription_item',billing_thresholds: null,created: 1745007631,+ current_period_end: 1747599630,+ current_period_start: 1745007630,discounts: [],metadata: {},plan: {id: 'price_1RFLOkQjnlxerLN3WzE0SNgt',object: 'plan',active: true,- aggregate_usage: null,amount: 1500,amount_decimal: '1500',billing_scheme: 'per_unit',@@ -562,7 +569,6 @@ export const mockStripeSubscriptionUpdatedEventWithDeletedItem: Stripe.CustomerSnickname: null,product: 'prod_S9eiEm1mzxUNjJ',recurring: {- aggregate_usage: null,interval: 'month',interval_count: 1,meter: null,@@ -585,13 +591,14 @@ export const mockStripeSubscriptionUpdatedEventWithDeletedItem: Stripe.CustomerSobject: 'subscription_item',billing_thresholds: null,created: 1745007631,+ current_period_end: 1747599630,+ current_period_start: 1745007630,discounts: [],metadata: {},plan: {id: 'price_1RFLOkQjnlxerLN3WzE0SNgt',object: 'plan',active: true,- aggregate_usage: null,amount: 1500,amount_decimal: '1500',billing_scheme: 'per_unit',@@ -623,7 +630,6 @@ export const mockStripeSubscriptionUpdatedEventWithDeletedItem: Stripe.CustomerSnickname: null,product: 'prod_S9eiEm1mzxUNjJ',recurring: {- aggregate_usage: null,interval: 'month',interval_count: 1,meter: null,diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.controller.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.controller.tsindex 12b2811900f..9ef1fc788f4 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.controller.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.controller.ts@@ -5,17 +5,18 @@ import {Headers,Logger,Post,- RawBodyRequest,+ type RawBodyRequest,Req,Res,UseFilters,UseGuards,} from '@nestjs/common';-import { Response } from 'express';+import { type Response } from 'express';import Stripe from 'stripe';import { BillingWebhookAlertService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-alert.service';+import { BillingWebhookCreditGrantService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-credit-grant.service';import { BillingWebhookCustomerService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-customer.service';import { BillingWebhookEntitlementService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-entitlement.service';import { BillingWebhookInvoiceService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service';@@ -50,6 +51,7 @@ export class BillingWebhookController {private readonly billingWebhookInvoiceService: BillingWebhookInvoiceService,private readonly billingWebhookCustomerService: BillingWebhookCustomerService,private readonly billingWebhookSubscriptionScheduleService: BillingWebhookSubscriptionScheduleService,+ private readonly billingWebhookCreditGrantService: BillingWebhookCreditGrantService,) {}@Post(['webhooks/stripe'])@@ -150,6 +152,26 @@ export class BillingWebhookController {event,);}++ case BillingWebhookEvent.CREDIT_GRANT_CREATED:+ case BillingWebhookEvent.CREDIT_GRANT_UPDATED: {+ const customer = event.data.object.customer;+ // customer can be string ID, Customer object, or DeletedCustomer object+ const stripeCustomerId =+ typeof customer === 'string' ? customer : customer?.id;++ if (!stripeCustomerId) {+ throw new BillingException(+ 'Customer ID is required for credit grant events',+ BillingExceptionCode.BILLING_CUSTOMER_EVENT_WORKSPACE_NOT_FOUND,+ );+ }++ return await this.billingWebhookCreditGrantService.processStripeEvent(+ stripeCustomerId,+ );+ }+default:return {};}diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.module.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.module.tsindex 8e57823f7e2..da1ac55bf75 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.module.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.module.ts@@ -10,6 +10,7 @@ import { BillingWebhookPriceService } from 'src/engine/core-modules/billing-webhimport { BillingWebhookProductService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-product.service';import { BillingWebhookSubscriptionScheduleService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-subscription-schedule.service';import { BillingWebhookSubscriptionService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service';+import { BillingWebhookCreditGrantService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-credit-grant.service';import { BillingModule } from 'src/engine/core-modules/billing/billing.module';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { BillingEntitlementEntity } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';@@ -58,6 +59,7 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permiBillingWebhookSubscriptionService,BillingWebhookSubscriptionScheduleService,BillingWebhookEntitlementService,+ BillingWebhookCreditGrantService,],})export class BillingWebhookModule {}diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-credit-grant.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-credit-grant.service.tsnew file mode 100644index 00000000000..e9f2474613e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-credit-grant.service.ts@@ -0,0 +1,31 @@+/* @license Enterprise */++import { Injectable } from '@nestjs/common';++import { isDefined } from 'twenty-shared/utils';++import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';+import { MeteredCreditService } from 'src/engine/core-modules/billing/services/metered-credit.service';++@Injectable()+export class BillingWebhookCreditGrantService {+ constructor(+ private readonly meteredCreditService: MeteredCreditService,+ private readonly billingSubscriptionService: BillingSubscriptionService,+ ) {}++ async processStripeEvent(stripeCustomerId: string): Promise<void> {+ const subscription =+ await this.billingSubscriptionService.getCurrentBillingSubscription({+ stripeCustomerId,+ });++ if (!isDefined(subscription)) {+ return;+ }++ await this.meteredCreditService.recreateBillingAlertForSubscription(+ subscription,+ );+ }+}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 f6c1272c177..0e5cbc88354 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@@ -1,49 +1,125 @@-import { Injectable, Logger } from '@nestjs/common';+import { Injectable } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';+import { addMonths, addYears } from 'date-fns';import { isDefined } from 'twenty-shared/utils';import { type Repository } from 'typeorm';import type Stripe from 'stripe';+import { getSubscriptionIdFromInvoice } from 'src/engine/core-modules/billing-webhook/utils/get-subscription-id-from-invoice.util';import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';+import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';+import { MeteredCreditService } from 'src/engine/core-modules/billing/services/metered-credit.service';const SUBSCRIPTION_CYCLE_BILLING_REASON = 'subscription_cycle';@Injectable()export class BillingWebhookInvoiceService {- protected readonly logger = new Logger(BillingWebhookInvoiceService.name);constructor(@InjectRepository(BillingSubscriptionItemEntity)private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItemEntity>,private readonly billingSubscriptionService: BillingSubscriptionService,+ private readonly billingCreditRolloverService: BillingCreditRolloverService,+ private readonly meteredCreditService: MeteredCreditService,) {}async processStripeEvent(data: Stripe.InvoiceFinalizedEvent.Data) {const {billing_reason: billingReason,- subscription,customer,+ period_start: periodStart,+ period_end: periodEnd,} = data.object;- const stripeSubscriptionId = subscription as string | undefined;+ const stripeSubscriptionId = getSubscriptionIdFromInvoice(data.object);const stripeCustomerId = customer as string | undefined;if (- isDefined(stripeSubscriptionId) &&- billingReason === SUBSCRIPTION_CYCLE_BILLING_REASON+ !isDefined(stripeSubscriptionId) ||+ billingReason !== SUBSCRIPTION_CYCLE_BILLING_REASON) {- await this.billingSubscriptionItemRepository.update(- { stripeSubscriptionId },- { hasReachedCurrentPeriodCap: false },+ return;+ }++ await this.billingSubscriptionItemRepository.update(+ { stripeSubscriptionId },+ { hasReachedCurrentPeriodCap: false },+ );++ if (!isDefined(stripeCustomerId) || !periodEnd) {+ return;+ }++ const subscription =+ await this.billingSubscriptionService.getCurrentBillingSubscription({+ stripeCustomerId,+ });++ if (!isDefined(subscription)) {+ return;+ }++ if (periodStart) {+ await this.processRollover(+ subscription,+ new Date(periodStart * 1000),+ new Date(periodEnd * 1000),);+ }- if (isDefined(stripeCustomerId)) {- await this.billingSubscriptionService.createBillingAlertForCustomer(- stripeCustomerId,- );- }+ // Pass the new period start (which is the invoiced period's end) for alert threshold calculation+ await this.meteredCreditService.recreateBillingAlertForSubscription(+ subscription,+ new Date(periodEnd * 1000),+ );+ }++ private async processRollover(+ subscription: BillingSubscriptionEntity,+ invoicedPeriodStart: Date,+ invoicedPeriodEnd: Date,+ ): Promise<void> {+ const rolloverParams =+ await this.meteredCreditService.getMeteredRolloverParameters(+ subscription.id,+ );++ if (!isDefined(rolloverParams)) {+ return;+ }++ // The invoice covers the period that just ended (invoicedPeriodStart to invoicedPeriodEnd)+ // We need to calculate unused credits from this period and roll them over+ // Credits should expire at the end of the NEXT period+ const nextPeriodEnd = this.calculateNextPeriodEnd(+ invoicedPeriodEnd,+ subscription.interval,+ );++ await this.billingCreditRolloverService.processRolloverOnPeriodTransition({+ stripeCustomerId: subscription.stripeCustomerId,+ subscriptionId: subscription.id,+ stripeMeterId: rolloverParams.stripeMeterId,+ previousPeriodStart: invoicedPeriodStart,+ previousPeriodEnd: invoicedPeriodEnd,+ newPeriodEnd: nextPeriodEnd,+ tierQuantity: rolloverParams.tierQuantity,+ unitPriceCents: rolloverParams.unitPriceCents,+ });+ }++ private calculateNextPeriodEnd(+ periodEnd: Date,+ interval: SubscriptionInterval,+ ): Date {+ if (interval === SubscriptionInterval.Year) {+ return addYears(periodEnd, 1);}++ return addMonths(periodEnd, 1);}}diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.tsindex da681a3ff3d..e56e78c79ac 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts@@ -13,6 +13,10 @@ import { getDeletedStripeSubscriptionItemIdsFromStripeSubscriptionEvent } from 'import { transformStripeSubscriptionEventToDatabaseCustomer } from 'src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-customer.util';import { transformStripeSubscriptionEventToDatabaseSubscriptionItem } from 'src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-subscription-item.util';import { transformStripeSubscriptionEventToDatabaseSubscription } from 'src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-subscription.util';+import {+ BillingException,+ BillingExceptionCode,+} from 'src/engine/core-modules/billing/billing.exception';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';@@ -70,10 +74,13 @@ export class BillingWebhookSubscriptionService {withDeleted: true,});+ if (!workspace) {+ return { noWorkspace: true };+ }+if (- !workspace ||- (isDefined(workspace?.deletedAt) &&- type !== BillingWebhookEvent.CUSTOMER_SUBSCRIPTION_DELETED)+ isDefined(workspace.deletedAt) &&+ type !== BillingWebhookEvent.CUSTOMER_SUBSCRIPTION_DELETED) {return { noWorkspace: true };}@@ -108,7 +115,10 @@ export class BillingWebhookSubscriptionService {);if (!updatedBillingSubscription) {- throw new Error('Billing subscription not found');+ throw new BillingException(+ 'Billing subscription not found after upsert',+ BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_FOUND,+ );}await this.updateBillingSubscriptionItems(@@ -116,25 +126,21 @@ export class BillingWebhookSubscriptionService {event,);- if (- this.shouldSuspendWorkspace(data) &&- workspace.activationStatus == WorkspaceActivationStatus.ACTIVE- ) {- await this.workspaceRepository.update(workspaceId, {- activationStatus: WorkspaceActivationStatus.SUSPENDED,- });- }-- if (- this.shouldSuspendWorkspace(data) &&- workspace.activationStatus === WorkspaceActivationStatus.PENDING_CREATION- ) {- await this.workspaceService.deleteWorkspace(workspace.id);- }-- if (- !this.shouldSuspendWorkspace(data) &&- workspace.activationStatus == WorkspaceActivationStatus.SUSPENDED+ const shouldSuspend = this.shouldSuspendWorkspace(data);++ if (shouldSuspend) {+ if (workspace.activationStatus === WorkspaceActivationStatus.ACTIVE) {+ await this.workspaceRepository.update(workspaceId, {+ activationStatus: WorkspaceActivationStatus.SUSPENDED,+ });+ } else if (+ workspace.activationStatus ===+ WorkspaceActivationStatus.PENDING_CREATION+ ) {+ await this.workspaceService.deleteWorkspace(workspace.id);+ }+ } else if (+ workspace.activationStatus === WorkspaceActivationStatus.SUSPENDED) {await this.workspaceRepository.update(workspaceId, {activationStatus: WorkspaceActivationStatus.ACTIVE,@@ -177,23 +183,24 @@ export class BillingWebhookSubscriptionService {| Stripe.CustomerSubscriptionUpdatedEvent.Data| Stripe.CustomerSubscriptionCreatedEvent.Data| Stripe.CustomerSubscriptionDeletedEvent.Data,- ) {- const timeSinceTrialEnd = Date.now() / 1000 - (data.object.trial_end || 0);- const hasTrialJustEnded =- timeSinceTrialEnd < 60 * 60 * 24 && timeSinceTrialEnd > 0;+ ): boolean {+ const status = data.object.status as SubscriptionStatus;- if (- [- SubscriptionStatus.Canceled,- SubscriptionStatus.Unpaid,- SubscriptionStatus.Paused, // TODO: remove this once paused subscriptions are deprecated- ].includes(data.object.status as SubscriptionStatus) ||- (hasTrialJustEnded && data.object.status === SubscriptionStatus.PastDue)- ) {+ const suspendedStatuses = [+ SubscriptionStatus.Canceled,+ SubscriptionStatus.Unpaid,+ SubscriptionStatus.Paused, // TODO: remove this once paused subscriptions are deprecated+ ];++ if (suspendedStatuses.includes(status)) {return true;}- return false;+ const timeSinceTrialEnd = Date.now() / 1000 - (data.object.trial_end || 0);+ const hasTrialJustEnded =+ timeSinceTrialEnd > 0 && timeSinceTrialEnd < 60 * 60 * 24;++ return hasTrialJustEnded && status === SubscriptionStatus.PastDue;}async updateBillingSubscriptionItems(diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/get-subscription-id-from-invoice.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/get-subscription-id-from-invoice.util.spec.tsnew file mode 100644index 00000000000..012500daa62--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/get-subscription-id-from-invoice.util.spec.ts@@ -0,0 +1,66 @@+/* @license Enterprise */++import type Stripe from 'stripe';++import { getSubscriptionIdFromInvoice } from 'src/engine/core-modules/billing-webhook/utils/get-subscription-id-from-invoice.util';++describe('getSubscriptionIdFromInvoice', () => {+ it('should extract subscription ID from parent.subscription_details (SDK v19+ structure)', () => {+ const invoice = {+ parent: {+ subscription_details: {+ subscription: 'sub_from_parent',+ metadata: null,+ },+ type: 'subscription_details',+ quote_details: null,+ },+ } as Stripe.Invoice;++ expect(getSubscriptionIdFromInvoice(invoice)).toBe('sub_from_parent');+ });++ it('should handle expanded subscription object in parent', () => {+ const invoice = {+ parent: {+ subscription_details: {+ subscription: { id: 'sub_expanded' } as Stripe.Subscription,+ metadata: null,+ },+ type: 'subscription_details',+ quote_details: null,+ },+ } as Stripe.Invoice;++ expect(getSubscriptionIdFromInvoice(invoice)).toBe('sub_expanded');+ });++ it('should fall back to legacy subscription field when parent is null', () => {+ const invoice = {+ parent: null,+ subscription: 'sub_legacy',+ } as Stripe.Invoice & { subscription?: string };++ expect(getSubscriptionIdFromInvoice(invoice)).toBe('sub_legacy');+ });++ it('should return undefined when no subscription present', () => {+ const invoice = {+ parent: null,+ } as Stripe.Invoice;++ expect(getSubscriptionIdFromInvoice(invoice)).toBeUndefined();+ });++ it('should return undefined when parent exists but subscription_details is null', () => {+ const invoice = {+ parent: {+ subscription_details: null,+ quote_details: null,+ type: 'quote_details',+ },+ } as Stripe.Invoice;++ expect(getSubscriptionIdFromInvoice(invoice)).toBeUndefined();+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/transform-stripe-subscription-event-to-database-subscription.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/transform-stripe-subscription-event-to-database-subscription.util.spec.tsindex 9788328dda1..ce346d1be00 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/transform-stripe-subscription-event-to-database-subscription.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/__tests__/transform-stripe-subscription-event-to-database-subscription.util.spec.ts@@ -18,13 +18,13 @@ describe('transformStripeSubscriptionEventToDatabaseSubscription', () => {plan: {interval: 'month',},+ current_period_end: mockTimestamp,+ current_period_start: mockTimestamp - 2592000, // 30 days before end},],},cancel_at_period_end: false,currency: 'usd',- current_period_end: mockTimestamp,- current_period_start: mockTimestamp - 2592000, // 30 days before endmetadata: {},collection_method: 'charge_automatically',automatic_tax: null,@@ -121,7 +121,7 @@ describe('transformStripeSubscriptionEventToDatabaseSubscription', () => {cancellation_details: {comment: 'Customer requested cancellation',feedback: 'too_expensive',- reason: 'customer_request',+ reason: 'cancellation_requested',},});@@ -136,7 +136,7 @@ describe('transformStripeSubscriptionEventToDatabaseSubscription', () => {expect(result.cancellationDetails).toEqual({comment: 'Customer requested cancellation',feedback: 'too_expensive',- reason: 'customer_request',+ reason: 'cancellation_requested',});});@@ -144,7 +144,11 @@ describe('transformStripeSubscriptionEventToDatabaseSubscription', () => {const mockData = createMockSubscriptionData({automatic_tax: {enabled: true,- status: 'calculated',+ disabled_reason: null,+ liability: {+ type: 'self',+ account: 'acct_123',+ },},});@@ -155,7 +159,11 @@ describe('transformStripeSubscriptionEventToDatabaseSubscription', () => {expect(result.automaticTax).toEqual({enabled: true,- status: 'calculated',+ disabled_reason: null,+ liability: {+ type: 'self',+ account: 'acct_123',+ },});});diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/get-subscription-id-from-invoice.util.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/get-subscription-id-from-invoice.util.tsnew file mode 100644index 00000000000..0c339151034--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/get-subscription-id-from-invoice.util.ts@@ -0,0 +1,40 @@+/* @license Enterprise */++import type Stripe from 'stripe';++/**+ * Extracts the subscription ID from a Stripe invoice.+ *+ * In Stripe SDK v19+, the subscription field moved from `Invoice.subscription`+ * to `Invoice.parent.subscription_details.subscription`.+ *+ * This utility handles both structures for backward compatibility with invoices+ * created before the SDK migration.+ */+export const getSubscriptionIdFromInvoice = (+ invoice: Stripe.Invoice,+): string | undefined => {+ // New structure (Stripe SDK v19+)+ const subscriptionFromParent = invoice.parent?.subscription_details+ ?.subscription as string | Stripe.Subscription | null | undefined;++ if (subscriptionFromParent) {+ return typeof subscriptionFromParent === 'string'+ ? subscriptionFromParent+ : subscriptionFromParent.id;+ }++ // Legacy structure (pre-v19 invoices may still have this field at runtime)+ // The field exists in the API response but was removed from SDK types in v19+ const legacySubscription = (+ invoice as Stripe.Invoice & { subscription?: string | Stripe.Subscription }+ ).subscription;++ if (legacySubscription) {+ return typeof legacySubscription === 'string'+ ? legacySubscription+ : legacySubscription.id;+ }++ return undefined;+};diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-subscription.util.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-subscription.util.tsindex 16d8f5e6745..5abbf97bace 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-subscription.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-event-to-database-subscription.util.ts@@ -2,22 +2,68 @@import type Stripe from 'stripe';+import { transformStripeSubscriptionScheduleEventToDatabaseSubscriptionPhase } from 'src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-schedule-event-to-database-subscription-phase.util';+import {+ type AutomaticTaxJson,+ type CancellationDetailsJson,+} from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { BillingSubscriptionCollectionMethod } from 'src/engine/core-modules/billing/enums/billing-subscription-collection-method.enum';-import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';import { type SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';import { type SubscriptionWithSchedule } from 'src/engine/core-modules/billing/types/billing-subscription-with-schedule.type';-import { transformStripeSubscriptionScheduleEventToDatabaseSubscriptionPhase } from 'src/engine/core-modules/billing-webhook/utils/transform-stripe-subscription-schedule-event-to-database-subscription-phase.util';++// Converts Stripe AutomaticTax to serialized JSON for JSONB storage+// Normalizes expandable fields (e.g., liability.account) to string IDs+const toAutomaticTaxJson = (+ value: Stripe.Subscription.AutomaticTax | null | undefined,+): AutomaticTaxJson | undefined => {+ if (!value) {+ return undefined;+ }++ return {+ disabled_reason: value.disabled_reason,+ enabled: value.enabled,+ liability: value.liability+ ? {+ type: value.liability.type,+ account:+ typeof value.liability.account === 'string'+ ? value.liability.account+ : value.liability.account?.id,+ }+ : null,+ };+};++// Converts Stripe CancellationDetails to serialized JSON for JSONB storage+const toCancellationDetailsJson = (+ value: Stripe.Subscription.CancellationDetails | null | undefined,+): CancellationDetailsJson | undefined => {+ if (!value) {+ return undefined;+ }++ return {+ comment: value.comment,+ feedback: value.feedback,+ reason: value.reason,+ };+};export const transformStripeSubscriptionEventToDatabaseSubscription = (workspaceId: string,subscription: SubscriptionWithSchedule,) => {+ // In Stripe SDK v19+, current_period_start/end moved from Subscription to SubscriptionItem+ const firstItem = subscription.items.data[0];+return {workspaceId,stripeCustomerId: String(subscription.customer),stripeSubscriptionId: subscription.id,status: getSubscriptionStatus(subscription.status),- interval: subscription.items.data[0].plan.interval as SubscriptionInterval,+ interval: firstItem.plan.interval as SubscriptionInterval,phases: subscription.schedule? transformStripeSubscriptionScheduleEventToDatabaseSubscriptionPhase(subscription.schedule,@@ -25,22 +71,18 @@ export const transformStripeSubscriptionEventToDatabaseSubscription = (: [],cancelAtPeriodEnd: subscription.cancel_at_period_end,currency: subscription.currency.toUpperCase(),- currentPeriodEnd: getDateFromTimestamp(subscription.current_period_end),- currentPeriodStart: getDateFromTimestamp(subscription.current_period_start),+ currentPeriodEnd: getDateFromTimestamp(firstItem.current_period_end),+ currentPeriodStart: getDateFromTimestamp(firstItem.current_period_start),metadata: subscription.metadata,collectionMethod:// @ts-expect-error legacy noImplicitAnyBillingSubscriptionCollectionMethod[subscription.collection_method.toUpperCase()],- automaticTax:- subscription.automatic_tax === null- ? undefined- : subscription.automatic_tax,- cancellationDetails:- subscription.cancellation_details === null- ? undefined- : subscription.cancellation_details,+ automaticTax: toAutomaticTaxJson(subscription.automatic_tax),+ cancellationDetails: toCancellationDetailsJson(+ subscription.cancellation_details,+ ),endedAt: subscription.ended_at? getDateFromTimestamp(subscription.ended_at): undefined,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 df58903ae0d..8af8cf19fa0 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@@ -17,15 +17,18 @@ import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entitimport { BillingRestApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-api-exception.filter';import { BillingFeatureUsedListener } from 'src/engine/core-modules/billing/listeners/billing-feature-used.listener';import { BillingWorkspaceMemberListener } from 'src/engine/core-modules/billing/listeners/billing-workspace-member.listener';+import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.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';import { BillingProductService } from 'src/engine/core-modules/billing/services/billing-product.service';import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';import { BillingSubscriptionPhaseService } from 'src/engine/core-modules/billing/services/billing-subscription-phase.service';+import { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.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 { BillingService } from 'src/engine/core-modules/billing/services/billing.service';+import { MeteredCreditService } from 'src/engine/core-modules/billing/services/metered-credit.service';import { StripeModule } from 'src/engine/core-modules/billing/stripe/stripe.module';import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';@@ -63,6 +66,7 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permi],providers: [BillingSubscriptionService,+ BillingSubscriptionUpdateService,BillingSubscriptionItemService,BillingPortalWorkspaceService,BillingProductService,@@ -78,12 +82,18 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permiBillingSyncPlansDataCommand,BillingUsageService,BillingPriceService,+ BillingCreditRolloverService,+ MeteredCreditService,],exports: [BillingSubscriptionService,+ BillingSubscriptionUpdateService,+ BillingSubscriptionItemService,BillingPortalWorkspaceService,BillingService,BillingUsageService,+ BillingCreditRolloverService,+ MeteredCreditService,],})export class BillingModule {}diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.tsindex d441fe8e361..f9a2a5f5a34 100644--- a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts@@ -18,6 +18,7 @@ import { BillingUpdateOutput } from 'src/engine/core-modules/billing/dtos/outputimport { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';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 { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.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 { BillingService } from 'src/engine/core-modules/billing/services/billing.service';@@ -51,6 +52,7 @@ import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-moduleexport class BillingResolver {constructor(private readonly billingSubscriptionService: BillingSubscriptionService,+ private readonly billingSubscriptionUpdateService: BillingSubscriptionUpdateService,private readonly billingPortalWorkspaceService: BillingPortalWorkspaceService,private readonly billingPlanService: BillingPlanService,private readonly billingService: BillingService,@@ -144,7 +146,7 @@ export class BillingResolver {async switchSubscriptionInterval(@AuthWorkspace() workspace: WorkspaceEntity,) {- await this.billingSubscriptionService.changeInterval(workspace.id);+ await this.billingSubscriptionUpdateService.changeInterval(workspace.id);return {billingSubscriptions:@@ -164,7 +166,7 @@ export class BillingResolver {SettingsPermissionGuard(PermissionFlagType.BILLING),)async switchBillingPlan(@AuthWorkspace() workspace: WorkspaceEntity) {- await this.billingSubscriptionService.changePlan(workspace.id);+ await this.billingSubscriptionUpdateService.changePlan(workspace.id);return {billingSubscriptions:@@ -184,7 +186,7 @@ export class BillingResolver {SettingsPermissionGuard(PermissionFlagType.BILLING),)async cancelSwitchBillingPlan(@AuthWorkspace() workspace: WorkspaceEntity) {- await this.billingSubscriptionService.cancelSwitchPlan(workspace.id);+ await this.billingSubscriptionUpdateService.cancelSwitchPlan(workspace.id);return {billingSubscriptions:@@ -206,7 +208,9 @@ export class BillingResolver {async cancelSwitchBillingInterval(@AuthWorkspace() workspace: WorkspaceEntity,) {- await this.billingSubscriptionService.cancelSwitchInterval(workspace.id);+ await this.billingSubscriptionUpdateService.cancelSwitchInterval(+ workspace.id,+ );return {billingSubscriptions:@@ -229,7 +233,7 @@ export class BillingResolver {@AuthWorkspace() workspace: WorkspaceEntity,@Args() { priceId }: BillingUpdateSubscriptionItemPriceInput,) {- await this.billingSubscriptionService.changeMeteredPrice(+ await this.billingSubscriptionUpdateService.changeMeteredPrice(workspace.id,priceId,);@@ -282,7 +286,9 @@ export class BillingResolver {SettingsPermissionGuard(PermissionFlagType.BILLING),)async cancelSwitchMeteredPrice(@AuthWorkspace() workspace: WorkspaceEntity) {- await this.billingSubscriptionService.cancelSwitchMeteredPrice(workspace);+ await this.billingSubscriptionUpdateService.cancelSwitchMeteredPrice(+ workspace,+ );return {billingSubscriptions:diff --git a/packages/twenty-server/src/engine/core-modules/billing/dtos/outputs/billing-metered-product-usage.output.ts b/packages/twenty-server/src/engine/core-modules/billing/dtos/outputs/billing-metered-product-usage.output.tsindex fb7ef86c27d..9111b0b2a48 100644--- a/packages/twenty-server/src/engine/core-modules/billing/dtos/outputs/billing-metered-product-usage.output.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/dtos/outputs/billing-metered-product-usage.output.ts@@ -19,6 +19,12 @@ export class BillingMeteredProductUsageOutput {@Field(() => Number)grantedCredits: number;+ @Field(() => Number)+ rolloverCredits: number;++ @Field(() => Number)+ totalGrantedCredits: number;+@Field(() => Number)unitPriceCents: number;}diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.tsindex fe798ef3891..21ab27b8c86 100644--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts@@ -4,7 +4,6 @@ import { Field, ObjectType, registerEnumType } from '@nestjs/graphql';import { IDField } from '@ptc-org/nestjs-query-graphql';import graphqlTypeJson from 'graphql-type-json';-import Stripe from 'stripe';import {Column,CreateDateColumn,@@ -14,14 +13,33 @@ import {ManyToOne,OneToMany,PrimaryGeneratedColumn,- Relation,+ type Relation,UpdateDateColumn,} from 'typeorm';+import type Stripe from 'stripe';++// Serialized types for JSONB storage - uses Stripe's enum types but normalizes expandable fields+// These avoid TypeORM's DeepPartialEntity issues with Stripe's expandable object types (e.g. Stripe.Account)+export type AutomaticTaxJson = {+ disabled_reason: Stripe.Subscription.AutomaticTax['disabled_reason'];+ enabled: boolean;+ liability: {+ type: Stripe.Subscription.AutomaticTax.Liability.Type;+ account?: string; // Normalized: always string ID, never expanded Stripe.Account+ } | null;+};++export type CancellationDetailsJson = {+ comment: string | null;+ feedback: Stripe.Subscription.CancellationDetails.Feedback | null;+ reason: Stripe.Subscription.CancellationDetails.Reason | null;+};+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';-import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { BillingSubscriptionSchedulePhaseDTO } from 'src/engine/core-modules/billing/dtos/billing-subscription-schedule-phase.dto';import { BillingSubscriptionItemDTO } from 'src/engine/core-modules/billing/dtos/outputs/billing-subscription-item.output';+import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';import { BillingSubscriptionCollectionMethod } from 'src/engine/core-modules/billing/enums/billing-subscription-collection-method.enum';import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';@@ -136,10 +154,10 @@ export class BillingSubscriptionEntity {canceledAt: Date | null;@Column({ nullable: true, type: 'jsonb' })- automaticTax: Stripe.Subscription.AutomaticTax | null;+ automaticTax: AutomaticTaxJson | null;@Column({ nullable: true, type: 'jsonb' })- cancellationDetails: Stripe.Subscription.CancellationDetails | null;+ cancellationDetails: CancellationDetailsJson | null;@Column({nullable: false,diff --git a/packages/twenty-server/src/engine/core-modules/billing/enums/billing-webhook-events.enum.ts b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-webhook-events.enum.tsindex 871a934ba67..9fb2c09d22d 100644--- a/packages/twenty-server/src/engine/core-modules/billing/enums/billing-webhook-events.enum.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-webhook-events.enum.ts@@ -14,4 +14,6 @@ export enum BillingWebhookEvent {ALERT_TRIGGERED = 'billing.alert.triggered',INVOICE_FINALIZED = 'invoice.finalized',SUBSCRIPTION_SCHEDULE_UPDATED = 'subscription_schedule.updated',+ CREDIT_GRANT_CREATED = 'billing.credit_grant.created',+ CREDIT_GRANT_UPDATED = 'billing.credit_grant.updated',}diff --git a/packages/twenty-server/src/engine/core-modules/billing/jobs/update-subscription-quantity.job.ts b/packages/twenty-server/src/engine/core-modules/billing/jobs/update-subscription-quantity.job.tsindex c56ef9d6410..f64a9fac609 100644--- a/packages/twenty-server/src/engine/core-modules/billing/jobs/update-subscription-quantity.job.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/jobs/update-subscription-quantity.job.ts@@ -2,7 +2,7 @@import { Logger, Scope } from '@nestjs/common';-import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';+import { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';import { StripeSubscriptionItemService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-item.service';import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';@@ -20,7 +20,7 @@ export class UpdateSubscriptionQuantityJob {protected readonly logger = new Logger(UpdateSubscriptionQuantityJob.name);constructor(- private readonly billingSubscriptionService: BillingSubscriptionService,+ private readonly billingSubscriptionUpdateService: BillingSubscriptionUpdateService,private readonly stripeSubscriptionItemService: StripeSubscriptionItemService,private readonly globalWorkspaceOrmManager: GlobalWorkspaceOrmManager,) {}@@ -45,7 +45,7 @@ export class UpdateSubscriptionQuantityJob {}try {- await this.billingSubscriptionService.changeSeats(+ await this.billingSubscriptionUpdateService.changeSeats(data.workspaceId,workspaceMembersCount,);diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-rollover.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-rollover.service.spec.tsnew file mode 100644index 00000000000..a975d5d73ba--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-rollover.service.spec.ts@@ -0,0 +1,143 @@+/* @license Enterprise */++import { Test, type TestingModule } from '@nestjs/testing';++import type Stripe from 'stripe';++import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.service';+import { StripeBillingMeterEventService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-meter-event.service';+import { StripeCreditGrantService } from 'src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service';++describe('BillingCreditRolloverService', () => {+ let service: BillingCreditRolloverService;+ let stripeCreditGrantService: jest.Mocked<StripeCreditGrantService>;+ let stripeBillingMeterEventService: jest.Mocked<StripeBillingMeterEventService>;++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ providers: [+ BillingCreditRolloverService,+ {+ provide: StripeCreditGrantService,+ useValue: {+ createCreditGrant: jest.fn(),+ listCreditGrants: jest.fn().mockResolvedValue([]),+ voidCreditGrant: jest.fn(),+ },+ },+ {+ provide: StripeBillingMeterEventService,+ useValue: {+ sumMeterEvents: jest.fn(),+ },+ },+ ],+ }).compile();++ service = module.get<BillingCreditRolloverService>(+ BillingCreditRolloverService,+ );+ stripeCreditGrantService = module.get(StripeCreditGrantService);+ stripeBillingMeterEventService = module.get(StripeBillingMeterEventService);+ });++ describe('processRolloverOnPeriodTransition', () => {+ const baseParams = {+ stripeCustomerId: 'cus_123',+ subscriptionId: 'sub_123',+ stripeMeterId: 'meter_123',+ previousPeriodStart: new Date('2024-01-01'),+ previousPeriodEnd: new Date('2024-02-01'),+ newPeriodEnd: new Date('2024-03-01'),+ tierQuantity: 1000,+ unitPriceCents: 10,+ };++ it('should create rollover grant for unused credits', async () => {+ stripeBillingMeterEventService.sumMeterEvents.mockResolvedValue(300);++ await service.processRolloverOnPeriodTransition(baseParams);++ expect(stripeCreditGrantService.createCreditGrant).toHaveBeenCalledWith({+ customerId: 'cus_123',+ creditUnits: 700, // 1000 - 300 = 700 unused+ unitPriceCents: 10,+ expiresAt: baseParams.newPeriodEnd,+ metadata: {+ type: 'rollover',+ fromPeriodStart: baseParams.previousPeriodStart.toISOString(),+ fromPeriodEnd: baseParams.previousPeriodEnd.toISOString(),+ subscriptionId: 'sub_123',+ },+ });+ });++ it('should cap rollover at tier quantity when all credits unused', async () => {+ stripeBillingMeterEventService.sumMeterEvents.mockResolvedValue(0);++ await service.processRolloverOnPeriodTransition(baseParams);++ expect(stripeCreditGrantService.createCreditGrant).toHaveBeenCalledWith(+ expect.objectContaining({+ creditUnits: 1000, // Capped at tierQuantity+ }),+ );+ });++ it('should not create grant when all credits used', async () => {+ stripeBillingMeterEventService.sumMeterEvents.mockResolvedValue(1000);++ await service.processRolloverOnPeriodTransition(baseParams);++ expect(stripeCreditGrantService.createCreditGrant).not.toHaveBeenCalled();+ });++ it('should not create grant when usage exceeds tier', async () => {+ stripeBillingMeterEventService.sumMeterEvents.mockResolvedValue(1500);++ await service.processRolloverOnPeriodTransition(baseParams);++ expect(stripeCreditGrantService.createCreditGrant).not.toHaveBeenCalled();+ });++ it('should void existing rollover grants before creating new one', async () => {+ const existingGrants = [+ {+ id: 'grant_old',+ metadata: { type: 'rollover' },+ voided_at: null,+ },+ {+ id: 'grant_other',+ metadata: { type: 'promotional' },+ voided_at: null,+ },+ {+ id: 'grant_voided',+ metadata: { type: 'rollover' },+ voided_at: 123456,+ },+ ] as unknown as Stripe.Billing.CreditGrant[];++ stripeCreditGrantService.listCreditGrants.mockResolvedValue(+ existingGrants,+ );+ stripeBillingMeterEventService.sumMeterEvents.mockResolvedValue(500);++ await service.processRolloverOnPeriodTransition(baseParams);++ // Should only void the active rollover grant, not promotional or already voided+ expect(stripeCreditGrantService.voidCreditGrant).toHaveBeenCalledTimes(1);+ expect(stripeCreditGrantService.voidCreditGrant).toHaveBeenCalledWith(+ 'grant_old',+ );++ // Should create the new grant after voiding+ expect(stripeCreditGrantService.createCreditGrant).toHaveBeenCalledWith(+ expect.objectContaining({+ creditUnits: 500, // 1000 - 500 = 500 unused+ }),+ );+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-subscription.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-subscription-update.service.spec.tssimilarity index 95%rename from packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-subscription.service.spec.tsrename to packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-subscription-update.service.spec.tsindex 29668b6dd59..57e56563a59 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-subscription.service.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-subscription-update.service.spec.ts@@ -5,25 +5,21 @@ import { type Repository } from 'typeorm';import type Stripe from 'stripe';-import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';-import { BillingEntitlementEntity } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';-import { BillingPlanService } from 'src/engine/core-modules/billing/services/billing-plan.service';import { BillingPriceService } from 'src/engine/core-modules/billing/services/billing-price.service';import { BillingProductService } from 'src/engine/core-modules/billing/services/billing-product.service';import { BillingSubscriptionPhaseService } from 'src/engine/core-modules/billing/services/billing-subscription-phase.service';+import { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';-import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';-import { StripeSubscriptionItemService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-item.service';-import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';+import { MeteredCreditService } from 'src/engine/core-modules/billing/services/metered-credit.service';import { StripeBillingAlertService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service';+import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';import { SubscriptionUpdateType } from 'src/engine/core-modules/billing/types/billing-subscription-update.type';-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';import {arrangeBillingPriceRepositoryFindOneOrFail,@@ -52,9 +48,9 @@ import {METER_PRICE_PRO_YEAR_ID,} from './utils/price.constants';-describe('BillingSubscriptionService', () => {+describe('BillingSubscriptionUpdateService', () => {let module: TestingModule;- let service: BillingSubscriptionService;+ let service: BillingSubscriptionUpdateService;let billingSubscriptionRepository: jest.Mocked<Repository<BillingSubscriptionEntity>>;@@ -64,18 +60,18 @@ describe('BillingSubscriptionService', () => {let stripeSubscriptionScheduleService: jest.Mocked<StripeSubscriptionScheduleService>;let stripeSubscriptionService: jest.Mocked<StripeSubscriptionService>;let billingSubscriptionPhaseService: jest.Mocked<BillingSubscriptionPhaseService>;+ let billingSubscriptionService: jest.Mocked<BillingSubscriptionService>;beforeEach(async () => {module = await Test.createTestingModule({providers: [- BillingSubscriptionService,+ BillingSubscriptionUpdateService,{- provide: BillingPlanService,+ provide: BillingSubscriptionService,useValue: {- getPlanBaseProduct: jest.fn(),- listPlans: jest.fn(),- getPlanByPriceId: jest.fn(),- getPricesPerPlanByInterval: jest.fn(),+ syncSubscriptionToDatabase: jest+ .fn()+ .mockResolvedValue({} as BillingSubscriptionEntity),},},{@@ -84,13 +80,6 @@ describe('BillingSubscriptionService', () => {getProductPrices: jest.fn(),},},- {- provide: StripeCustomerService,- useValue: {- hasPaymentMethod: jest.fn(),- },- },- { provide: StripeSubscriptionItemService, useValue: {} },{provide: StripeSubscriptionScheduleService,useValue: {@@ -105,8 +94,6 @@ describe('BillingSubscriptionService', () => {provide: StripeSubscriptionService,useValue: {updateSubscription: jest.fn().mockResolvedValue({}),- cancelSubscription: jest.fn(),- collectLastInvoice: jest.fn(),},},{@@ -139,16 +126,6 @@ describe('BillingSubscriptionService', () => {isSamePhaseSignature: jest.fn().mockResolvedValue(false),},},- {- provide: TwentyConfigService,- useValue: {- get: jest.fn().mockReturnValue(0),- },- },- {- provide: getRepositoryToken(BillingEntitlementEntity),- useValue: repoMock<BillingEntitlementEntity>(),- },{provide: getRepositoryToken(BillingSubscriptionEntity),useValue: repoMock<BillingSubscriptionEntity>(),@@ -161,21 +138,26 @@ describe('BillingSubscriptionService', () => {provide: getRepositoryToken(BillingSubscriptionItemEntity),useValue: repoMock<BillingSubscriptionItemEntity>(),},- {- provide: getRepositoryToken(BillingCustomerEntity),- useValue: repoMock<BillingCustomerEntity>(),- },{provide: StripeBillingAlertService,useValue: {createUsageThresholdAlertForCustomerMeter: jest.fn(),},},+ {+ provide: MeteredCreditService,+ useValue: {+ getMeteredPricingInfoFromPriceId: jest+ .fn()+ .mockResolvedValue({ tierCap: 1000, unitPriceCents: 10 }),+ getCreditBalance: jest.fn().mockResolvedValue(0),+ },+ },BillingPriceService,],}).compile();- service = module.get(BillingSubscriptionService);+ service = module.get(BillingSubscriptionUpdateService);billingSubscriptionRepository = module.get(getRepositoryToken(BillingSubscriptionEntity),);@@ -189,10 +171,7 @@ describe('BillingSubscriptionService', () => {billingSubscriptionPhaseService = module.get(BillingSubscriptionPhaseService,);-- jest- .spyOn(service, 'syncSubscriptionToDatabase')- .mockResolvedValue({} as BillingSubscriptionEntity);+ billingSubscriptionService = module.get(BillingSubscriptionService);jest.spyOn(billingPriceService, 'getBillingThresholdsByMeterPriceId')@@ -283,7 +262,9 @@ describe('BillingSubscriptionService', () => {expect(stripeSubscriptionScheduleService.updateSchedule,).not.toHaveBeenCalled();- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should update from PRO to ENTERPRISE - with schedule', async () => {@@ -417,7 +398,9 @@ describe('BillingSubscriptionService', () => {}),],});- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should update from ENTERPRISE to PRO - without schedule', async () => {@@ -511,7 +494,9 @@ describe('BillingSubscriptionService', () => {expect(stripeSubscriptionService.updateSubscription,).not.toHaveBeenCalled();- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should update from ENTERPRISE to PRO - with schedule', async () => {@@ -619,7 +604,9 @@ describe('BillingSubscriptionService', () => {expect(stripeSubscriptionService.updateSubscription,).not.toHaveBeenCalled();- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});});@@ -687,7 +674,9 @@ describe('BillingSubscriptionService', () => {},},);- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change metered price from low cap to high cap - with schedule (ENTERPRISE to PRO downgrade)', async () => {@@ -828,7 +817,9 @@ describe('BillingSubscriptionService', () => {}),],});- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change metered price from high cap to low cap - without schedule', async () => {@@ -913,7 +904,9 @@ describe('BillingSubscriptionService', () => {expect(stripeSubscriptionService.updateSubscription,).not.toHaveBeenCalled();- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change metered price from high cap to low cap - with schedule (ENTERPRISE to PRO downgrade)', async () => {@@ -1028,7 +1021,9 @@ describe('BillingSubscriptionService', () => {expect(stripeSubscriptionService.updateSubscription,).not.toHaveBeenCalled();- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});});@@ -1106,7 +1101,9 @@ describe('BillingSubscriptionService', () => {},},);- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change interval from monthly to yearly - with schedule (ENTERPRISE monthly to PRO yearly downgrade)', async () => {@@ -1238,7 +1235,9 @@ describe('BillingSubscriptionService', () => {}),],});- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change interval from yearly to monthly - without schedule', async () => {@@ -1332,7 +1331,9 @@ describe('BillingSubscriptionService', () => {expect(stripeSubscriptionService.updateSubscription,).not.toHaveBeenCalled();- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change interval from yearly to monthly - with schedule (ENTERPRISE yearly to PRO monthly downgrade)', async () => {@@ -1440,7 +1441,9 @@ describe('BillingSubscriptionService', () => {expect(stripeSubscriptionService.updateSubscription,).not.toHaveBeenCalled();- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});});@@ -1501,7 +1504,9 @@ describe('BillingSubscriptionService', () => {},},);- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change seats from 1 to 2 - with schedule (ENTERPRISE monthly to PRO yearly downgrade)', async () => {@@ -1616,7 +1621,9 @@ describe('BillingSubscriptionService', () => {}),],});- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change seats from 2 to 1 - without schedule', async () => {@@ -1675,7 +1682,9 @@ describe('BillingSubscriptionService', () => {},},);- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});it('should change seats from 2 to 1 - with schedule', async () => {@@ -1790,7 +1799,9 @@ describe('BillingSubscriptionService', () => {}),],});- expect(service.syncSubscriptionToDatabase).toHaveBeenCalled();+ expect(+ billingSubscriptionService.syncSubscriptionToDatabase,+ ).toHaveBeenCalled();});});});diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/metered-credit.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/metered-credit.service.spec.tsnew file mode 100644index 00000000000..0ac404e2d62--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/metered-credit.service.spec.ts@@ -0,0 +1,253 @@+/* @license Enterprise */++import { Test, type TestingModule } from '@nestjs/testing';+import { getRepositoryToken } from '@nestjs/typeorm';++import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';+import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';+import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';+import { MeteredCreditService } from 'src/engine/core-modules/billing/services/metered-credit.service';+import { StripeBillingAlertService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service';+import { StripeCreditGrantService } from 'src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service';++describe('MeteredCreditService', () => {+ let service: MeteredCreditService;+ let billingSubscriptionRepository: jest.Mocked<any>;+ let billingSubscriptionItemService: jest.Mocked<BillingSubscriptionItemService>;+ let stripeBillingAlertService: jest.Mocked<StripeBillingAlertService>;+ let stripeCreditGrantService: jest.Mocked<StripeCreditGrantService>;++ beforeEach(async () => {+ const module: TestingModule = await Test.createTestingModule({+ providers: [+ MeteredCreditService,+ {+ provide: getRepositoryToken(BillingSubscriptionEntity),+ useValue: {+ findOne: jest.fn(),+ find: jest.fn(),+ },+ },+ {+ provide: getRepositoryToken(BillingPriceEntity),+ useValue: {+ findOneOrFail: jest.fn(),+ },+ },+ {+ provide: BillingSubscriptionItemService,+ useValue: {+ getMeteredSubscriptionItemDetails: jest.fn(),+ },+ },+ {+ provide: StripeBillingAlertService,+ useValue: {+ createUsageThresholdAlertForCustomerMeter: jest.fn(),+ },+ },+ {+ provide: StripeCreditGrantService,+ useValue: {+ getCustomerCreditBalance: jest.fn(),+ },+ },+ ],+ }).compile();++ service = module.get<MeteredCreditService>(MeteredCreditService);+ billingSubscriptionRepository = module.get(+ getRepositoryToken(BillingSubscriptionEntity),+ );+ billingSubscriptionItemService = module.get(BillingSubscriptionItemService);+ stripeBillingAlertService = module.get(StripeBillingAlertService);+ stripeCreditGrantService = module.get(StripeCreditGrantService);+ });++ describe('getMeteredPricingInfo', () => {+ const createMockSubscription = (meteredTiers: any[] | null = null) => ({+ id: 'sub_123',+ billingSubscriptionItems: [+ {+ stripePriceId: 'price_123',+ billingProduct: {+ metadata: { productKey: BillingProductKey.WORKFLOW_NODE_EXECUTION },+ billingPrices: [+ {+ stripePriceId: 'price_123',+ stripeMeterId: 'meter_123',+ tiers: meteredTiers ?? [+ {+ up_to: 1000,+ flat_amount: null,+ unit_amount: null,+ unit_amount_decimal: null,+ },+ {+ up_to: null,+ flat_amount: null,+ unit_amount: null,+ unit_amount_decimal: '10',+ },+ ],+ },+ ],+ },+ },+ ],+ });++ it('should return pricing info when subscription and metered item found', async () => {+ const mockSubscription = createMockSubscription();++ billingSubscriptionRepository.findOne.mockResolvedValue(mockSubscription);++ const result = await service.getMeteredPricingInfo('sub_123');++ expect(result).toEqual({+ tierCap: 1000,+ unitPriceCents: 10,+ stripeMeterId: 'meter_123',+ });+ });++ it('should return null when subscription not found', async () => {+ billingSubscriptionRepository.findOne.mockResolvedValue(null);++ const result = await service.getMeteredPricingInfo('sub_123');++ expect(result).toBeNull();+ });++ it('should return null when metered item not found', async () => {+ const mockSubscription = {+ id: 'sub_123',+ billingSubscriptionItems: [+ {+ billingProduct: {+ metadata: { productKey: 'other_product' },+ billingPrices: [],+ },+ },+ ],+ };++ billingSubscriptionRepository.findOne.mockResolvedValue(mockSubscription);++ const result = await service.getMeteredPricingInfo('sub_123');++ expect(result).toBeNull();+ });+ });++ describe('getMeteredRolloverParameters', () => {+ it('should return parameters when metered item found', async () => {+ billingSubscriptionItemService.getMeteredSubscriptionItemDetails.mockResolvedValue(+ [+ {+ stripeSubscriptionItemId: 'si_123',+ productKey: BillingProductKey.WORKFLOW_NODE_EXECUTION,+ stripeMeterId: 'meter_123',+ tierQuantity: 5000,+ unitPriceCents: 5,+ freeTrialQuantity: 100,+ },+ ],+ );++ const result = await service.getMeteredRolloverParameters('sub_123');++ expect(result).toEqual({+ stripeMeterId: 'meter_123',+ tierQuantity: 5000,+ unitPriceCents: 5,+ });+ });++ it('should return null when metered item not found', async () => {+ billingSubscriptionItemService.getMeteredSubscriptionItemDetails.mockResolvedValue(+ [],+ );++ const result = await service.getMeteredRolloverParameters('sub_123');++ expect(result).toBeNull();+ });+ });++ describe('recreateBillingAlertForSubscription', () => {+ it('should create billing alert with correct parameters', async () => {+ const currentPeriodStart = new Date('2024-01-01');+ const mockSubscription = {+ id: 'sub_123',+ stripeCustomerId: 'cus_123',+ currentPeriodStart,+ status: SubscriptionStatus.Active,+ billingSubscriptionItems: [+ {+ stripePriceId: 'price_123',+ billingProduct: {+ metadata: {+ productKey: BillingProductKey.WORKFLOW_NODE_EXECUTION,+ },+ billingPrices: [+ {+ stripePriceId: 'price_123',+ stripeMeterId: 'meter_123',+ tiers: [+ {+ up_to: 1000,+ flat_amount: null,+ unit_amount: null,+ unit_amount_decimal: null,+ },+ {+ up_to: null,+ flat_amount: null,+ unit_amount: null,+ unit_amount_decimal: '10',+ },+ ],+ },+ ],+ },+ },+ ],+ };++ // Mock for getMeteredPricingInfo (uses findOne)+ billingSubscriptionRepository.findOne.mockResolvedValue(mockSubscription);+ stripeCreditGrantService.getCustomerCreditBalance.mockResolvedValue(500);++ await service.recreateBillingAlertForSubscription(+ mockSubscription as any,+ );++ expect(+ stripeBillingAlertService.createUsageThresholdAlertForCustomerMeter,+ ).toHaveBeenCalledWith('cus_123', 1000, 500, currentPeriodStart);+ });++ it('should not create alert when metered pricing info not found', async () => {+ const mockSubscription = {+ id: 'sub_123',+ stripeCustomerId: 'cus_123',+ currentPeriodStart: new Date('2024-01-01'),+ status: SubscriptionStatus.Active,+ billingSubscriptionItems: [],+ };++ billingSubscriptionRepository.findOne.mockResolvedValue(mockSubscription);++ await service.recreateBillingAlertForSubscription(+ mockSubscription as any,+ );++ expect(+ stripeBillingAlertService.createUsageThresholdAlertForCustomerMeter,+ ).not.toHaveBeenCalled();+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.tsnew file mode 100644index 00000000000..69c57c08d90--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts@@ -0,0 +1,86 @@+/* @license Enterprise */++import { Injectable } from '@nestjs/common';++import { StripeBillingMeterEventService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-meter-event.service';+import { StripeCreditGrantService } from 'src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service';++@Injectable()+export class BillingCreditRolloverService {+ constructor(+ private readonly stripeCreditGrantService: StripeCreditGrantService,+ private readonly stripeBillingMeterEventService: StripeBillingMeterEventService,+ ) {}++ async processRolloverOnPeriodTransition({+ stripeCustomerId,+ subscriptionId,+ stripeMeterId,+ previousPeriodStart,+ previousPeriodEnd,+ newPeriodEnd,+ tierQuantity,+ unitPriceCents,+ }: {+ stripeCustomerId: string;+ subscriptionId: string;+ stripeMeterId: string;+ previousPeriodStart: Date;+ previousPeriodEnd: Date;+ newPeriodEnd: Date;+ tierQuantity: number;+ unitPriceCents: number;+ }): Promise<void> {+ // Void any existing rollover grants before creating a new one+ // This ensures only one rollover grant is active at a time+ await this.voidExistingRolloverGrants(stripeCustomerId);++ const usedCredits =+ await this.stripeBillingMeterEventService.sumMeterEvents(+ stripeMeterId,+ stripeCustomerId,+ previousPeriodStart,+ previousPeriodEnd,+ );++ const unusedCredits = Math.max(0, tierQuantity - usedCredits);++ if (unusedCredits <= 0) {+ return;+ }++ const rolloverAmount = Math.min(unusedCredits, tierQuantity);++ await this.stripeCreditGrantService.createCreditGrant({+ customerId: stripeCustomerId,+ creditUnits: rolloverAmount,+ unitPriceCents,+ expiresAt: newPeriodEnd,+ metadata: {+ type: 'rollover',+ fromPeriodStart: previousPeriodStart.toISOString(),+ fromPeriodEnd: previousPeriodEnd.toISOString(),+ subscriptionId,+ },+ });+ }++ private async voidExistingRolloverGrants(+ stripeCustomerId: string,+ ): Promise<void> {+ const existingGrants =+ await this.stripeCreditGrantService.listCreditGrants(stripeCustomerId);++ const rolloverGrants = existingGrants.filter(+ (grant) => grant.metadata?.type === 'rollover' && !grant.voided_at,+ );++ if (rolloverGrants.length === 0) {+ return;+ }++ for (const grant of rolloverGrants) {+ await this.stripeCreditGrantService.voidCreditGrant(grant.id);+ }+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-update.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-update.service.tsnew file mode 100644index 00000000000..50ec6f10ccf--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-update.service.ts@@ -0,0 +1,701 @@+/* @license Enterprise */++import { Injectable, Logger } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';++import {+ assertIsDefinedOrThrow,+ assertUnreachable,+ findOrThrow,+ isDefined,+} from 'twenty-shared/utils';+import { type Repository } from 'typeorm';++import type Stripe from 'stripe';++import { billingValidator } from 'src/engine/core-modules/billing/billing.validate';+import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';+import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';+import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';+import { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { BillingPriceService } from 'src/engine/core-modules/billing/services/billing-price.service';+import { BillingProductService } from 'src/engine/core-modules/billing/services/billing-product.service';+import { BillingSubscriptionPhaseService } from 'src/engine/core-modules/billing/services/billing-subscription-phase.service';+import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';+import { MeteredCreditService } from 'src/engine/core-modules/billing/services/metered-credit.service';+import { StripeBillingAlertService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service';+import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';+import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';+import {+ type SubscriptionUpdate,+ SubscriptionUpdateType,+} from 'src/engine/core-modules/billing/types/billing-subscription-update.type';+import { computeSubscriptionUpdateOptions } from 'src/engine/core-modules/billing/utils/compute-subscription-update-options.util';+import { getCurrentLicensedBillingSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-licensed-billing-subscription-item-or-throw.util';+import { getCurrentMeteredBillingSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-metered-billing-subscription-item-or-throw.util';+import { getSubscriptionPricesFromSchedulePhase } from 'src/engine/core-modules/billing/utils/get-subscription-prices-from-schedule-phase.util';+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';++type SubscriptionStripePrices = {+ licensedPriceId: string;+ seats: number;+ meteredPriceId: string;+};++@Injectable()+export class BillingSubscriptionUpdateService {+ protected readonly logger = new Logger(BillingSubscriptionUpdateService.name);++ constructor(+ private readonly stripeSubscriptionService: StripeSubscriptionService,+ private readonly billingPriceService: BillingPriceService,+ private readonly billingProductService: BillingProductService,+ @InjectRepository(BillingPriceEntity)+ private readonly billingPriceRepository: Repository<BillingPriceEntity>,+ @InjectRepository(BillingSubscriptionItemEntity)+ private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItemEntity>,+ @InjectRepository(BillingSubscriptionEntity)+ private readonly billingSubscriptionRepository: Repository<BillingSubscriptionEntity>,+ private readonly stripeSubscriptionScheduleService: StripeSubscriptionScheduleService,+ private readonly billingSubscriptionPhaseService: BillingSubscriptionPhaseService,+ private readonly stripeBillingAlertService: StripeBillingAlertService,+ private readonly billingSubscriptionService: BillingSubscriptionService,+ private readonly meteredCreditService: MeteredCreditService,+ ) {}++ async changeMeteredPrice(+ workspaceId: string,+ meteredPriceId: string,+ ): Promise<void> {+ const billingSubscription =+ await this.billingSubscriptionService.getCurrentBillingSubscriptionOrThrow(+ { workspaceId },+ );++ const subscriptionUpdate = {+ type: SubscriptionUpdateType.METERED_PRICE,+ newMeteredPriceId: meteredPriceId,+ } as const;++ const isScheduledForPeriodEnd =+ await this.shouldUpdateAtSubscriptionPeriodEnd(+ billingSubscription,+ subscriptionUpdate,+ );++ await this.updateSubscription(billingSubscription.id, subscriptionUpdate);++ if (!isScheduledForPeriodEnd) {+ await this.billingSubscriptionItemRepository.update(+ { stripeSubscriptionId: billingSubscription.stripeSubscriptionId },+ { hasReachedCurrentPeriodCap: false },+ );++ const meteredPricingInfo =+ await this.meteredCreditService.getMeteredPricingInfoFromPriceId(+ meteredPriceId,+ );++ const creditBalance = await this.meteredCreditService.getCreditBalance(+ billingSubscription.stripeCustomerId,+ meteredPricingInfo.unitPriceCents,+ );++ await this.stripeBillingAlertService.createUsageThresholdAlertForCustomerMeter(+ billingSubscription.stripeCustomerId,+ meteredPricingInfo.tierCap,+ creditBalance,+ billingSubscription.currentPeriodStart,+ );+ }+ }++ async cancelSwitchMeteredPrice(workspace: WorkspaceEntity): Promise<void> {+ const billingSubscription =+ await this.billingSubscriptionService.getCurrentBillingSubscriptionOrThrow(+ { workspaceId: workspace.id },+ );++ const currentMeteredPrice =+ getCurrentMeteredBillingSubscriptionItemOrThrow(billingSubscription);++ await this.updateSubscription(billingSubscription.id, {+ type: SubscriptionUpdateType.METERED_PRICE,+ newMeteredPriceId: currentMeteredPrice.stripePriceId,+ });+ }++ async cancelSwitchPlan(workspaceId: string) {+ const billingSubscription =+ await this.billingSubscriptionService.getCurrentBillingSubscriptionOrThrow(+ { workspaceId },+ );++ const currentPlan =+ getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription)+ .billingProduct?.metadata.planKey;++ await this.updateSubscription(billingSubscription.id, {+ type: SubscriptionUpdateType.PLAN,+ newPlan: currentPlan,+ });+ }++ async cancelSwitchInterval(workspaceId: string) {+ const billingSubscription =+ await this.billingSubscriptionService.getCurrentBillingSubscriptionOrThrow(+ { workspaceId },+ );++ const currentInterval = billingSubscription.interval;++ await this.updateSubscription(billingSubscription.id, {+ type: SubscriptionUpdateType.INTERVAL,+ newInterval: currentInterval,+ });+ }++ async changeInterval(workspaceId: string) {+ const billingSubscription =+ await this.billingSubscriptionService.getCurrentBillingSubscriptionOrThrow(+ { workspaceId },+ );++ const currentInterval = billingSubscription.interval;++ await this.updateSubscription(billingSubscription.id, {+ type: SubscriptionUpdateType.INTERVAL,+ newInterval:+ currentInterval === SubscriptionInterval.Month+ ? SubscriptionInterval.Year+ : SubscriptionInterval.Month,+ });+ }++ async changePlan(workspaceId: string) {+ const billingSubscription =+ await this.billingSubscriptionService.getCurrentBillingSubscriptionOrThrow(+ { workspaceId },+ );++ const currentPlan =+ getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription)+ .billingProduct?.metadata.planKey;++ await this.updateSubscription(billingSubscription.id, {+ type: SubscriptionUpdateType.PLAN,+ newPlan:+ currentPlan === BillingPlanKey.ENTERPRISE+ ? BillingPlanKey.PRO+ : BillingPlanKey.ENTERPRISE,+ });+ }++ async changeSeats(workspaceId: string, newSeats: number) {+ const billingSubscription =+ await this.billingSubscriptionService.getCurrentBillingSubscriptionOrThrow(+ { workspaceId },+ );++ await this.updateSubscription(billingSubscription.id, {+ type: SubscriptionUpdateType.SEATS,+ newSeats,+ });+ }++ async updateSubscription(+ subscriptionId: string,+ subscriptionUpdate: SubscriptionUpdate,+ ): Promise<void> {+ const subscription = await this.billingSubscriptionRepository.findOneOrFail(+ {+ where: { id: subscriptionId },+ relations: [+ 'billingSubscriptionItems',+ 'billingSubscriptionItems.billingProduct',+ ],+ },+ );++ const licensedItem =+ getCurrentLicensedBillingSubscriptionItemOrThrow(subscription);+ const meteredItem =+ getCurrentMeteredBillingSubscriptionItemOrThrow(subscription);++ const toUpdateCurrentPrices = await this.computeSubscriptionPricesUpdate(+ subscriptionUpdate,+ {+ licensedPriceId: licensedItem.stripePriceId,+ meteredPriceId: meteredItem.stripePriceId,+ seats: licensedItem.quantity,+ },+ );++ const { schedule, currentPhase, nextPhase } =+ await this.stripeSubscriptionScheduleService.loadSubscriptionSchedule(+ subscription.stripeSubscriptionId,+ );++ const shouldUpdateAtPeriodEnd =+ await this.shouldUpdateAtSubscriptionPeriodEnd(+ subscription,+ subscriptionUpdate,+ );++ if (shouldUpdateAtPeriodEnd) {+ if (!isDefined(schedule)) {+ const { schedule, currentPhase } =+ await this.stripeSubscriptionScheduleService.createSubscriptionSchedule(+ subscription.stripeSubscriptionId,+ );++ await this.runSubscriptionScheduleUpdate({+ stripeScheduleId: schedule.id,+ toUpdateCurrentPrices: undefined,+ toUpdateNextPrices: toUpdateCurrentPrices,+ currentPhase:+ this.billingSubscriptionPhaseService.toPhaseUpdateParams(+ currentPhase,+ ),+ subscriptionCurrentPeriodEnd: Math.floor(+ subscription.currentPeriodEnd.getTime() / 1000,+ ),+ });+ } else {+ assertIsDefinedOrThrow(nextPhase);+ assertIsDefinedOrThrow(currentPhase);++ const toUpdateNextPrices = await this.computeSubscriptionPricesUpdate(+ subscriptionUpdate,+ getSubscriptionPricesFromSchedulePhase(nextPhase),+ );++ await this.runSubscriptionScheduleUpdate({+ stripeScheduleId: schedule.id,+ toUpdateNextPrices,+ toUpdateCurrentPrices: undefined,+ currentPhase:+ this.billingSubscriptionPhaseService.toPhaseUpdateParams(+ currentPhase,+ ),+ subscriptionCurrentPeriodEnd: Math.floor(+ subscription.currentPeriodEnd.getTime() / 1000,+ ),+ });+ }+ } else {+ const subscriptionOptions =+ computeSubscriptionUpdateOptions(subscriptionUpdate);++ await this.runSubscriptionUpdate({+ stripeSubscriptionId: subscription.stripeSubscriptionId,+ licensedStripeItemId: licensedItem.stripeSubscriptionItemId,+ meteredStripeItemId: meteredItem.stripeSubscriptionItemId,+ licensedStripePriceId: toUpdateCurrentPrices.licensedPriceId,+ meteredStripePriceId: toUpdateCurrentPrices.meteredPriceId,+ seats: toUpdateCurrentPrices.seats,+ ...subscriptionOptions,+ });++ if (isDefined(nextPhase)) {+ assertIsDefinedOrThrow(schedule);+ const { currentPhase: refreshedCurrentPhase } =+ await this.stripeSubscriptionScheduleService.loadSubscriptionSchedule(+ subscription.stripeSubscriptionId,+ );++ assertIsDefinedOrThrow(refreshedCurrentPhase);++ const nextPhasePrices =+ getSubscriptionPricesFromSchedulePhase(nextPhase);+ const toUpdateNextPrices = await this.computeSubscriptionPricesUpdate(+ subscriptionUpdate,+ nextPhasePrices,+ );++ await this.runSubscriptionScheduleUpdate({+ stripeScheduleId: schedule.id,+ toUpdateNextPrices,+ toUpdateCurrentPrices: undefined, //subscription update causes schedule current phase update+ currentPhase:+ this.billingSubscriptionPhaseService.toPhaseUpdateParams(+ refreshedCurrentPhase,+ ),+ subscriptionCurrentPeriodEnd: Math.floor(+ subscription.currentPeriodEnd.getTime() / 1000,+ ),+ });+ }+ }++ await this.billingSubscriptionService.syncSubscriptionToDatabase(+ subscription.workspaceId,+ subscription.stripeSubscriptionId,+ );+ }++ private async runSubscriptionUpdate({+ stripeSubscriptionId,+ licensedStripeItemId,+ meteredStripeItemId,+ licensedStripePriceId,+ meteredStripePriceId,+ seats,+ anchor,+ proration,+ metadata,+ }: {+ stripeSubscriptionId: string;+ licensedStripeItemId: string;+ meteredStripeItemId: string;+ licensedStripePriceId: string;+ meteredStripePriceId: string;+ seats: number;+ anchor?: Stripe.SubscriptionUpdateParams.BillingCycleAnchor;+ proration?: Stripe.SubscriptionUpdateParams.ProrationBehavior;+ metadata?: Record<string, string>;+ }) {+ return await this.stripeSubscriptionService.updateSubscription(+ stripeSubscriptionId,+ {+ items: [+ {+ id: licensedStripeItemId,+ price: licensedStripePriceId,+ quantity: seats,+ },+ { id: meteredStripeItemId, price: meteredStripePriceId },+ ],+ ...(anchor ? { billing_cycle_anchor: anchor } : {}),+ ...(proration ? { proration_behavior: proration } : {}),+ ...(metadata ? { metadata } : {}),+ billing_thresholds:+ await this.billingPriceService.getBillingThresholdsByMeterPriceId(+ meteredStripePriceId,+ ),+ },+ );+ }++ private async runSubscriptionScheduleUpdate({+ stripeScheduleId,+ toUpdateNextPrices,+ toUpdateCurrentPrices,+ currentPhase,+ subscriptionCurrentPeriodEnd,+ }: {+ stripeScheduleId: string;+ toUpdateNextPrices: SubscriptionStripePrices;+ toUpdateCurrentPrices: SubscriptionStripePrices | undefined;+ currentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase;+ subscriptionCurrentPeriodEnd: number;+ }) {+ let toUpdateCurrentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase = {+ ...currentPhase,+ end_date: subscriptionCurrentPeriodEnd,+ };++ if (isDefined(toUpdateCurrentPrices)) {+ toUpdateCurrentPhase =+ await this.billingSubscriptionPhaseService.buildPhaseUpdateParams({+ licensedStripePriceId: toUpdateCurrentPrices.licensedPriceId,+ seats: toUpdateCurrentPrices.seats,+ meteredStripePriceId: toUpdateCurrentPrices.meteredPriceId,+ endDate: subscriptionCurrentPeriodEnd,+ startDate: currentPhase.start_date,+ });+ }++ const toUpdateNextPhase =+ await this.billingSubscriptionPhaseService.buildPhaseUpdateParams({+ licensedStripePriceId: toUpdateNextPrices.licensedPriceId,+ seats: toUpdateNextPrices.seats,+ meteredStripePriceId: toUpdateNextPrices.meteredPriceId,+ startDate: subscriptionCurrentPeriodEnd,+ endDate: undefined,+ });++ if (+ await this.billingSubscriptionPhaseService.isSamePhaseSignature(+ toUpdateCurrentPhase,+ toUpdateNextPhase,+ )+ ) {+ return await this.stripeSubscriptionScheduleService.releaseSubscriptionSchedule(+ stripeScheduleId,+ );+ }++ return await this.stripeSubscriptionScheduleService.updateSchedule(+ stripeScheduleId,+ {+ phases: [toUpdateCurrentPhase, toUpdateNextPhase],+ },+ );+ }++ async shouldUpdateAtSubscriptionPeriodEnd(+ subscription: BillingSubscriptionEntity,+ update: SubscriptionUpdate,+ ): Promise<boolean> {+ switch (update.type) {+ case SubscriptionUpdateType.PLAN: {+ const currentPlan =+ subscription.billingSubscriptionItems[0].billingProduct?.metadata+ .planKey;++ const isDowngrade =+ currentPlan !== update.newPlan &&+ update.newPlan === BillingPlanKey.PRO;++ return isDowngrade;+ }+ case SubscriptionUpdateType.METERED_PRICE: {+ const currentMeteredPriceId =+ subscription.billingSubscriptionItems.find(+ (item) => item.quantity == null,+ )?.stripePriceId;++ assertIsDefinedOrThrow(currentMeteredPriceId);+ const currentMeteredPrice =+ await this.billingPriceRepository.findOneOrFail({+ where: { stripePriceId: currentMeteredPriceId },+ relations: ['billingProduct'],+ });+ const newMeteredPrice = await this.billingPriceRepository.findOneOrFail(+ {+ where: { stripePriceId: update.newMeteredPriceId },+ relations: ['billingProduct'],+ },+ );++ billingValidator.assertIsMeteredPrice(currentMeteredPrice);+ billingValidator.assertIsMeteredPrice(newMeteredPrice);++ const currentMeteredCap = currentMeteredPrice.tiers[0].up_to;+ const newMeteredCap = newMeteredPrice.tiers[0].up_to;++ const isDowngrade = currentMeteredCap > newMeteredCap;++ return isDowngrade;+ }+ case SubscriptionUpdateType.SEATS:+ return false;+ case SubscriptionUpdateType.INTERVAL: {+ const currentInterval = subscription.interval;+ const isDowngrade =+ currentInterval !== update.newInterval &&+ update.newInterval === SubscriptionInterval.Month;++ return isDowngrade;+ }+ default: {+ return assertUnreachable(+ update,+ 'Should never occur, add validator for new subscription update type',+ );+ }+ }+ }++ async computeSubscriptionPricesUpdate(+ update: SubscriptionUpdate,+ currentPrices: SubscriptionStripePrices,+ ): Promise<SubscriptionStripePrices> {+ switch (update.type) {+ case SubscriptionUpdateType.PLAN:+ return await this.computeSubscriptionPricesUpdateByPlan(+ update.newPlan,+ currentPrices,+ );+ case SubscriptionUpdateType.METERED_PRICE:+ return await this.computeSubscriptionPricesUpdateByMeteredPrice(+ update.newMeteredPriceId,+ currentPrices,+ );+ case SubscriptionUpdateType.SEATS:+ return this.computeSubscriptionPricesUpdateBySeats(+ update.newSeats,+ currentPrices,+ );+ case SubscriptionUpdateType.INTERVAL:+ return await this.computeSubscriptionPricesUpdateByInterval(+ update.newInterval,+ currentPrices,+ );+ }+ }++ private computeSubscriptionPricesUpdateBySeats(+ newSeats: number,+ currentPrices: SubscriptionStripePrices,+ ): SubscriptionStripePrices {+ return {+ ...currentPrices,+ seats: newSeats,+ };+ }++ private async computeSubscriptionPricesUpdateByMeteredPrice(+ newMeteredPriceId: string,+ currentPrices: SubscriptionStripePrices,+ ): Promise<SubscriptionStripePrices> {+ const currentLicensedPrice =+ await this.billingPriceRepository.findOneOrFail({+ where: { stripePriceId: currentPrices.licensedPriceId },+ relations: ['billingProduct'],+ });+ const currentInterval = currentLicensedPrice.interval;+ const currentPlanKey =+ currentLicensedPrice.billingProduct?.metadata.planKey;++ assertIsDefinedOrThrow(currentPlanKey);++ const newMeteredPrice = await this.billingPriceRepository.findOneOrFail({+ where: { stripePriceId: newMeteredPriceId },+ relations: ['billingProduct'],+ });++ billingValidator.assertIsMeteredPrice(newMeteredPrice);++ const newInterval = newMeteredPrice.interval;+ const newPlanKey = newMeteredPrice.billingProduct?.metadata.planKey;++ if (newInterval === currentInterval && currentPlanKey === newPlanKey) {+ return {+ ...currentPrices,+ meteredPriceId: newMeteredPriceId,+ };+ }++ const newEquivalentMeteredPrice =+ await this.billingPriceService.findEquivalentMeteredPrice({+ meteredPrice: newMeteredPrice,+ targetInterval: currentInterval,+ targetPlanKey: currentPlanKey,+ hasSameInterval: newInterval === currentInterval,+ hasSamePlanKey: currentPlanKey === newPlanKey,+ });++ return {+ ...currentPrices,+ meteredPriceId: newEquivalentMeteredPrice.stripePriceId,+ };+ }++ private async computeSubscriptionPricesUpdateByPlan(+ newPlan: BillingPlanKey,+ currentPrices: SubscriptionStripePrices,+ ): Promise<SubscriptionStripePrices> {+ const currentLicensedPrice =+ await this.billingPriceRepository.findOneOrFail({+ where: { stripePriceId: currentPrices.licensedPriceId },+ relations: ['billingProduct'],+ });++ const currentInterval = currentLicensedPrice.interval;+ const currentPlanKey =+ currentLicensedPrice.billingProduct?.metadata.planKey;++ assertIsDefinedOrThrow(currentPlanKey);++ if (currentPlanKey === newPlan) {+ return currentPrices;+ }++ const billingPricesPerPlanAndIntervalArray =+ await this.billingProductService.getProductPrices({+ interval: currentInterval,+ planKey: newPlan,+ });++ const targetLicensedPrice = findOrThrow(+ billingPricesPerPlanAndIntervalArray,+ ({ billingProduct }) =>+ billingProduct?.metadata.productKey === BillingProductKey.BASE_PRODUCT,+ );++ const currentMeteredPrice = await this.billingPriceRepository.findOneOrFail(+ {+ where: { stripePriceId: currentPrices.meteredPriceId },+ relations: ['billingProduct'],+ },+ );++ billingValidator.assertIsMeteredPrice(currentMeteredPrice);++ const targetMeteredPrice =+ await this.billingPriceService.findEquivalentMeteredPrice({+ meteredPrice: currentMeteredPrice,+ targetInterval: currentInterval,+ targetPlanKey: newPlan,+ hasSameInterval: true,+ hasSamePlanKey: false,+ });++ return {+ ...currentPrices,+ licensedPriceId: targetLicensedPrice.stripePriceId,+ meteredPriceId: targetMeteredPrice.stripePriceId,+ };+ }++ private async computeSubscriptionPricesUpdateByInterval(+ newInterval: SubscriptionInterval,+ currentPrices: SubscriptionStripePrices,+ ): Promise<SubscriptionStripePrices> {+ const currentLicensedPrice =+ await this.billingPriceRepository.findOneOrFail({+ where: { stripePriceId: currentPrices.licensedPriceId },+ relations: ['billingProduct'],+ });++ const currentInterval = currentLicensedPrice.interval;+ const currentPlanKey =+ currentLicensedPrice.billingProduct?.metadata.planKey;++ assertIsDefinedOrThrow(currentPlanKey);++ if (currentInterval === newInterval) {+ return currentPrices;+ }++ const billingPricesPerPlanAndIntervalArray =+ await this.billingProductService.getProductPrices({+ interval: newInterval,+ planKey: currentPlanKey,+ });++ const targetLicensedPrice = findOrThrow(+ billingPricesPerPlanAndIntervalArray,+ ({ billingProduct }) =>+ billingProduct?.metadata.productKey === BillingProductKey.BASE_PRODUCT,+ );++ const currentMeteredPrice = await this.billingPriceRepository.findOneOrFail(+ {+ where: { stripePriceId: currentPrices.meteredPriceId },+ relations: ['billingProduct'],+ },+ );++ billingValidator.assertIsMeteredPrice(currentMeteredPrice);++ const targetMeteredPrice =+ await this.billingPriceService.findEquivalentMeteredPrice({+ meteredPrice: currentMeteredPrice,+ targetInterval: newInterval,+ targetPlanKey: currentPlanKey,+ hasSameInterval: false,+ hasSamePlanKey: true,+ });++ return {+ ...currentPrices,+ licensedPriceId: targetLicensedPrice.stripePriceId,+ meteredPriceId: targetMeteredPrice.stripePriceId,+ };+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.tsindex 135121e4b0d..9ab1bbdcf3d 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts@@ -6,7 +6,6 @@ import { InjectRepository } from '@nestjs/typeorm';import { differenceInDays } from 'date-fns';import {assertIsDefinedOrThrow,- assertUnreachable,findOrThrow,isDefined,} from 'twenty-shared/utils';@@ -24,65 +23,43 @@ import {BillingException,BillingExceptionCode,} from 'src/engine/core-modules/billing/billing.exception';-import { billingValidator } from 'src/engine/core-modules/billing/billing.validate';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { BillingEntitlementEntity } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';-import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { type BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';-import { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';-import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';import { BillingPlanService } from 'src/engine/core-modules/billing/services/billing-plan.service';import { BillingPriceService } from 'src/engine/core-modules/billing/services/billing-price.service';-import { BillingProductService } from 'src/engine/core-modules/billing/services/billing-product.service';-import { BillingSubscriptionPhaseService } from 'src/engine/core-modules/billing/services/billing-subscription-phase.service';-import { StripeBillingAlertService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service';+import { MeteredCreditService } from 'src/engine/core-modules/billing/services/metered-credit.service';import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';-import {- type SubscriptionUpdate,- SubscriptionUpdateType,-} from 'src/engine/core-modules/billing/types/billing-subscription-update.type';-import { computeSubscriptionUpdateOptions } from 'src/engine/core-modules/billing/utils/compute-subscription-update-options.util';-import { getCurrentLicensedBillingSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-licensed-billing-subscription-item-or-throw.util';-import { getCurrentMeteredBillingSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-metered-billing-subscription-item-or-throw.util';import { getPlanKeyFromSubscription } from 'src/engine/core-modules/billing/utils/get-plan-key-from-subscription.util';-import { getSubscriptionPricesFromSchedulePhase } from 'src/engine/core-modules/billing/utils/get-subscription-prices-from-schedule-phase.util';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';-type SubscriptionStripePrices = {- licensedPriceId: string;- seats: number;- meteredPriceId: string;-};@Injectable()export class BillingSubscriptionService {protected readonly logger = new Logger(BillingSubscriptionService.name);+constructor(private readonly stripeSubscriptionService: StripeSubscriptionService,private readonly billingPriceService: BillingPriceService,private readonly billingPlanService: BillingPlanService,- private readonly billingProductService: BillingProductService,@InjectRepository(BillingEntitlementEntity)private readonly billingEntitlementRepository: Repository<BillingEntitlementEntity>,@InjectRepository(BillingSubscriptionEntity)private readonly billingSubscriptionRepository: Repository<BillingSubscriptionEntity>,private readonly stripeCustomerService: StripeCustomerService,private readonly twentyConfigService: TwentyConfigService,- @InjectRepository(BillingPriceEntity)- private readonly billingPriceRepository: Repository<BillingPriceEntity>,@InjectRepository(BillingSubscriptionItemEntity)private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItemEntity>,private readonly stripeSubscriptionScheduleService: StripeSubscriptionScheduleService,- private readonly billingSubscriptionPhaseService: BillingSubscriptionPhaseService,@InjectRepository(BillingCustomerEntity)private readonly billingCustomerRepository: Repository<BillingSubscriptionEntity>,- private readonly stripeBillingAlertService: StripeBillingAlertService,+ private readonly meteredCreditService: MeteredCreditService,) {}async getBillingSubscriptions(workspaceId: string) {@@ -154,14 +131,14 @@ export class BillingSubscriptionService {const stripeProductId = baseProduct.stripeProductId;const billingSubscriptionItem =- billingSubscription.billingSubscriptionItems.filter(- (billingSubscriptionItem) =>- billingSubscriptionItem.stripeProductId === stripeProductId,- )?.[0];+ billingSubscription.billingSubscriptionItems.find(+ (item) => item.stripeProductId === stripeProductId,+ );if (!billingSubscriptionItem) {- throw new Error(+ throw new BillingException(`Cannot find billingSubscriptionItem for product ${stripeProductId} for workspace ${workspaceId}`,+ BillingExceptionCode.BILLING_SUBSCRIPTION_ITEM_NOT_FOUND,);}@@ -186,7 +163,7 @@ export class BillingSubscriptionService {{ stripeCustomerId: data.object.customer as string },);- if (billingSubscription?.status === 'unpaid') {+ if (billingSubscription.status === SubscriptionStatus.Unpaid) {await this.stripeSubscriptionService.collectLastInvoice(billingSubscription.stripeSubscriptionId,);@@ -194,76 +171,21 @@ export class BillingSubscriptionService {return {handleUnpaidInvoiceStripeSubscriptionId:- billingSubscription?.stripeSubscriptionId,+ billingSubscription.stripeSubscriptionId,};}async getWorkspaceEntitlementByKey(workspaceId: string,key: BillingEntitlementKey,- ) {+ ): Promise<boolean> {const entitlement = await this.billingEntitlementRepository.findOneBy({workspaceId,key,value: true,});- if (!entitlement) {- return false;- }-- return entitlement.value;- }-- async changeMeteredPrice(- workspaceId: string,- meteredPriceId: string,- ): Promise<void> {- const billingSubscription = await this.getCurrentBillingSubscriptionOrThrow(- { workspaceId },- );-- const subscriptionUpdate = {- type: SubscriptionUpdateType.METERED_PRICE,- newMeteredPriceId: meteredPriceId,- } as const;-- const isScheduledForPeriodEnd =- await this.shouldUpdateAtSubscriptionPeriodEnd(- billingSubscription,- subscriptionUpdate,- );-- await this.updateSubscription(billingSubscription.id, subscriptionUpdate);-- if (!isScheduledForPeriodEnd) {- await this.billingSubscriptionItemRepository.update(- { stripeSubscriptionId: billingSubscription.stripeSubscriptionId },- { hasReachedCurrentPeriodCap: false },- );-- const newTierCap =- await this.getWorkflowTierCapFromPriceId(meteredPriceId);-- await this.stripeBillingAlertService.createUsageThresholdAlertForCustomerMeter(- billingSubscription.stripeCustomerId,- newTierCap,- );- }- }-- async cancelSwitchMeteredPrice(workspace: WorkspaceEntity): Promise<void> {- const billingSubscription = await this.getCurrentBillingSubscriptionOrThrow(- { workspaceId: workspace.id },- );-- const currentMeteredPrice =- getCurrentMeteredBillingSubscriptionItemOrThrow(billingSubscription);-- await this.updateSubscription(billingSubscription.id, {- type: SubscriptionUpdateType.METERED_PRICE,- newMeteredPriceId: currentMeteredPrice.stripePriceId,- });+ return entitlement?.value ?? false;}async endTrialPeriod(workspace: WorkspaceEntity) {@@ -299,8 +221,8 @@ export class BillingSubscriptionService {{ hasReachedCurrentPeriodCap: false },);- await this.createBillingAlertForCustomer(- billingSubscription.stripeCustomerId,+ await this.meteredCreditService.recreateBillingAlertForSubscription(+ billingSubscription,);return {@@ -337,93 +259,6 @@ export class BillingSubscriptionService {),},);-- const workflowSubscriptionItem =- billingSubscription.billingSubscriptionItems.find(- (item) =>- item.billingProduct.metadata.productKey ===- BillingProductKey.WORKFLOW_NODE_EXECUTION,- );-- if (!workflowSubscriptionItem) {- throw new BillingException(- 'Workflow subscription item not found',- BillingExceptionCode.BILLING_SUBSCRIPTION_ITEM_NOT_FOUND,- );- }- }-- async cancelSwitchPlan(workspaceId: string) {- const billingSubscription = await this.getCurrentBillingSubscriptionOrThrow(- { workspaceId },- );-- const currentPlan =- getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription)- .billingProduct?.metadata.planKey;-- await this.updateSubscription(billingSubscription.id, {- type: SubscriptionUpdateType.PLAN,- newPlan: currentPlan,- });- }-- async cancelSwitchInterval(workspaceId: string) {- const billingSubscription = await this.getCurrentBillingSubscriptionOrThrow(- { workspaceId },- );-- const currentInterval = billingSubscription.interval;-- await this.updateSubscription(billingSubscription.id, {- type: SubscriptionUpdateType.INTERVAL,- newInterval: currentInterval,- });- }-- async changeInterval(workspaceId: string) {- const billingSubscription = await this.getCurrentBillingSubscriptionOrThrow(- { workspaceId },- );-- const currentInterval = billingSubscription.interval;-- await this.updateSubscription(billingSubscription.id, {- type: SubscriptionUpdateType.INTERVAL,- newInterval:- currentInterval === SubscriptionInterval.Month- ? SubscriptionInterval.Year- : SubscriptionInterval.Month,- });- }-- async changePlan(workspaceId: string) {- const billingSubscription = await this.getCurrentBillingSubscriptionOrThrow(- { workspaceId },- );-- const currentPlan =- getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription)- .billingProduct?.metadata.planKey;-- await this.updateSubscription(billingSubscription.id, {- type: SubscriptionUpdateType.PLAN,- newPlan:- currentPlan === BillingPlanKey.ENTERPRISE- ? BillingPlanKey.PRO- : BillingPlanKey.ENTERPRISE,- });- }-- async changeSeats(workspaceId: string, newSeats: number) {- const billingSubscription = await this.getCurrentBillingSubscriptionOrThrow(- { workspaceId },- );-- await this.updateSubscription(billingSubscription.id, {- type: SubscriptionUpdateType.SEATS,- newSeats,- });}async syncSubscriptionToDatabase(@@ -541,574 +376,4 @@ export class BillingSubscriptionService {),);}-- async getWorkflowTierCapForSubscription(- subscriptionId: string,- ): Promise<number> {- const subscription = await this.billingSubscriptionRepository.findOneOrFail(- {- where: { id: subscriptionId },- relations: [- 'billingSubscriptionItems',- 'billingSubscriptionItems.billingProduct',- 'billingSubscriptionItems.billingProduct.billingPrices',- ],- },- );-- const workflowItem = subscription.billingSubscriptionItems.find(- (item) =>- item.billingProduct.metadata.productKey ===- BillingProductKey.WORKFLOW_NODE_EXECUTION,- );-- if (!isDefined(workflowItem)) {- throw new BillingException(- 'Workflow subscription item not found',- BillingExceptionCode.BILLING_SUBSCRIPTION_ITEM_NOT_FOUND,- );- }-- const matchingPrice = workflowItem.billingProduct.billingPrices.find(- (price) => price.stripePriceId === workflowItem.stripePriceId,- );-- if (!isDefined(matchingPrice)) {- throw new BillingException(- `Cannot find price for product ${workflowItem.stripeProductId}`,- BillingExceptionCode.BILLING_PRICE_NOT_FOUND,- );- }-- billingValidator.assertIsMeteredTiersSchemaOrThrow(matchingPrice.tiers);-- return matchingPrice.tiers[0].up_to;- }-- async getWorkflowTierCapFromPriceId(meteredPriceId: string): Promise<number> {- const price = await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: meteredPriceId },- });-- billingValidator.assertIsMeteredTiersSchemaOrThrow(price.tiers);-- return price.tiers[0].up_to;- }-- async createBillingAlertForCustomer(stripeCustomerId: string): Promise<void> {- const subscription = await this.getCurrentBillingSubscription({- stripeCustomerId,- });-- if (!isDefined(subscription)) {- this.logger.warn(- `Cannot create billing alert: subscription not found for stripeCustomerId ${stripeCustomerId}`,- );-- return;- }-- const tierCap = await this.getWorkflowTierCapForSubscription(- subscription.id,- );-- await this.stripeBillingAlertService.createUsageThresholdAlertForCustomerMeter(- stripeCustomerId,- tierCap,- );- }-- private async runSubscriptionUpdate({- stripeSubscriptionId,- licensedStripeItemId,- meteredStripeItemId,- licensedStripePriceId,- meteredStripePriceId,- seats,- anchor,- proration,- metadata,- }: {- stripeSubscriptionId: string;- licensedStripeItemId: string;- meteredStripeItemId: string;- licensedStripePriceId: string;- meteredStripePriceId: string;- seats: number;- anchor?: Stripe.SubscriptionUpdateParams.BillingCycleAnchor;- proration?: Stripe.SubscriptionUpdateParams.ProrationBehavior;- metadata?: Record<string, string>;- }) {- return await this.stripeSubscriptionService.updateSubscription(- stripeSubscriptionId,- {- items: [- {- id: licensedStripeItemId,- price: licensedStripePriceId,- quantity: seats,- },- { id: meteredStripeItemId, price: meteredStripePriceId },- ],- ...(anchor ? { billing_cycle_anchor: anchor } : {}),- ...(proration ? { proration_behavior: proration } : {}),- ...(metadata ? { metadata } : {}),- billing_thresholds:- await this.billingPriceService.getBillingThresholdsByMeterPriceId(- meteredStripePriceId,- ),- },- );- }-- async updateSubscription(- subscriptionId: string,- subscriptionUpdate: SubscriptionUpdate,- ): Promise<void> {- const subscription = await this.billingSubscriptionRepository.findOneOrFail(- {- where: { id: subscriptionId },- relations: [- 'billingSubscriptionItems',- 'billingSubscriptionItems.billingProduct',- ],- },- );-- const licensedItem =- getCurrentLicensedBillingSubscriptionItemOrThrow(subscription);- const meteredItem =- getCurrentMeteredBillingSubscriptionItemOrThrow(subscription);-- const toUpdateCurrentPrices = await this.computeSubscriptionPricesUpdate(- subscriptionUpdate,- {- licensedPriceId: licensedItem.stripePriceId,- meteredPriceId: meteredItem.stripePriceId,- seats: licensedItem.quantity,- },- );-- const { schedule, currentPhase, nextPhase } =- await this.stripeSubscriptionScheduleService.loadSubscriptionSchedule(- subscription.stripeSubscriptionId,- );-- const shouldUpdateAtSubscriptionPeriodEnd =- await this.shouldUpdateAtSubscriptionPeriodEnd(- subscription,- subscriptionUpdate,- );-- if (shouldUpdateAtSubscriptionPeriodEnd) {- if (!isDefined(schedule)) {- const { schedule, currentPhase } =- await this.stripeSubscriptionScheduleService.createSubscriptionSchedule(- subscription.stripeSubscriptionId,- );-- await this.runSubscriptionScheduleUpdate({- stripeScheduleId: schedule.id,- toUpdateCurrentPrices: undefined,- toUpdateNextPrices: toUpdateCurrentPrices,- currentPhase:- this.billingSubscriptionPhaseService.toPhaseUpdateParams(- currentPhase,- ),- subscriptionCurrentPeriodEnd: Math.floor(- subscription.currentPeriodEnd.getTime() / 1000,- ),- });- } else {- assertIsDefinedOrThrow(nextPhase);- assertIsDefinedOrThrow(currentPhase);-- const toUpdateNextPrices = await this.computeSubscriptionPricesUpdate(- subscriptionUpdate,- getSubscriptionPricesFromSchedulePhase(nextPhase),- );-- await this.runSubscriptionScheduleUpdate({- stripeScheduleId: schedule.id,- toUpdateNextPrices,- toUpdateCurrentPrices: undefined,- currentPhase:- this.billingSubscriptionPhaseService.toPhaseUpdateParams(- currentPhase,- ),- subscriptionCurrentPeriodEnd: Math.floor(- subscription.currentPeriodEnd.getTime() / 1000,- ),- });- }- } else {- const subscriptionOptions =- computeSubscriptionUpdateOptions(subscriptionUpdate);-- await this.runSubscriptionUpdate({- stripeSubscriptionId: subscription.stripeSubscriptionId,- licensedStripeItemId: licensedItem.stripeSubscriptionItemId,- meteredStripeItemId: meteredItem.stripeSubscriptionItemId,- licensedStripePriceId: toUpdateCurrentPrices.licensedPriceId,- meteredStripePriceId: toUpdateCurrentPrices.meteredPriceId,- seats: toUpdateCurrentPrices.seats,- ...subscriptionOptions,- });-- if (isDefined(nextPhase)) {- assertIsDefinedOrThrow(schedule);- const { currentPhase: refreshedCurrentPhase } =- await this.stripeSubscriptionScheduleService.loadSubscriptionSchedule(- subscription.stripeSubscriptionId,- );-- assertIsDefinedOrThrow(refreshedCurrentPhase);-- const nextPhasePrices =- getSubscriptionPricesFromSchedulePhase(nextPhase);- const toUpdateNextPrices = await this.computeSubscriptionPricesUpdate(- subscriptionUpdate,- nextPhasePrices,- );-- await this.runSubscriptionScheduleUpdate({- stripeScheduleId: schedule.id,- toUpdateNextPrices,- toUpdateCurrentPrices: undefined, //subscription update causes schedule current phase update- currentPhase:- this.billingSubscriptionPhaseService.toPhaseUpdateParams(- refreshedCurrentPhase,- ),- subscriptionCurrentPeriodEnd: Math.floor(- subscription.currentPeriodEnd.getTime() / 1000,- ),- });- }- }-- await this.syncSubscriptionToDatabase(- subscription.workspaceId,- subscription.stripeSubscriptionId,- );- }-- private async runSubscriptionScheduleUpdate({- stripeScheduleId,- toUpdateNextPrices,- toUpdateCurrentPrices,- currentPhase,- subscriptionCurrentPeriodEnd,- }: {- stripeScheduleId: string;- toUpdateNextPrices: SubscriptionStripePrices;- toUpdateCurrentPrices: SubscriptionStripePrices | undefined;- currentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase;- subscriptionCurrentPeriodEnd: number;- }) {- let toUpdateCurrentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase = {- ...currentPhase,- end_date: subscriptionCurrentPeriodEnd,- };-- if (isDefined(toUpdateCurrentPrices)) {- toUpdateCurrentPhase =- await this.billingSubscriptionPhaseService.buildPhaseUpdateParams({- licensedStripePriceId: toUpdateCurrentPrices.licensedPriceId,- seats: toUpdateCurrentPrices.seats,- meteredStripePriceId: toUpdateCurrentPrices.meteredPriceId,- endDate: subscriptionCurrentPeriodEnd,- startDate: currentPhase.start_date,- });- }-- const toUpdateNextPhase =- await this.billingSubscriptionPhaseService.buildPhaseUpdateParams({- licensedStripePriceId: toUpdateNextPrices.licensedPriceId,- seats: toUpdateNextPrices.seats,- meteredStripePriceId: toUpdateNextPrices.meteredPriceId,- startDate: subscriptionCurrentPeriodEnd,- endDate: undefined,- });-- if (- await this.billingSubscriptionPhaseService.isSamePhaseSignature(- toUpdateCurrentPhase,- toUpdateNextPhase,- )- ) {- return await this.stripeSubscriptionScheduleService.releaseSubscriptionSchedule(- stripeScheduleId,- );- }-- return await this.stripeSubscriptionScheduleService.updateSchedule(- stripeScheduleId,- {- phases: [toUpdateCurrentPhase, toUpdateNextPhase],- },- );- }-- private async shouldUpdateAtSubscriptionPeriodEnd(- subscription: BillingSubscriptionEntity,- update: SubscriptionUpdate,- ): Promise<boolean> {- switch (update.type) {- case SubscriptionUpdateType.PLAN: {- const currentPlan =- subscription.billingSubscriptionItems[0].billingProduct?.metadata- .planKey;-- const isDowngrade =- currentPlan !== update.newPlan &&- update.newPlan === BillingPlanKey.PRO;-- return isDowngrade;- }- case SubscriptionUpdateType.METERED_PRICE: {- const currentMeteredPriceId =- subscription.billingSubscriptionItems.find(- (item) => item.quantity == null,- )?.stripePriceId;-- assertIsDefinedOrThrow(currentMeteredPriceId);- const currentMeteredPrice =- await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: currentMeteredPriceId },- relations: ['billingProduct'],- });- const newMeteredPrice = await this.billingPriceRepository.findOneOrFail(- {- where: { stripePriceId: update.newMeteredPriceId },- relations: ['billingProduct'],- },- );-- billingValidator.assertIsMeteredPrice(currentMeteredPrice);- billingValidator.assertIsMeteredPrice(newMeteredPrice);-- const currentMeteredCap = currentMeteredPrice.tiers[0].up_to;- const newMeteredCap = newMeteredPrice.tiers[0].up_to;-- const isDowngrade = currentMeteredCap > newMeteredCap;-- return isDowngrade;- }- case SubscriptionUpdateType.SEATS:- return false;- case SubscriptionUpdateType.INTERVAL: {- const currentInterval = subscription.interval;- const isDowngrade =- currentInterval !== update.newInterval &&- update.newInterval === SubscriptionInterval.Month;-- return isDowngrade;- }- default: {- return assertUnreachable(- update,- 'Should never occur, add validator for new subscription update type',- );- }- }- }-- async computeSubscriptionPricesUpdate(- update: SubscriptionUpdate,- currentPrices: SubscriptionStripePrices,- ): Promise<SubscriptionStripePrices> {- switch (update.type) {- case SubscriptionUpdateType.PLAN:- return await this.computeSubscriptionPricesUpdateByPlan(- update.newPlan,- currentPrices,- );- case SubscriptionUpdateType.METERED_PRICE:- return await this.computeSubscriptionPricesUpdateByMeteredPrice(- update.newMeteredPriceId,- currentPrices,- );- case SubscriptionUpdateType.SEATS:- return this.computeSubscriptionPricesUpdateBySeats(- update.newSeats,- currentPrices,- );- case SubscriptionUpdateType.INTERVAL:- return await this.computeSubscriptionPricesUpdateByInterval(- update.newInterval,- currentPrices,- );- }- }-- private computeSubscriptionPricesUpdateBySeats(- newSeats: number,- currentPrices: SubscriptionStripePrices,- ): SubscriptionStripePrices {- return {- ...currentPrices,- seats: newSeats,- };- }-- private async computeSubscriptionPricesUpdateByMeteredPrice(- newMeteredPriceId: string,- currentPrices: SubscriptionStripePrices,- ): Promise<SubscriptionStripePrices> {- const currentLicensedPrice =- await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: currentPrices.licensedPriceId },- relations: ['billingProduct'],- });- const currentInterval = currentLicensedPrice.interval;- const currentPlanKey =- currentLicensedPrice.billingProduct?.metadata.planKey;-- assertIsDefinedOrThrow(currentPlanKey);-- const newMeteredPrice = await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: newMeteredPriceId },- relations: ['billingProduct'],- });-- billingValidator.assertIsMeteredPrice(newMeteredPrice);-- const newInterval = newMeteredPrice.interval;- const newPlanKey = newMeteredPrice.billingProduct?.metadata.planKey;-- if (newInterval === currentInterval && currentPlanKey === newPlanKey) {- return {- ...currentPrices,- meteredPriceId: newMeteredPriceId,- };- }-- const newEquivalentMeteredPrice =- await this.billingPriceService.findEquivalentMeteredPrice({- meteredPrice: newMeteredPrice,- targetInterval: currentInterval,- targetPlanKey: currentPlanKey,- hasSameInterval: newInterval === currentInterval,- hasSamePlanKey: currentPlanKey === newPlanKey,- });-- return {- ...currentPrices,- meteredPriceId: newEquivalentMeteredPrice.stripePriceId,- };- }-- private async computeSubscriptionPricesUpdateByPlan(- newPlan: BillingPlanKey,- currentPrices: SubscriptionStripePrices,- ): Promise<SubscriptionStripePrices> {- const currentLicensedPrice =- await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: currentPrices.licensedPriceId },- relations: ['billingProduct'],- });-- const currentInterval = currentLicensedPrice.interval;- const currentPlanKey =- currentLicensedPrice.billingProduct?.metadata.planKey;-- assertIsDefinedOrThrow(currentPlanKey);-- if (currentPlanKey === newPlan) {- return currentPrices;- }-- const billingPricesPerPlanAndIntervalArray =- await this.billingProductService.getProductPrices({- interval: currentInterval,- planKey: newPlan,- });-- const targetLicensedPrice = findOrThrow(- billingPricesPerPlanAndIntervalArray,- ({ billingProduct }) =>- billingProduct?.metadata.productKey === BillingProductKey.BASE_PRODUCT,- );-- const currentMeteredPrice = await this.billingPriceRepository.findOneOrFail(- {- where: { stripePriceId: currentPrices.meteredPriceId },- relations: ['billingProduct'],- },- );-- billingValidator.assertIsMeteredPrice(currentMeteredPrice);-- const targetMeteredPrice =- await this.billingPriceService.findEquivalentMeteredPrice({- meteredPrice: currentMeteredPrice,- targetInterval: currentInterval,- targetPlanKey: newPlan,- hasSameInterval: true,- hasSamePlanKey: false,- });-- return {- ...currentPrices,- licensedPriceId: targetLicensedPrice.stripePriceId,- meteredPriceId: targetMeteredPrice.stripePriceId,- };- }-- private async computeSubscriptionPricesUpdateByInterval(- newInterval: SubscriptionInterval,- currentPrices: SubscriptionStripePrices,- ): Promise<SubscriptionStripePrices> {- const currentLicensedPrice =- await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: currentPrices.licensedPriceId },- relations: ['billingProduct'],- });-- const currentInterval = currentLicensedPrice.interval;- const currentPlanKey =- currentLicensedPrice.billingProduct?.metadata.planKey;-- assertIsDefinedOrThrow(currentPlanKey);-- if (currentInterval === newInterval) {- return currentPrices;- }-- const billingPricesPerPlanAndIntervalArray =- await this.billingProductService.getProductPrices({- interval: newInterval,- planKey: currentPlanKey,- });-- const targetLicensedPrice = findOrThrow(- billingPricesPerPlanAndIntervalArray,- ({ billingProduct }) =>- billingProduct?.metadata.productKey === BillingProductKey.BASE_PRODUCT,- );-- const currentMeteredPrice = await this.billingPriceRepository.findOneOrFail(- {- where: { stripePriceId: currentPrices.meteredPriceId },- relations: ['billingProduct'],- },- );-- billingValidator.assertIsMeteredPrice(currentMeteredPrice);-- const targetMeteredPrice =- await this.billingPriceService.findEquivalentMeteredPrice({- meteredPrice: currentMeteredPrice,- targetInterval: newInterval,- targetPlanKey: currentPlanKey,- hasSameInterval: false,- hasSamePlanKey: true,- });-- return {- ...currentPrices,- licensedPriceId: targetLicensedPrice.stripePriceId,- meteredPriceId: targetMeteredPrice.stripePriceId,- };- }}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.tsindex 4b78de2a152..17b485dcf6c 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts@@ -4,7 +4,7 @@ import { Injectable, Logger } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { isDefined } from 'twenty-shared/utils';-import { Repository } from 'typeorm';+import { type Repository } from 'typeorm';import {BillingException,@@ -12,13 +12,15 @@ import {} from 'src/engine/core-modules/billing/billing.exception';import { type BillingMeteredProductUsageOutput } from 'src/engine/core-modules/billing/dtos/outputs/billing-metered-product-usage.output';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';+import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { StripeBillingMeterEventService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-meter-event.service';+import { StripeCreditGrantService } from 'src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service';import { type BillingUsageEvent } from 'src/engine/core-modules/billing/types/billing-usage-event.type';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';-import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';@Injectable()export class BillingUsageService {@@ -30,6 +32,7 @@ export class BillingUsageService {private readonly stripeBillingMeterEventService: StripeBillingMeterEventService,private readonly twentyConfigService: TwentyConfigService,private readonly billingSubscriptionItemService: BillingSubscriptionItemService,+ private readonly stripeCreditGrantService: StripeCreditGrantService,) {}async canFeatureBeUsed(workspaceId: string): Promise<boolean> {@@ -98,43 +101,80 @@ export class BillingUsageService {subscription.id,);- let periodStart: Date;- let periodEnd: Date;-- if (- subscription.status === SubscriptionStatus.Trialing &&- isDefined(subscription.trialStart) &&- isDefined(subscription.trialEnd)- ) {- periodStart = subscription.trialStart;- periodEnd = subscription.trialEnd;- } else {- periodStart = subscription.currentPeriodStart;- periodEnd = subscription.currentPeriodEnd;- }+ const { periodStart, periodEnd } = this.getSubscriptionPeriod(subscription);return Promise.all(- meteredSubscriptionItemDetails.map(async (item) => {- const meterEventsSum =- await this.stripeBillingMeterEventService.sumMeterEvents(- item.stripeMeterId,- subscription.stripeCustomerId,- periodStart,- periodEnd,- );-- return {- productKey: item.productKey,+ meteredSubscriptionItemDetails.map((item) =>+ this.buildMeteredProductUsage(+ subscription,+ item,periodStart,periodEnd,- usedCredits: meterEventsSum,- grantedCredits:- subscription.status === SubscriptionStatus.Trialing- ? item.freeTrialQuantity- : item.tierQuantity,- unitPriceCents: item.unitPriceCents,- };- }),+ ),+ ),);}++ private getSubscriptionPeriod(subscription: BillingSubscriptionEntity): {+ periodStart: Date;+ periodEnd: Date;+ } {+ const isTrialing =+ subscription.status === SubscriptionStatus.Trialing &&+ isDefined(subscription.trialStart) &&+ isDefined(subscription.trialEnd);++ if (isTrialing) {+ return {+ periodStart: subscription.trialStart!,+ periodEnd: subscription.trialEnd!,+ };+ }++ return {+ periodStart: subscription.currentPeriodStart,+ periodEnd: subscription.currentPeriodEnd,+ };+ }++ private async buildMeteredProductUsage(+ subscription: BillingSubscriptionEntity,+ item: Awaited<+ ReturnType<+ typeof this.billingSubscriptionItemService.getMeteredSubscriptionItemDetails+ >+ >[number],+ periodStart: Date,+ periodEnd: Date,+ ): Promise<BillingMeteredProductUsageOutput> {+ const meterEventsSum =+ await this.stripeBillingMeterEventService.sumMeterEvents(+ item.stripeMeterId,+ subscription.stripeCustomerId,+ periodStart,+ periodEnd,+ );++ const grantedCredits =+ subscription.status === SubscriptionStatus.Trialing+ ? item.freeTrialQuantity+ : item.tierQuantity;++ const rolloverCredits =+ await this.stripeCreditGrantService.getCustomerCreditBalance(+ subscription.stripeCustomerId,+ item.unitPriceCents,+ );++ return {+ productKey: item.productKey,+ periodStart,+ periodEnd,+ usedCredits: meterEventsSum,+ grantedCredits,+ rolloverCredits,+ totalGrantedCredits: grantedCredits + rolloverCredits,+ unitPriceCents: item.unitPriceCents,+ };+ }}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.tsindex 42f826fbde2..3db15b1a740 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing.service.ts@@ -70,28 +70,35 @@ export class BillingService {async canBillMeteredProduct(workspaceId: string,productKey: BillingProductKey,- ) {+ ): Promise<boolean> {const subscription =await this.billingSubscriptionService.getCurrentBillingSubscriptionOrThrow({ workspaceId },);- if (- ![SubscriptionStatus.Active, SubscriptionStatus.Trialing].includes(- subscription.status,- )- ) {+ const billableStatuses = [+ SubscriptionStatus.Active,+ SubscriptionStatus.Trialing,+ ];++ if (!billableStatuses.includes(subscription.status)) {return false;}const planKey = getPlanKeyFromSubscription(subscription);const products =await this.billingProductService.getProductsByPlan(planKey);+const targetProduct = products.find(({ metadata }) => metadata.productKey === productKey,);++ if (!targetProduct) {+ return false;+ }+const subscriptionItem = subscription.billingSubscriptionItems.find(- (item) => item.stripeProductId === targetProduct?.stripeProductId,+ (item) => item.stripeProductId === targetProduct.stripeProductId,);return subscriptionItem?.hasReachedCurrentPeriodCap === false;diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/metered-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/metered-credit.service.tsnew file mode 100644index 00000000000..0bb62fd663e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/services/metered-credit.service.ts@@ -0,0 +1,183 @@+/* @license Enterprise */++import { Injectable, Logger } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';++import { isDefined } from 'twenty-shared/utils';+import { type Repository } from 'typeorm';++import { billingValidator } from 'src/engine/core-modules/billing/billing.validate';+import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';+import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';+import { StripeBillingAlertService } from 'src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service';+import { StripeCreditGrantService } from 'src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service';++export type MeteredPricingInfo = {+ tierCap: number;+ unitPriceCents: number;+ stripeMeterId?: string;+};++@Injectable()+export class MeteredCreditService {+ protected readonly logger = new Logger(MeteredCreditService.name);++ constructor(+ @InjectRepository(BillingSubscriptionEntity)+ private readonly billingSubscriptionRepository: Repository<BillingSubscriptionEntity>,+ @InjectRepository(BillingPriceEntity)+ private readonly billingPriceRepository: Repository<BillingPriceEntity>,+ private readonly billingSubscriptionItemService: BillingSubscriptionItemService,+ private readonly stripeBillingAlertService: StripeBillingAlertService,+ private readonly stripeCreditGrantService: StripeCreditGrantService,+ ) {}++ /**+ * Get metered pricing info for a subscription by looking up the metered subscription item+ * and extracting tier cap and unit price from the associated price.+ */+ async getMeteredPricingInfo(+ subscriptionId: string,+ ): Promise<MeteredPricingInfo | null> {+ const subscription = await this.billingSubscriptionRepository.findOne({+ where: { id: subscriptionId },+ relations: [+ 'billingSubscriptionItems',+ 'billingSubscriptionItems.billingProduct',+ 'billingSubscriptionItems.billingProduct.billingPrices',+ ],+ });++ if (!isDefined(subscription)) {+ return null;+ }++ const meteredItem = subscription.billingSubscriptionItems.find(+ (item) =>+ item.billingProduct.metadata.productKey ===+ BillingProductKey.WORKFLOW_NODE_EXECUTION,+ );++ if (!isDefined(meteredItem)) {+ return null;+ }++ const matchingPrice = meteredItem.billingProduct.billingPrices.find(+ (price) => price.stripePriceId === meteredItem.stripePriceId,+ );++ if (!isDefined(matchingPrice)) {+ return null;+ }++ if (!billingValidator.isMeteredTiersSchema(matchingPrice.tiers)) {+ return null;+ }++ return {+ tierCap: matchingPrice.tiers[0].up_to,+ unitPriceCents: Number(matchingPrice.tiers[1].unit_amount_decimal),+ stripeMeterId: matchingPrice.stripeMeterId ?? undefined,+ };+ }++ /**+ * Get metered pricing info directly from a price ID.+ */+ async getMeteredPricingInfoFromPriceId(+ priceId: string,+ ): Promise<MeteredPricingInfo> {+ const price = await this.billingPriceRepository.findOneOrFail({+ where: { stripePriceId: priceId },+ });++ billingValidator.assertIsMeteredTiersSchemaOrThrow(price.tiers);++ return {+ tierCap: price.tiers[0].up_to,+ unitPriceCents: Number(price.tiers[1].unit_amount_decimal),+ stripeMeterId: price.stripeMeterId ?? undefined,+ };+ }++ /**+ * Get metered rollover parameters for a subscription.+ * Returns null if no metered item is found.+ */+ async getMeteredRolloverParameters(subscriptionId: string): Promise<{+ stripeMeterId: string;+ tierQuantity: number;+ unitPriceCents: number;+ } | null> {+ const meteredDetails =+ await this.billingSubscriptionItemService.getMeteredSubscriptionItemDetails(+ subscriptionId,+ );++ const meteredItem = meteredDetails.find(+ (item) => item.productKey === BillingProductKey.WORKFLOW_NODE_EXECUTION,+ );++ if (!meteredItem) {+ return null;+ }++ return {+ stripeMeterId: meteredItem.stripeMeterId,+ tierQuantity: meteredItem.tierQuantity,+ unitPriceCents: meteredItem.unitPriceCents,+ };+ }++ /**+ * Recreate billing alert for a subscription. This archives existing alerts and creates+ * a new one with the correct threshold based on current pricing and credit balance.+ */+ async recreateBillingAlertForSubscription(+ subscription: BillingSubscriptionEntity,+ periodStart?: Date,+ ): Promise<void> {+ const meteredPricingInfo = await this.getMeteredPricingInfo(+ subscription.id,+ );++ if (!isDefined(meteredPricingInfo)) {+ this.logger.warn(+ `Cannot create billing alert: metered pricing info not found for subscription ${subscription.id}`,+ );++ return;+ }++ const creditBalance =+ await this.stripeCreditGrantService.getCustomerCreditBalance(+ subscription.stripeCustomerId,+ meteredPricingInfo.unitPriceCents,+ );++ // Use the subscription's current period start if not provided+ const effectivePeriodStart = periodStart ?? subscription.currentPeriodStart;++ await this.stripeBillingAlertService.createUsageThresholdAlertForCustomerMeter(+ subscription.stripeCustomerId,+ meteredPricingInfo.tierCap,+ creditBalance,+ effectivePeriodStart,+ );+ }++ /**+ * Get credit balance for a customer in credit units (not monetary).+ */+ async getCreditBalance(+ stripeCustomerId: string,+ unitPriceCents: number,+ ): Promise<number> {+ return this.stripeCreditGrantService.getCustomerCreditBalance(+ stripeCustomerId,+ unitPriceCents,+ );+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service.tsindex 91922e2eca3..cb4e7beb13d 100644--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-billing-alert.service.ts@@ -1,4 +1,4 @@-import { Injectable, Logger } from '@nestjs/common';+import { Injectable } from '@nestjs/common';import { assertIsDefinedOrThrow } from 'twenty-shared/utils';@@ -12,7 +12,6 @@ import { BillingMeterEventName } from 'src/engine/core-modules/billing/enums/bil@Injectable()export class StripeBillingAlertService {- protected readonly logger = new Logger(StripeBillingAlertService.name);private readonly stripe: Stripe;constructor(@@ -32,10 +31,12 @@ export class StripeBillingAlertService {async createUsageThresholdAlertForCustomerMeter(customerId: string,tierCap: number,+ creditBalance: number = 0,+ periodStart?: Date,): Promise<void> {const meter = (await this.stripeBillingMeterService.getAllMeters()).find(- (meter) => {- return meter.event_name === BillingMeterEventName.WORKFLOW_NODE_RUN;+ (meterItem) => {+ return meterItem.event_name === BillingMeterEventName.WORKFLOW_NODE_RUN;},);@@ -43,13 +44,21 @@ export class StripeBillingAlertService {await this.archiveAlertsForCustomer(customerId, meter.id);- const cumulativeUsage =- await this.stripeBillingMeterEventService.getTotalCumulativeUsage(- meter.id,- customerId,- );+ // Use cumulative usage at period start to ensure consistent threshold+ // regardless of when the alert is created/recreated during the period+ const usageAtPeriodStart = periodStart+ ? await this.stripeBillingMeterEventService.getCumulativeUsageAtTime(+ meter.id,+ customerId,+ periodStart,+ )+ : await this.stripeBillingMeterEventService.getTotalCumulativeUsage(+ meter.id,+ customerId,+ );- const dynamicThreshold = cumulativeUsage + tierCap;+ // Threshold = usage at period start + allowance for this period+ const dynamicThreshold = usageAtPeriodStart + tierCap + creditBalance;await this.stripe.billing.alerts.create({alert_type: 'usage_threshold',@@ -66,10 +75,6 @@ export class StripeBillingAlertService {],},});-- this.logger.log(- `Created billing alert for customer ${customerId}: threshold=${dynamicThreshold} (cumulative=${cumulativeUsage} + tierCap=${tierCap})`,- );}private async archiveAlertsForCustomer(@@ -91,7 +96,6 @@ export class StripeBillingAlertService {for (const alert of customerAlerts) {await this.stripe.billing.alerts.archive(alert.id);- this.logger.log(`Archived alert ${alert.id} for customer ${customerId}`);}}}diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-billing-meter-event.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-billing-meter-event.service.tsindex 53b6a8c4382..1c21152d6bb 100644--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-billing-meter-event.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-billing-meter-event.service.ts@@ -5,8 +5,8 @@ import { Injectable, Logger } from '@nestjs/common';import type Stripe from 'stripe';import { type BillingMeterEventName } from 'src/engine/core-modules/billing/enums/billing-meter-event-names';-import { type BillingDimensions } from 'src/engine/core-modules/billing/types/billing-dimensions.type';import { StripeSDKService } from 'src/engine/core-modules/billing/stripe/stripe-sdk/services/stripe-sdk.service';+import { type BillingDimensions } from 'src/engine/core-modules/billing/types/billing-dimensions.type';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';@Injectable()@@ -84,7 +84,7 @@ export class StripeBillingMeterEventService {stripeMeterId: string,stripeCustomerId: string,): Promise<number> {- const startTime = new Date(0);+ const startTime = this.getMinimumMeterStartTime();const endTime = new Date();return this.sumMeterEvents(@@ -94,4 +94,28 @@ export class StripeBillingMeterEventService {endTime,);}++ async getCumulativeUsageAtTime(+ stripeMeterId: string,+ stripeCustomerId: string,+ atTime: Date,+ ): Promise<number> {+ const startTime = this.getMinimumMeterStartTime();++ return this.sumMeterEvents(+ stripeMeterId,+ stripeCustomerId,+ startTime,+ atTime,+ );+ }++ /**+ * Returns a reasonable minimum start time for meter queries.+ * Stripe's billing meters API doesn't accept timestamps from 1970 (epoch).+ * Using 2020-01-01 as a safe minimum since Stripe Billing Meters is a recent feature.+ */+ private getMinimumMeterStartTime(): Date {+ return new Date('2020-01-01T00:00:00Z');+ }}diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service.tsnew file mode 100644index 00000000000..04973e7005d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service.ts@@ -0,0 +1,117 @@+/* @license Enterprise */++import { Injectable } from '@nestjs/common';++import type Stripe from 'stripe';++import { StripeSDKService } from 'src/engine/core-modules/billing/stripe/stripe-sdk/services/stripe-sdk.service';+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';++@Injectable()+export class StripeCreditGrantService {+ private readonly stripe: Stripe;++ constructor(+ private readonly twentyConfigService: TwentyConfigService,+ private readonly stripeSDKService: StripeSDKService,+ ) {+ if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {+ return;+ }+ this.stripe = this.stripeSDKService.getStripe(+ this.twentyConfigService.get('BILLING_STRIPE_API_KEY'),+ );+ }++ async createCreditGrant({+ customerId,+ creditUnits,+ unitPriceCents,+ expiresAt,+ metadata,+ }: {+ customerId: string;+ creditUnits: number;+ unitPriceCents: number;+ expiresAt: Date;+ metadata: Record<string, string>;+ }): Promise<Stripe.Billing.CreditGrant> {+ const monetaryAmount = this.convertCreditsToMonetary(+ creditUnits,+ unitPriceCents,+ );++ // Add 60 seconds buffer to ensure effective_at is in the future when Stripe processes it+ const effectiveAt = Math.floor(Date.now() / 1000) + 60;++ return this.stripe.billing.creditGrants.create({+ customer: customerId,+ amount: {+ type: 'monetary',+ monetary: { currency: 'usd', value: monetaryAmount },+ },+ applicability_config: {+ scope: { price_type: 'metered' },+ },+ category: 'promotional',+ effective_at: effectiveAt,+ expires_at: Math.floor(expiresAt.getTime() / 1000),+ name: 'Rollover credits',+ metadata,+ });+ }++ async getCustomerCreditBalance(+ customerId: string,+ unitPriceCents: number,+ ): Promise<number> {+ const balance = await this.stripe.billing.creditBalanceSummary.retrieve({+ customer: customerId,+ filter: {+ type: 'applicability_scope',+ applicability_scope: { price_type: 'metered' },+ },+ });++ const availableAmount =+ balance.balances?.[0]?.available_balance?.monetary?.value;++ if (!availableAmount) {+ return 0;+ }++ return this.convertMonetaryToCredits(availableAmount, unitPriceCents);+ }++ async voidCreditGrant(creditGrantId: string): Promise<void> {+ await this.stripe.billing.creditGrants.voidGrant(creditGrantId);+ }++ async listCreditGrants(+ customerId: string,+ ): Promise<Stripe.Billing.CreditGrant[]> {+ const grants = await this.stripe.billing.creditGrants.list({+ customer: customerId,+ });++ return grants.data;+ }++ private convertCreditsToMonetary(+ creditUnits: number,+ unitPriceCents: number,+ ): number {+ return Math.round(creditUnits * unitPriceCents);+ }++ private convertMonetaryToCredits(+ monetaryAmountCents: number,+ unitPriceCents: number,+ ): number {+ if (unitPriceCents === 0) {+ return 0;+ }++ return Math.round(monetaryAmountCents / unitPriceCents);+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/stripe.module.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/stripe.module.tsindex 70c8850f6fa..ecbdc0f3b08 100644--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/stripe.module.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/stripe.module.ts@@ -15,6 +15,7 @@ import { StripeSubscriptionItemService } from 'src/engine/core-modules/billing/simport { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';import { StripeWebhookService } from 'src/engine/core-modules/billing/stripe/services/stripe-webhook.service';+import { StripeCreditGrantService } from 'src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service';import { StripeSDKModule } from 'src/engine/core-modules/billing/stripe/stripe-sdk/stripe-sdk.module';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { DomainServerConfigModule } from 'src/engine/core-modules/domain/domain-server-config/domain-server-config.module';@@ -38,6 +39,7 @@ import { DomainServerConfigModule } from 'src/engine/core-modules/domain/domain-StripeProductService,StripeBillingMeterEventService,StripeBillingAlertService,+ StripeCreditGrantService,],exports: [StripeWebhookService,@@ -52,6 +54,7 @@ import { DomainServerConfigModule } from 'src/engine/core-modules/domain/domain-StripeBillingMeterEventService,StripeSubscriptionScheduleService,StripeBillingAlertService,+ StripeCreditGrantService,],})export class StripeModule {}diff --git a/packages/twenty-server/src/engine/core-modules/telemetry/telemetry.service.ts b/packages/twenty-server/src/engine/core-modules/telemetry/telemetry.service.tsindex acf3e77bc28..b780fb3c3d0 100644--- a/packages/twenty-server/src/engine/core-modules/telemetry/telemetry.service.ts+++ b/packages/twenty-server/src/engine/core-modules/telemetry/telemetry.service.ts@@ -1,5 +1,5 @@import { HttpService } from '@nestjs/axios';-import { Injectable, Logger } from '@nestjs/common';+import { Injectable } from '@nestjs/common';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';@@ -10,8 +10,6 @@ type CreateEventInput = {@Injectable()export class TelemetryService {- private readonly logger = new Logger(TelemetryService.name);-constructor(private readonly twentyConfigService: TwentyConfigService,private readonly httpService: HttpService,@@ -39,14 +37,7 @@ export class TelemetryService {try {await this.httpService.axiosRef.post(`/selfHostingEvent`, data);- } catch (error) {- this.logger.error('Error occurred:', error);- if (error.response) {- this.logger.error(- `Error response body: ${JSON.stringify(error.response.data)}`,- );- }-+ } catch {return { success: false };}diff --git a/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-price-created-data.util.ts b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-price-created-data.util.tsindex adcb11cf0c2..7a4bc8125ff 100644--- a/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-price-created-data.util.ts+++ b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-price-created-data.util.ts@@ -16,7 +16,6 @@ export const createMockStripePriceCreatedData = (nickname: null,product: 'prod_RLN',recurring: {- aggregate_usage: null,interval: 'month',interval_count: 1,meter: null,diff --git a/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-subscription-created-data.util.ts b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-subscription-created-data.util.tsindex 9cbb8e6ee16..bfe3bd73971 100644--- a/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-subscription-created-data.util.ts+++ b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-subscription-created-data.util.ts@@ -15,7 +15,6 @@ export const createMockStripeSubscriptionCreatedData = (id: 'plan_default',object: 'plan',active: true,- aggregate_usage: null,amount_decimal: '0',billing_scheme: 'per_unit',interval_count: 1,@@ -37,6 +36,8 @@ export const createMockStripeSubscriptionCreatedData = (object: 'subscription_item',billing_thresholds: null,created: 0,+ current_period_end: 1672531200,+ current_period_start: 1672531200,discounts: [],metadata: {},price: {@@ -53,7 +54,6 @@ export const createMockStripeSubscriptionCreatedData = (nickname: null,product: 'prod_default',recurring: {- aggregate_usage: null,interval: 'month',interval_count: 1,meter: null,@@ -77,8 +77,6 @@ export const createMockStripeSubscriptionCreatedData = (},cancel_at_period_end: false,currency: 'usd',- current_period_end: 1672531200,- current_period_start: 1672531200,metadata: { workspaceId: '3b8e6458-5fc1-4e63-8563-008ccddaa6db' },trial_end: null,trial_start: null,@@ -87,6 +85,7 @@ export const createMockStripeSubscriptionCreatedData = (application: null,application_fee_percent: null,automatic_tax: {+ disabled_reason: null,enabled: true,liability: {type: 'self',@@ -94,6 +93,10 @@ export const createMockStripeSubscriptionCreatedData = (},billing_cycle_anchor: 0,billing_cycle_anchor_config: null,+ billing_mode: {+ type: 'flexible',+ flexible: {},+ },billing_thresholds: null,cancel_at: null,cancellation_details: null,@@ -103,7 +106,6 @@ export const createMockStripeSubscriptionCreatedData = (default_payment_method: null,default_source: null,description: null,- discount: null,discounts: [],ended_at: null,invoice_settings: {diff --git a/yarn.lock b/yarn.lockindex 9bc128a2f82..c91586a2267 100644--- a/yarn.lock+++ b/yarn.lock@@ -24847,7 +24847,7 @@ __metadata:languageName: nodelinkType: hard-"@types/node@npm:*, @types/node@npm:>=10.0.0, @types/node@npm:>=13.7.0, @types/node@npm:>=8.1.0, @types/node@npm:^24.0.0":+"@types/node@npm:*, @types/node@npm:>=10.0.0, @types/node@npm:>=13.7.0, @types/node@npm:^24.0.0":version: 24.3.1resolution: "@types/node@npm:24.3.1"dependencies:@@ -55067,13 +55067,17 @@ __metadata:languageName: nodelinkType: hard-"stripe@npm:17.3.1":- version: 17.3.1- resolution: "stripe@npm:17.3.1"+"stripe@npm:19.3.1":+ version: 19.3.1+ resolution: "stripe@npm:19.3.1"dependencies:- "@types/node": "npm:>=8.1.0"qs: "npm:^6.11.0"- checksum: 10c0/96c9595428775d3bb5d619f770dd4775357ec778be4033915d629ef6033d29a70ec4d916311cc2e1e5e5e45646d9b53fcef6215e60e1ea183d89554bd61e7055+ peerDependencies:+ "@types/node": ">=16"+ peerDependenciesMeta:+ "@types/node":+ optional: true+ checksum: 10c0/986b42cf25993ad7ee6aa378bac581dc6b403b8424cfb0363595062c0d4afcf79b5a15f05ee08dc9b9e93d3559c3ec9f300f786c61a3be1fdb89851660f8af8dlanguageName: nodelinkType: hard@@ -56953,7 +56957,7 @@ __metadata:rxjs: "npm:7.8.1"semver: "npm:7.6.3"sharp: "npm:0.32.6"- stripe: "npm:17.3.1"+ stripe: "npm:19.3.1"transliteration: "npm:2.3.5"tsconfig-paths: "npm:^4.2.0"tsdav: "npm:^2.1.5"