The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(billing): identify subscription items by product key, not by quantity (#26635)
Etienne8167613970c4
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 273bc7ee233..48158e2de0b 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@@ -30,7 +30,6 @@ import { BillingPortalWorkspaceService } from 'src/engine/core-modules/billing/simport { 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 { BillingCreditAllowanceProvider } from 'src/engine/core-modules/billing/services/billing-credit-allowance-provider.service';import { BillingUsageLimitEntitlementProvider } from 'src/engine/core-modules/billing/services/billing-usage-limit-entitlement-provider.service';import { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';@@ -91,7 +90,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingSubscriptionItemService,BillingPortalWorkspaceService,BillingProductService,- BillingSubscriptionPhaseService,BillingResolver,BillingSubscriptionItemResolver,BillingPlanService,@@ -120,7 +118,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingSubscriptionService,BillingSubscriptionUpdateService,BillingSubscriptionItemService,- BillingSubscriptionPhaseService,BillingPortalWorkspaceService,BillingService,BillingUsageService,diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.validate.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.validate.tsindex ec877b710e1..5680e1fcf53 100644--- a/packages/twenty-server/src/engine/core-modules/billing/billing.validate.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.validate.ts@@ -1,4 +1,3 @@-import { msg } from '@lingui/core/macro';import { isDefined } from 'twenty-shared/utils';import { isNumber } from 'class-validator';@@ -8,15 +7,9 @@ import {} from 'src/engine/core-modules/billing/billing.exception';import { type BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';import { type BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';-import { type 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 { BillingUsageType } from 'src/engine/core-modules/billing/enums/billing-usage-type.enum';import { type BillingMeterPrice } from 'src/engine/core-modules/billing/types/billing-meter-price.type';-import {- type LicensedBillingSubscriptionItem,- type MeteredBillingSubscriptionItem,-} from 'src/engine/core-modules/billing/types/billing-subscription-item.type';-import { type BillingSubscriptionWithSubscriptionItems } from 'src/engine/core-modules/billing/types/billing-subscription-with-subscription-items.type';import { type MeterBillingPriceTiers } from 'src/engine/core-modules/billing/types/meter-billing-price-tier.type';const assertIsMeteredTiersSchemaOrThrow = (@@ -52,38 +45,6 @@ const isMeteredTiersSchema = (return true;};-const assertIsLicensedSubscriptionItem = (- subscriptionItem: BillingSubscriptionItemEntity,-): asserts subscriptionItem is LicensedBillingSubscriptionItem => {- if (- subscriptionItem.quantity !== null &&- subscriptionItem.billingProduct.metadata.priceUsageBased ===- BillingUsageType.LICENSED- )- return;-- throw new BillingException(- 'Subscription Item is not a licence subscription item',- BillingExceptionCode.BILLING_SUBSCRIPTION_ITEM_INVALID,- );-};--const assertIsMeteredSubscriptionItem = (- subscriptionItem: BillingSubscriptionItemEntity,-): asserts subscriptionItem is MeteredBillingSubscriptionItem => {- if (- subscriptionItem.quantity === null &&- subscriptionItem.billingProduct.metadata.priceUsageBased ===- BillingUsageType.METERED- )- return;-- throw new BillingException(- 'Subscription Item is not a meter subscription item',- BillingExceptionCode.BILLING_SUBSCRIPTION_ITEM_INVALID,- );-};-const assertIsMeteredPrice = (price: BillingPriceEntity,): asserts price is BillingMeterPrice => {@@ -120,36 +81,6 @@ const isMeteredPrice = (return true;};-const assertIsSubscription = (- subscription: BillingSubscriptionEntity | undefined,-): asserts subscription is BillingSubscriptionEntity &- BillingSubscriptionWithSubscriptionItems => {- if (!isDefined(subscription)) {- throw new BillingException(- 'Subscription is not defined',- BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_FOUND,- );- }- if (!isDefined(subscription.billingSubscriptionItems)) {- throw new BillingException(- 'Subscription items is not defined. Check the relation in the query',- BillingExceptionCode.BILLING_SUBSCRIPTION_ITEM_NOT_FOUND,- );- }-- if (subscription.billingSubscriptionItems.length !== 2) {- throw new BillingException(- 'Subscription must have exactly two subscription items. Check that stripe and database are in sync',- BillingExceptionCode.BILLING_SUBSCRIPTION_INVALID,- {- userFriendlyMessage: msg`Your billing subscription is corrupted. Please contact support.`,- },- );- }-- return;-};-// V2 validators — do not throw for V1 items; only used on V2 code pathsconst isLicensedResourceCreditItem = (@@ -192,10 +123,7 @@ const getCapFromCreditMetadata = (price: BillingPriceEntity): number => {export const billingValidator: {assertIsMeteredTiersSchemaOrThrow: typeof assertIsMeteredTiersSchemaOrThrow;isMeteredTiersSchema: typeof isMeteredTiersSchema;- assertIsLicensedSubscriptionItem: typeof assertIsLicensedSubscriptionItem;- assertIsMeteredSubscriptionItem: typeof assertIsMeteredSubscriptionItem;assertIsMeteredPrice: typeof assertIsMeteredPrice;- assertIsSubscription: typeof assertIsSubscription;isMeteredPrice: typeof isMeteredPrice;assertIsLicensedResourceCreditPrice: typeof assertIsLicensedResourceCreditPrice;isLicensedResourceCreditItem: typeof isLicensedResourceCreditItem;@@ -203,10 +131,7 @@ export const billingValidator: {} = {assertIsMeteredTiersSchemaOrThrow,isMeteredTiersSchema,- assertIsLicensedSubscriptionItem,- assertIsMeteredSubscriptionItem,assertIsMeteredPrice,- assertIsSubscription,isMeteredPrice,assertIsLicensedResourceCreditPrice,isLicensedResourceCreditItem,diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/billing-subscription-update.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/billing-subscription-update.service.spec.tsindex d71400e6575..a237c955227 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/billing-subscription-update.service.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__tests__/billing-subscription-update.service.spec.ts@@ -11,7 +11,6 @@ import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billimport { SubscriptionUpdateType } from 'src/engine/core-modules/billing/types/billing-subscription-update.type';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 { BillingSubscriptionUpdateService } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';import { StripeInvoiceService } from 'src/engine/core-modules/billing/stripe/services/stripe-invoice.service';@@ -66,12 +65,12 @@ const buildPrice = ({billingProduct: product,}) as unknown as BillingPriceEntity;-const licensedMonth = buildPrice({+const baseProductMonth = buildPrice({stripePriceId: 'price_base_month',interval: SubscriptionInterval.Month,product: baseProduct,});-const licensedYear = buildPrice({+const baseProductYear = buildPrice({stripePriceId: 'price_base_year',interval: SubscriptionInterval.Year,product: baseProduct,@@ -97,15 +96,15 @@ const creditYearPackages = [600, 1200, 2400].map((creditAmount) =>);const allPrices = [- licensedMonth,- licensedYear,+ baseProductMonth,+ baseProductYear,...creditMonthPackages,...creditYearPackages,];// The interval lookup for the base product reads the prices off the product it// is given, so the fixture products carry their own prices.-baseProduct.billingPrices.push(licensedMonth, licensedYear);+baseProduct.billingPrices.push(baseProductMonth, baseProductYear);resourceCreditProduct.billingPrices.push(...creditMonthPackages,...creditYearPackages,@@ -168,7 +167,6 @@ describe('BillingSubscriptionUpdateService interval switch', () => {{ provide: StripeSubscriptionService, useValue: noop },{ provide: StripeInvoiceService, useValue: noop },{ provide: StripeSubscriptionScheduleService, useValue: noop },- { provide: BillingSubscriptionPhaseService, useValue: noop },{ provide: BillingSubscriptionService, useValue: noop },{ provide: WorkspaceOrmManager, useValue: noop },],@@ -186,14 +184,14 @@ describe('BillingSubscriptionUpdateService interval switch', () => {newInterval: SubscriptionInterval.Year,},{- licensedPriceId: 'price_base_month',+ baseProductPriceId: 'price_base_month',resourceCreditPriceId: 'price_credits_month_100',seats: 3,} as never,);expect(result.resourceCreditPriceId).toBe('price_credits_year_1200');- expect(result.licensedPriceId).toBe('price_base_year');+ expect(result.baseProductPriceId).toBe('price_base_year');});it('moves a yearly package back to the monthly package worth a twelfth of it', async () => {@@ -203,14 +201,14 @@ describe('BillingSubscriptionUpdateService interval switch', () => {newInterval: SubscriptionInterval.Month,},{- licensedPriceId: 'price_base_year',+ baseProductPriceId: 'price_base_year',resourceCreditPriceId: 'price_credits_year_1200',seats: 3,} as never,);expect(result.resourceCreditPriceId).toBe('price_credits_month_100');- expect(result.licensedPriceId).toBe('price_base_month');+ expect(result.baseProductPriceId).toBe('price_base_month');});it('switches interval on a product holding several packages at that interval', async () => {@@ -230,7 +228,7 @@ describe('BillingSubscriptionUpdateService interval switch', () => {newInterval: SubscriptionInterval.Year,},{- licensedPriceId: 'price_base_month',+ baseProductPriceId: 'price_base_month',resourceCreditPriceId: 'price_credits_month_100',seats: 1,} as never,@@ -240,7 +238,7 @@ describe('BillingSubscriptionUpdateService interval switch', () => {it('leaves the prices untouched when the interval already matches', async () => {const currentPrices = {- licensedPriceId: 'price_base_month',+ baseProductPriceId: 'price_base_month',resourceCreditPriceId: 'price_credits_month_100',seats: 2,};diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-plan.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-plan.service.tsindex 516bbe47b3e..14f0a15ef94 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-plan.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-plan.service.ts@@ -3,7 +3,6 @@import { Injectable, Logger } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';-import { findOrThrow } from 'twenty-shared/utils';import { Repository } from 'typeorm';import {@@ -66,30 +65,6 @@ export class BillingPlanService {});}- async getPlanByPriceId(stripePriceId: string) {- const plans = await this.listPlans();-- return findOrThrow(plans, (plan) => {- return (- plan.meteredProducts.some((product) =>- product.billingPrices.some(- (price) => price.stripePriceId === stripePriceId,- ),- ) ||- plan.baseProducts.some((product) =>- product.billingPrices.some(- (price) => price.stripePriceId === stripePriceId,- ),- ) ||- plan.resourceCreditProducts.some((product) =>- product.billingPrices.some(- (price) => price.stripePriceId === stripePriceId,- ),- )- );- });- }-async getPricesPerPlanByInterval({planKey,interval,diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-phase.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-phase.service.tsdeleted file mode 100644index 46e1d9d05db..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription-phase.service.ts+++ /dev/null@@ -1,217 +0,0 @@-/* @license Enterprise */--import { Injectable } from '@nestjs/common';-import { InjectRepository } from '@nestjs/typeorm';--import {- assertIsDefinedOrThrow,- findOrThrow,- isDefined,-} from 'twenty-shared/utils';-import { type Repository } from 'typeorm';--import type Stripe from 'stripe';--import { type BillingSubscriptionSchedulePhaseDTO } from 'src/engine/core-modules/billing/dtos/billing-subscription-schedule-phase.dto';-import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';-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 { SubscriptionStripePrices } from 'src/engine/core-modules/billing/services/billing-subscription-update.service';-import { normalizePriceRef } from 'src/engine/core-modules/billing/utils/normalize-price-ref.utils';--@Injectable()-export class BillingSubscriptionPhaseService {- constructor(- @InjectRepository(BillingPriceEntity)- private readonly billingPriceRepository: Repository<BillingPriceEntity>,- private readonly billingPlanService: BillingPlanService,- private readonly billingPriceService: BillingPriceService,- ) {}-- async getDetailsFromPhase(phase: BillingSubscriptionSchedulePhaseDTO) {- const meteredPrice = await this.billingPriceRepository.findOneOrFail({- where: {- stripePriceId: findOrThrow(- phase.items,- ({ quantity }) => !isDefined(quantity),- ).price,- },- });-- const { quantity, price: licensedItemPriceId } = findOrThrow(- phase.items,- ({ quantity }) => isDefined(quantity),- );-- const licensedPrice = await this.billingPriceRepository.findOneOrFail({- where: {- stripePriceId: licensedItemPriceId,- },- });-- const plan = await this.billingPlanService.getPlanByPriceId(- meteredPrice.stripePriceId,- );-- if (!isDefined(quantity)) {- throw new Error('Quantity is not defined');- }-- return {- plan,- meteredPrice,- licensedPrice,- quantity,- interval: meteredPrice.interval,- };- }-- toPhaseUpdateParams(- phase: Stripe.SubscriptionSchedule.Phase,- ): Stripe.SubscriptionScheduleUpdateParams.Phase {- return {- start_date: phase.start_date,- end_date: phase.end_date ?? undefined,- items: (phase.items || []).map((it) => ({- price: normalizePriceRef(it.price) as string,- quantity: it.quantity ?? undefined,- })),- ...(phase.billing_thresholds- ? { billing_thresholds: phase.billing_thresholds }- : {}),- proration_behavior: 'none',- } as Stripe.SubscriptionScheduleUpdateParams.Phase;- }-- buildPhaseUpdateParams({- toUpdatePrices,- startDate,- endDate,- }: {- toUpdatePrices: SubscriptionStripePrices;- startDate: Stripe.SubscriptionScheduleUpdateParams.Phase['start_date'];- endDate: number | undefined;- }): Stripe.SubscriptionScheduleUpdateParams.Phase {- return {- start_date: startDate,- ...(endDate ? { end_date: endDate } : {}),- proration_behavior: 'none',- items: [- {- price: toUpdatePrices.licensedPriceId,- quantity: toUpdatePrices.seats,- },- { price: toUpdatePrices.resourceCreditPriceId, quantity: 1 },- ],- };- }-- getLicensedPriceIdAndQuantityFromPhaseUpdateParams(- phase: Stripe.SubscriptionScheduleUpdateParams.Phase,- ): { price: string; quantity: number } {- const licensedItem = findOrThrow(phase.items!, (i) => i.quantity != null);-- assertIsDefinedOrThrow(licensedItem.price);- assertIsDefinedOrThrow(licensedItem.quantity);-- return {- price: licensedItem.price,- quantity: licensedItem.quantity,- };- }-- async isSamePhaseSignature(- a: Stripe.SubscriptionScheduleUpdateParams.Phase,- b: Stripe.SubscriptionScheduleUpdateParams.Phase,- ): Promise<boolean> {- try {- const phaseALicensedPriceIdAndQuantity =- this.getLicensedPriceIdAndQuantityFromPhaseUpdateParams(a);- const phaseBLicensedPriceIdAndQuantity =- this.getLicensedPriceIdAndQuantityFromPhaseUpdateParams(b);- const phaseAResourceCreditPriceId =- this.getResourceCreditPriceIdFromPhaseUpdateParams(a);- const phaseBResourceCreditPriceId =- this.getResourceCreditPriceIdFromPhaseUpdateParams(b);-- return (- phaseALicensedPriceIdAndQuantity.price ===- phaseBLicensedPriceIdAndQuantity.price &&- phaseALicensedPriceIdAndQuantity.quantity ===- phaseBLicensedPriceIdAndQuantity.quantity &&- phaseAResourceCreditPriceId === phaseBResourceCreditPriceId- );- } catch {- return false;- }- }- async buildResourceCreditPhaseUpdateParams({- basePlanStripePriceId,- seats,- resourceCreditStripePriceId,- startDate,- endDate,- }: {- basePlanStripePriceId: string;- seats: number;- resourceCreditStripePriceId: string;- startDate: Stripe.SubscriptionScheduleUpdateParams.Phase['start_date'];- endDate: number | undefined;- }): Promise<Stripe.SubscriptionScheduleUpdateParams.Phase> {- return {- start_date: startDate,- ...(endDate ? { end_date: endDate } : {}),- proration_behavior: 'none',- items: [- { price: basePlanStripePriceId, quantity: seats },- { price: resourceCreditStripePriceId, quantity: 1 },- ],- };- }-- // Billing V2: compares resource credit Stripe price id between phases- async isSameResourceCreditPhaseSignature(- a: Stripe.SubscriptionScheduleUpdateParams.Phase,- b: Stripe.SubscriptionScheduleUpdateParams.Phase,- ): Promise<boolean> {- try {- const phaseALicensedPriceIdAndQuantity =- this.getLicensedPriceIdAndQuantityFromPhaseUpdateParams(a);- const phaseBLicensedPriceIdAndQuantity =- this.getLicensedPriceIdAndQuantityFromPhaseUpdateParams(b);- const phaseAResourceCreditPriceId =- this.getResourceCreditPriceIdFromPhaseUpdateParams(a);- const phaseBResourceCreditPriceId =- this.getResourceCreditPriceIdFromPhaseUpdateParams(b);-- return (- phaseALicensedPriceIdAndQuantity.price ===- phaseBLicensedPriceIdAndQuantity.price &&- phaseALicensedPriceIdAndQuantity.quantity ===- phaseBLicensedPriceIdAndQuantity.quantity &&- phaseAResourceCreditPriceId === phaseBResourceCreditPriceId- );- } catch {- return false;- }- }-- getResourceCreditPriceIdFromPhaseUpdateParams(- phase: Stripe.SubscriptionScheduleUpdateParams.Phase,- ): string {- const items = phase.items ?? [];- const licensedPriceIdAndQuantity =- this.getLicensedPriceIdAndQuantityFromPhaseUpdateParams(phase);-- const resourceCreditItem = items.find(- (item) =>- item.price !== licensedPriceIdAndQuantity.price && item.quantity === 1,- );-- if (!resourceCreditItem?.price) {- throw new Error('Resource credit item not found in V2 phase params');- }-- return resourceCreditItem.price;- }-}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.tsindex f51a3cc72ca..5c88cbaf3b0 100644--- 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.ts@@ -26,7 +26,6 @@ import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billimport { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.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 { StripeInvoiceService } from 'src/engine/core-modules/billing/stripe/services/stripe-invoice.service';import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';@@ -38,23 +37,22 @@ import {import { computeSubscriptionUpdateOptions } from 'src/engine/core-modules/billing/utils/compute-subscription-update-options.util';import { findSellableBaseProductPriceOrThrow } from 'src/engine/core-modules/billing/utils/find-sellable-base-product-price-or-throw.util';import { findProductPriceForIntervalOrThrow } from 'src/engine/core-modules/billing/utils/find-product-price-for-interval-or-throw.util';+import { isResourceCreditPriceForSubscription } from 'src/engine/core-modules/billing/utils/is-resource-credit-price-for-subscription.util';import { isSellableCatalogPrice } from 'src/engine/core-modules/billing/utils/is-sellable-catalog-price.util';import { getBaseProductSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-base-product-subscription-item-or-throw.util';-import { getCurrentLicensedBillingSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-licensed-billing-subscription-item-or-throw.util';import { getCurrentResourceCreditSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-resource-credit-subscription-item-or-throw.util';import { normalizePriceRef } from 'src/engine/core-modules/billing/utils/normalize-price-ref.utils';+import { buildSchedulePhasesUpdate } from 'src/engine/core-modules/billing/utils/build-schedule-phases-update.util';+import { buildSubscriptionItemsUpdate } from 'src/engine/core-modules/billing/utils/build-subscription-items-update.util';+import { isSamePhaseSignature } from 'src/engine/core-modules/billing/utils/is-same-phase-signature.util';+import { toPhaseUpdateParams } from 'src/engine/core-modules/billing/utils/to-phase-update-params.util';+import { type SubscriptionStripePrices } from 'src/engine/core-modules/billing/types/subscription-stripe-prices.type';import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';-export type SubscriptionStripePrices = {- licensedPriceId: string;- seats: number;- resourceCreditPriceId: string;-};-@Injectable()export class BillingSubscriptionUpdateService {protected readonly logger = new Logger(BillingSubscriptionUpdateService.name);@@ -69,7 +67,6 @@ export class BillingSubscriptionUpdateService {@InjectWorkspaceScopedRepository(BillingSubscriptionEntity)private readonly billingSubscriptionRepository: WorkspaceScopedRepository<BillingSubscriptionEntity>,private readonly stripeSubscriptionScheduleService: StripeSubscriptionScheduleService,- private readonly billingSubscriptionPhaseService: BillingSubscriptionPhaseService,private readonly billingSubscriptionService: BillingSubscriptionService,private readonly workspaceOrmManager: WorkspaceOrmManager,) {}@@ -83,16 +80,29 @@ export class BillingSubscriptionUpdateService {{ workspaceId },);- // Only this entry point takes a price id from the client, so a superseded- // package must be refused here rather than in the shared price computation,- // which is also reused to rewrite a scheduled phase and to cancel a pending- // switch back onto the package the workspace already pays for.const newResourceCreditPrice =await this.billingPriceRepository.findOneOrFail({where: { stripePriceId: resourceCreditPriceId },relations: ['billingProduct'],});+ const currentPlanKey =+ getBaseProductSubscriptionItemOrThrow(billingSubscription).billingProduct+ ?.metadata.planKey;++ if (+ !isResourceCreditPriceForSubscription({+ billingPrice: newResourceCreditPrice,+ interval: billingSubscription.interval,+ planKey: currentPlanKey,+ })+ ) {+ throw new BillingException(+ `Resource credit price ${resourceCreditPriceId} does not match the subscription interval and plan`,+ BillingExceptionCode.BILLING_PRICE_INVALID,+ );+ }+if (!isSellableCatalogPrice(newResourceCreditPrice)) {throw new BillingException(`Resource credit price ${resourceCreditPriceId} is no longer sold`,@@ -141,8 +151,8 @@ export class BillingSubscriptionUpdateService {);const currentPlan =- getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription)- .billingProduct?.metadata.planKey;+ getBaseProductSubscriptionItemOrThrow(billingSubscription).billingProduct+ ?.metadata.planKey;await this.updateSubscription(workspaceId, billingSubscription.id, {type: SubscriptionUpdateType.PLAN,@@ -188,8 +198,8 @@ export class BillingSubscriptionUpdateService {);const currentPlan =- getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription)- .billingProduct?.metadata.planKey;+ getBaseProductSubscriptionItemOrThrow(billingSubscription).billingProduct+ ?.metadata.planKey;await this.updateSubscription(workspaceId, billingSubscription.id, {type: SubscriptionUpdateType.PLAN,@@ -228,7 +238,7 @@ export class BillingSubscriptionUpdateService {},);- const licensedItem = getBaseProductSubscriptionItemOrThrow(subscription);+ const baseProductItem = getBaseProductSubscriptionItemOrThrow(subscription);const resourceCreditItem =getCurrentResourceCreditSubscriptionItemOrThrow(subscription);@@ -240,9 +250,9 @@ export class BillingSubscriptionUpdateService {const toUpdateCurrentPrices = await this.computeSubscriptionPricesUpdate(subscriptionUpdate,{- licensedPriceId: licensedItem.stripePriceId,+ baseProductPriceId: baseProductItem.stripePriceId,resourceCreditPriceId: resourceCreditItem.stripePriceId,- seats: seats > 0 ? seats : licensedItem.quantity,+ seats: seats > 0 ? seats : baseProductItem.quantity,},);@@ -268,10 +278,7 @@ export class BillingSubscriptionUpdateService {stripeScheduleId: schedule.id,toUpdateCurrentPrices: undefined,toUpdateNextPrices: toUpdateCurrentPrices,- currentPhase:- this.billingSubscriptionPhaseService.toPhaseUpdateParams(- currentPhase,- ),+ currentPhase: toPhaseUpdateParams(currentPhase),subscriptionCurrentPeriodEnd: Math.floor(subscription.currentPeriodEnd.getTime() / 1000,),@@ -292,10 +299,8 @@ export class BillingSubscriptionUpdateService {stripeScheduleId: schedule.id,toUpdateNextPrices,toUpdateCurrentPrices: undefined,- currentPhase:- this.billingSubscriptionPhaseService.toPhaseUpdateParams(- currentPhase,- ),+ currentPhase: toPhaseUpdateParams(currentPhase),+ nextPhase: toPhaseUpdateParams(nextPhase),subscriptionCurrentPeriodEnd: Math.floor(subscription.currentPeriodEnd.getTime() / 1000,),@@ -305,7 +310,7 @@ export class BillingSubscriptionUpdateService {const subscriptionOptions = computeSubscriptionUpdateOptions(subscriptionUpdate,{- currentSeats: licensedItem.quantity,+ currentSeats: baseProductItem.quantity,isTrialing: subscription.status === SubscriptionStatus.Trialing,},);@@ -323,12 +328,10 @@ export class BillingSubscriptionUpdateService {await this.runSubscriptionUpdate({stripeSubscriptionId: subscription.stripeSubscriptionId,- licensedStripeItemId: licensedItem.stripeSubscriptionItemId,- resourceCreditStripeItemId: resourceCreditItem.stripeSubscriptionItemId,- licensedStripePriceId: toUpdateCurrentPrices.licensedPriceId,- resourceCreditStripePriceId:- toUpdateCurrentPrices.resourceCreditPriceId,- seats: toUpdateCurrentPrices.seats,+ items: buildSubscriptionItemsUpdate({+ billingSubscriptionItems: subscription.billingSubscriptionItems,+ toUpdatePrices: toUpdateCurrentPrices,+ }),...subscriptionOptions,});@@ -352,10 +355,8 @@ export class BillingSubscriptionUpdateService {stripeScheduleId: schedule.id,toUpdateNextPrices,toUpdateCurrentPrices: undefined,- currentPhase:- this.billingSubscriptionPhaseService.toPhaseUpdateParams(- refreshedCurrentPhase,- ),+ currentPhase: toPhaseUpdateParams(refreshedCurrentPhase),+ nextPhase: toPhaseUpdateParams(nextPhase),subscriptionCurrentPeriodEnd: Math.floor(subscription.currentPeriodEnd.getTime() / 1000,),@@ -428,19 +429,42 @@ export class BillingSubscriptionUpdateService {}}+ private async getProductKeyByPriceId(+ stripePriceIds: string[],+ ): Promise<Map<string, BillingProductKey>> {+ if (stripePriceIds.length === 0) {+ return new Map();+ }++ const prices = await this.billingPriceRepository.find({+ where: { stripePriceId: In(stripePriceIds) },+ relations: ['billingProduct'],+ });++ return new Map(+ prices.flatMap((price) => {+ const productKey = price.billingProduct?.metadata?.productKey;++ return isDefined(productKey)+ ? [[price.stripePriceId, productKey] as const]+ : [];+ }),+ );+ }+private async getSubscriptionPricesFromSchedulePhase(phase: Stripe.SubscriptionSchedule.Phase,): Promise<SubscriptionStripePrices> {- const licensedItemPriceIds = phase.items- .filter((item) => item.quantity != null)- .map((item) => normalizePriceRef(item.price));+ const phaseItemPriceIds = phase.items.map((item) =>+ normalizePriceRef(item.price),+ );- const licensedItemPrices = await this.billingPriceRepository.find({- where: { stripePriceId: In(licensedItemPriceIds) },+ const phaseItemPrices = await this.billingPriceRepository.find({+ where: { stripePriceId: In(phaseItemPriceIds) },relations: ['billingProduct'],});- const basePlanPrice = licensedItemPrices.find(+ const basePlanPrice = phaseItemPrices.find((price) =>price.billingProduct?.metadata?.productKey ===BillingProductKey.BASE_PRODUCT,@@ -455,7 +479,7 @@ export class BillingSubscriptionUpdateService {assertIsDefinedOrThrow(basePlanPhaseItem.quantity);- const resourceCreditPrice = licensedItemPrices.find(+ const resourceCreditPrice = phaseItemPrices.find((price) =>price.billingProduct?.metadata?.productKey ===BillingProductKey.RESOURCE_CREDIT,@@ -464,7 +488,7 @@ export class BillingSubscriptionUpdateService {assertIsDefinedOrThrow(resourceCreditPrice);return {- licensedPriceId: basePlanPrice.stripePriceId,+ baseProductPriceId: basePlanPrice.stripePriceId,seats: basePlanPhaseItem.quantity,resourceCreditPriceId: resourceCreditPrice.stripePriceId,};@@ -472,21 +496,13 @@ export class BillingSubscriptionUpdateService {private async runSubscriptionUpdate({stripeSubscriptionId,- licensedStripeItemId,- resourceCreditStripeItemId,- licensedStripePriceId,- resourceCreditStripePriceId,- seats,+ items,anchor,proration,metadata,}: {stripeSubscriptionId: string;- licensedStripeItemId: string;- resourceCreditStripeItemId: string;- licensedStripePriceId: string;- resourceCreditStripePriceId: string;- seats: number;+ items: Stripe.SubscriptionUpdateParams.Item[];anchor?: Stripe.SubscriptionUpdateParams.BillingCycleAnchor;proration?: Stripe.SubscriptionUpdateParams.ProrationBehavior;metadata?: Record<string, string>;@@ -494,18 +510,7 @@ export class BillingSubscriptionUpdateService {return await this.stripeSubscriptionService.updateSubscription(stripeSubscriptionId,{- items: [- {- id: licensedStripeItemId,- price: licensedStripePriceId,- quantity: seats,- },- {- id: resourceCreditStripeItemId,- price: resourceCreditStripePriceId,- quantity: 1,- },- ],+ items,...(anchor ? { billing_cycle_anchor: anchor } : {}),...(proration ? { proration_behavior: proration } : {}),...(metadata ? { metadata } : {}),@@ -518,41 +523,35 @@ export class BillingSubscriptionUpdateService {toUpdateNextPrices,toUpdateCurrentPrices,currentPhase,+ nextPhase,subscriptionCurrentPeriodEnd,}: {stripeScheduleId: string;toUpdateNextPrices: SubscriptionStripePrices;toUpdateCurrentPrices: SubscriptionStripePrices | undefined;currentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase;+ nextPhase?: Stripe.SubscriptionScheduleUpdateParams.Phase;subscriptionCurrentPeriodEnd: number;}) {- let toUpdateCurrentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase = {- ...currentPhase,- end_date: subscriptionCurrentPeriodEnd,- };-- if (isDefined(toUpdateCurrentPrices)) {- toUpdateCurrentPhase =- await this.billingSubscriptionPhaseService.buildPhaseUpdateParams({- toUpdatePrices: toUpdateCurrentPrices,- endDate: subscriptionCurrentPeriodEnd,- startDate: currentPhase.start_date,- });- }-- const toUpdateNextPhase =- await this.billingSubscriptionPhaseService.buildPhaseUpdateParams({- toUpdatePrices: toUpdateNextPrices,- startDate: subscriptionCurrentPeriodEnd,- endDate: undefined,+ const productKeyByPriceId = await this.getProductKeyByPriceId([+ ...new Set(+ [...(currentPhase.items ?? []), ...(nextPhase?.items ?? [])]+ .map(({ price }) => price)+ .filter(isDefined),+ ),+ ]);++ const { toUpdateCurrentPhase, toUpdateNextPhase } =+ buildSchedulePhasesUpdate({+ currentPhase,+ nextPhase,+ productKeyByPriceId,+ toUpdateCurrentPrices,+ toUpdateNextPrices,+ subscriptionCurrentPeriodEnd,});- if (- await this.billingSubscriptionPhaseService.isSamePhaseSignature(- toUpdateCurrentPhase,- toUpdateNextPhase,- )- ) {+ if (isSamePhaseSignature(toUpdateCurrentPhase, toUpdateNextPhase)) {return await this.stripeSubscriptionScheduleService.releaseSubscriptionSchedule(stripeScheduleId,);@@ -581,8 +580,8 @@ export class BillingSubscriptionUpdateService {switch (update.type) {case SubscriptionUpdateType.PLAN: {const currentPlan =- subscription.billingSubscriptionItems[0].billingProduct?.metadata- .planKey;+ getBaseProductSubscriptionItemOrThrow(subscription).billingProduct+ ?.metadata.planKey;const isDowngrade =currentPlan !== update.newPlan &&@@ -689,14 +688,14 @@ export class BillingSubscriptionUpdateService {newResourceCreditPriceId: string,currentPrices: SubscriptionStripePrices,): Promise<SubscriptionStripePrices> {- const currentLicensedPrice =+ const currentBaseProductPrice =await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: currentPrices.licensedPriceId },+ where: { stripePriceId: currentPrices.baseProductPriceId },relations: ['billingProduct'],});- const currentInterval = currentLicensedPrice.interval;+ const currentInterval = currentBaseProductPrice.interval;const currentPlanKey =- currentLicensedPrice.billingProduct?.metadata.planKey;+ currentBaseProductPrice.billingProduct?.metadata.planKey;assertIsDefinedOrThrow(currentPlanKey);@@ -739,15 +738,15 @@ export class BillingSubscriptionUpdateService {newPlan: BillingPlanKey,currentPrices: SubscriptionStripePrices,): Promise<SubscriptionStripePrices> {- const currentLicensedPrice =+ const currentBaseProductPrice =await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: currentPrices.licensedPriceId },+ where: { stripePriceId: currentPrices.baseProductPriceId },relations: ['billingProduct'],});- const currentInterval = currentLicensedPrice.interval;+ const currentInterval = currentBaseProductPrice.interval;const currentPlanKey =- currentLicensedPrice.billingProduct?.metadata.planKey;+ currentBaseProductPrice.billingProduct?.metadata.planKey;assertIsDefinedOrThrow(currentPlanKey);@@ -761,7 +760,7 @@ export class BillingSubscriptionUpdateService {planKey: newPlan,});- const targetLicensedPrice = findSellableBaseProductPriceOrThrow(+ const targetBaseProductPrice = findSellableBaseProductPriceOrThrow(billingPricesPerPlanAndIntervalArray,);@@ -786,7 +785,7 @@ export class BillingSubscriptionUpdateService {return {...currentPrices,- licensedPriceId: targetLicensedPrice.stripePriceId,+ baseProductPriceId: targetBaseProductPrice.stripePriceId,resourceCreditPriceId: targetResourceCreditPrice.stripePriceId,};}@@ -795,14 +794,14 @@ export class BillingSubscriptionUpdateService {newInterval: SubscriptionInterval,currentPrices: SubscriptionStripePrices,): Promise<SubscriptionStripePrices> {- const currentLicensedPrice =+ const currentBaseProductPrice =await this.billingPriceRepository.findOneOrFail({- where: { stripePriceId: currentPrices.licensedPriceId },+ where: { stripePriceId: currentPrices.baseProductPriceId },relations: ['billingProduct', 'billingProduct.billingPrices'],});- const currentInterval = currentLicensedPrice.interval;- const currentBillingProduct = currentLicensedPrice.billingProduct;+ const currentInterval = currentBaseProductPrice.interval;+ const currentBillingProduct = currentBaseProductPrice.billingProduct;assertIsDefinedOrThrow(currentBillingProduct);@@ -816,7 +815,7 @@ export class BillingSubscriptionUpdateService {// Switching interval is not a repackaging, so the subscription stays on the// products it already sits on rather than being resolved from the catalog.- const targetLicensedPrice = findProductPriceForIntervalOrThrow(+ const targetBaseProductPrice = findProductPriceForIntervalOrThrow(currentBillingProduct,newInterval,);@@ -844,7 +843,7 @@ export class BillingSubscriptionUpdateService {return {...currentPrices,- licensedPriceId: targetLicensedPrice.stripePriceId,+ baseProductPriceId: targetBaseProductPrice.stripePriceId,resourceCreditPriceId: targetResourceCreditPrice.stripePriceId,};}diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/billing-subscription-item.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/base-product-subscription-item.type.tssimilarity index 53%rename from packages/twenty-server/src/engine/core-modules/billing/types/billing-subscription-item.type.tsrename to packages/twenty-server/src/engine/core-modules/billing/types/base-product-subscription-item.type.tsindex fbbdf739275..c646b3c89d7 100644--- a/packages/twenty-server/src/engine/core-modules/billing/types/billing-subscription-item.type.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/types/base-product-subscription-item.type.ts@@ -1,15 +1,8 @@import { type BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';-export type LicensedBillingSubscriptionItem = Omit<+export type BaseProductSubscriptionItem = Omit<BillingSubscriptionItemEntity,'quantity'> & {quantity: number;};--export type MeteredBillingSubscriptionItem = Omit<- BillingSubscriptionItemEntity,- 'quantity'-> & {- quantity: null;-};diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/billing-subscription-with-subscription-items.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/billing-subscription-with-subscription-items.type.tsdeleted file mode 100644index 248f161fb80..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/types/billing-subscription-with-subscription-items.type.ts+++ /dev/null@@ -1,14 +0,0 @@-import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import {- type LicensedBillingSubscriptionItem,- type MeteredBillingSubscriptionItem,-} from 'src/engine/core-modules/billing/types/billing-subscription-item.type';--export type BillingSubscriptionWithSubscriptionItems = Omit<- BillingSubscriptionEntity,- 'billingSubscriptionItems'-> & {- billingSubscriptionItems: Array<- LicensedBillingSubscriptionItem | MeteredBillingSubscriptionItem- >;-};diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/subscription-stripe-prices.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/subscription-stripe-prices.type.tsnew file mode 100644index 00000000000..e25360428c0--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/types/subscription-stripe-prices.type.ts@@ -0,0 +1,7 @@+/* @license Enterprise */++export type SubscriptionStripePrices = {+ baseProductPriceId: string;+ seats: number;+ resourceCreditPriceId: string;+};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-phase-update-params-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-phase-update-params-or-throw.util.spec.tsnew file mode 100644index 00000000000..3e1d58c7dd5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-phase-update-params-or-throw.util.spec.ts@@ -0,0 +1,156 @@+/* @license Enterprise */++import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { buildPhaseUpdateParamsOrThrow } from 'src/engine/core-modules/billing/utils/build-phase-update-params-or-throw.util';++const BASE_PRICE_ID = 'price_base_month';+const CREDIT_PRICE_ID = 'price_credit_month';+const ADD_ON_PRICE_ID = 'price_add_on_month';++const productKeyByPriceId = new Map([+ [BASE_PRICE_ID, BillingProductKey.BASE_PRODUCT],+ [CREDIT_PRICE_ID, BillingProductKey.RESOURCE_CREDIT],+]);++const toUpdatePrices = {+ baseProductPriceId: 'price_base_year',+ seats: 7,+ resourceCreditPriceId: 'price_credit_year',+};++const PHASE_START = 1_700_000_000;+const NEW_START = 1_750_000_000;++const buildPhase = (items: Array<{ price: string; quantity?: number }>) => ({+ start_date: PHASE_START,+ proration_behavior: 'none' as const,+ items,+});++describe('buildPhaseUpdateParamsOrThrow', () => {+ it('rewrites the base and credit items and leaves an unclassified item untouched', () => {+ const phase = buildPhaseUpdateParamsOrThrow({+ currentPhase: buildPhase([+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ { price: ADD_ON_PRICE_ID, quantity: 1 },+ ]),+ productKeyByPriceId,+ toUpdatePrices,+ startDate: NEW_START,+ endDate: undefined,+ });++ expect(phase.start_date).toBe(NEW_START);+ expect(phase.items).toEqual([+ { price: 'price_base_year', quantity: 7 },+ { price: 'price_credit_year', quantity: 1 },+ { price: ADD_ON_PRICE_ID, quantity: 1 },+ ]);+ });++ it('keeps an unclassified item whatever its position', () => {+ const phase = buildPhaseUpdateParamsOrThrow({+ currentPhase: buildPhase([+ { price: ADD_ON_PRICE_ID, quantity: 1 },+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ ]),+ productKeyByPriceId,+ toUpdatePrices,+ startDate: NEW_START,+ endDate: undefined,+ });++ expect(phase.items?.[0]).toEqual({ price: ADD_ON_PRICE_ID, quantity: 1 });+ });++ it('keeps an item whose price the catalog does not know', () => {+ const phase = buildPhaseUpdateParamsOrThrow({+ currentPhase: buildPhase([+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ { price: 'price_never_synced', quantity: 2 },+ ]),+ productKeyByPriceId,+ toUpdatePrices,+ startDate: NEW_START,+ endDate: undefined,+ });++ expect(phase.items?.[2]).toEqual({+ price: 'price_never_synced',+ quantity: 2,+ });+ });++ it('throws when the resource credit price is missing from the catalog', () => {+ expect(() =>+ buildPhaseUpdateParamsOrThrow({+ currentPhase: buildPhase([+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ ]),+ productKeyByPriceId: new Map([+ [BASE_PRICE_ID, BillingProductKey.BASE_PRODUCT],+ ]),+ toUpdatePrices,+ startDate: NEW_START,+ endDate: undefined,+ }),+ ).toThrow('Subscription schedule phase has no resource credit item');+ });++ it('throws when the phase carries no base product item', () => {+ expect(() =>+ buildPhaseUpdateParamsOrThrow({+ currentPhase: buildPhase([{ price: CREDIT_PRICE_ID, quantity: 1 }]),+ productKeyByPriceId,+ toUpdatePrices,+ startDate: NEW_START,+ endDate: undefined,+ }),+ ).toThrow('Subscription schedule phase has no base product item');+ });++ it('throws when the base product price is missing from the catalog', () => {+ expect(() =>+ buildPhaseUpdateParamsOrThrow({+ currentPhase: buildPhase([+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ ]),+ productKeyByPriceId: new Map(),+ toUpdatePrices,+ startDate: NEW_START,+ endDate: undefined,+ }),+ ).toThrow('Subscription schedule phase has no base product item');+ });++ it('sets the end date only when one is given', () => {+ const currentPhase = buildPhase([+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ ]);++ const withoutEndDate = buildPhaseUpdateParamsOrThrow({+ currentPhase,+ productKeyByPriceId,+ toUpdatePrices,+ startDate: NEW_START,+ endDate: undefined,+ });++ const withEndDate = buildPhaseUpdateParamsOrThrow({+ currentPhase,+ productKeyByPriceId,+ toUpdatePrices,+ startDate: NEW_START,+ endDate: 1_800_000_000,+ });++ expect(withoutEndDate.end_date).toBeUndefined();+ expect(withEndDate.end_date).toBe(1_800_000_000);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-schedule-phases-update.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-schedule-phases-update.util.spec.tsnew file mode 100644index 00000000000..0da0118ff33--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-schedule-phases-update.util.spec.ts@@ -0,0 +1,130 @@+/* @license Enterprise */++import type Stripe from 'stripe';++import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { buildSchedulePhasesUpdate } from 'src/engine/core-modules/billing/utils/build-schedule-phases-update.util';++const BASE_PRICE_ID = 'price_base_month';+const CREDIT_PRICE_ID = 'price_credit_month';+const PENDING_ONLY_PRICE_ID = 'price_pending_only_month';++const PERIOD_END = 1_800_000_000;++const productKeyByPriceId = new Map([+ [BASE_PRICE_ID, BillingProductKey.BASE_PRODUCT],+ [CREDIT_PRICE_ID, BillingProductKey.RESOURCE_CREDIT],+]);++const toUpdateNextPrices = {+ baseProductPriceId: 'price_base_year',+ seats: 7,+ resourceCreditPriceId: 'price_credit_year',+};++const buildPhase = (+ items: Array<{ price: string; quantity?: number }>,+ startDate: number,+): Stripe.SubscriptionScheduleUpdateParams.Phase => ({+ start_date: startDate,+ proration_behavior: 'none',+ items,+});++const currentPhase = buildPhase(+ [+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ ],+ 1_700_000_000,+);++describe('buildSchedulePhasesUpdate', () => {+ it('keeps an item the pending phase holds and the current phase does not', () => {+ const nextPhase = buildPhase(+ [+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ { price: PENDING_ONLY_PRICE_ID, quantity: 2 },+ ],+ PERIOD_END,+ );++ const { toUpdateNextPhase } = buildSchedulePhasesUpdate({+ currentPhase,+ nextPhase,+ productKeyByPriceId,+ toUpdateCurrentPrices: undefined,+ toUpdateNextPrices,+ subscriptionCurrentPeriodEnd: PERIOD_END,+ });++ expect(toUpdateNextPhase.items).toEqual([+ { price: 'price_base_year', quantity: 7 },+ { price: 'price_credit_year', quantity: 1 },+ { price: PENDING_ONLY_PRICE_ID, quantity: 2 },+ ]);+ });++ it('drops an item the current phase holds and the pending phase does not', () => {+ const nextPhase = buildPhase(+ [+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ ],+ PERIOD_END,+ );++ const { toUpdateNextPhase } = buildSchedulePhasesUpdate({+ currentPhase: buildPhase(+ [+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ { price: PENDING_ONLY_PRICE_ID, quantity: 2 },+ ],+ 1_700_000_000,+ ),+ nextPhase,+ productKeyByPriceId,+ toUpdateCurrentPrices: undefined,+ toUpdateNextPrices,+ subscriptionCurrentPeriodEnd: PERIOD_END,+ });++ expect(toUpdateNextPhase.items).toEqual([+ { price: 'price_base_year', quantity: 7 },+ { price: 'price_credit_year', quantity: 1 },+ ]);+ });++ it('falls back to the current phase when no schedule is pending yet', () => {+ const { toUpdateNextPhase } = buildSchedulePhasesUpdate({+ currentPhase,+ nextPhase: undefined,+ productKeyByPriceId,+ toUpdateCurrentPrices: undefined,+ toUpdateNextPrices,+ subscriptionCurrentPeriodEnd: PERIOD_END,+ });++ expect(toUpdateNextPhase.items).toEqual([+ { price: 'price_base_year', quantity: 7 },+ { price: 'price_credit_year', quantity: 1 },+ ]);+ expect(toUpdateNextPhase.start_date).toBe(PERIOD_END);+ });++ it('ends the current phase at the period boundary when its prices are unchanged', () => {+ const { toUpdateCurrentPhase } = buildSchedulePhasesUpdate({+ currentPhase,+ nextPhase: undefined,+ productKeyByPriceId,+ toUpdateCurrentPrices: undefined,+ toUpdateNextPrices,+ subscriptionCurrentPeriodEnd: PERIOD_END,+ });++ expect(toUpdateCurrentPhase.end_date).toBe(PERIOD_END);+ expect(toUpdateCurrentPhase.items).toEqual(currentPhase.items);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-subscription-items-update.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-subscription-items-update.util.spec.tsnew file mode 100644index 00000000000..a73f8c55c9d--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-subscription-items-update.util.spec.ts@@ -0,0 +1,75 @@+/* @license Enterprise */++import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { buildSubscriptionItemsUpdate } from 'src/engine/core-modules/billing/utils/build-subscription-items-update.util';++const toUpdatePrices = {+ baseProductPriceId: 'price_base_year',+ seats: 7,+ resourceCreditPriceId: 'price_credits_year_1200',+};++const baseItem = {+ stripeSubscriptionItemId: 'si_base',+ stripePriceId: 'price_base_month',+ quantity: 3,+ billingProduct: {+ metadata: { productKey: BillingProductKey.BASE_PRODUCT },+ },+};++const creditItem = {+ stripeSubscriptionItemId: 'si_credit',+ stripePriceId: 'price_credits_month_100',+ quantity: 1,+ billingProduct: {+ metadata: { productKey: BillingProductKey.RESOURCE_CREDIT },+ },+};++describe('buildSubscriptionItemsUpdate', () => {+ it('leaves an item it does not manage out of the payload, so Stripe keeps it as is', () => {+ const items = buildSubscriptionItemsUpdate({+ billingSubscriptionItems: [+ baseItem,+ creditItem,+ {+ stripeSubscriptionItemId: 'si_add_on',+ billingProduct: null,+ },+ ],+ toUpdatePrices,+ });++ expect(items).toEqual([+ { id: 'si_base', price: 'price_base_year', quantity: 7 },+ { id: 'si_credit', price: 'price_credits_year_1200', quantity: 1 },+ ]);+ });++ it('rewrites the base and credit items whatever their position', () => {+ const items = buildSubscriptionItemsUpdate({+ billingSubscriptionItems: [creditItem, baseItem],+ toUpdatePrices,+ });++ expect(items).toEqual([+ { id: 'si_credit', price: 'price_credits_year_1200', quantity: 1 },+ { id: 'si_base', price: 'price_base_year', quantity: 7 },+ ]);+ });++ it('leaves out an item whose product the catalog cannot classify', () => {+ const items = buildSubscriptionItemsUpdate({+ billingSubscriptionItems: [+ baseItem,+ { stripeSubscriptionItemId: 'si_metered', billingProduct: null },+ ],+ toUpdatePrices,+ });++ expect(items).toEqual([+ { id: 'si_base', price: 'price_base_year', quantity: 7 },+ ]);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-licensed-billing-subscription-item-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-licensed-billing-subscription-item-or-throw.util.spec.tsdeleted file mode 100644index 8945fbb6a92..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-licensed-billing-subscription-item-or-throw.util.spec.ts+++ /dev/null@@ -1,97 +0,0 @@-import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import { BillingUsageType } from 'src/engine/core-modules/billing/enums/billing-usage-type.enum';-import { getCurrentLicensedBillingSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-licensed-billing-subscription-item-or-throw.util';--describe('getCurrentLicensedBillingSubscriptionItemOrThrow', () => {- it('returns the licensed billing subscription item when found', () => {- const licensedItem = {- id: 'item_licensed',- quantity: 5,- billingProduct: {- metadata: {- priceUsageBased: BillingUsageType.LICENSED,- },- },- };-- const meteredItem = {- id: 'item_metered',- quantity: null,- billingProduct: {- metadata: {- priceUsageBased: BillingUsageType.METERED,- },- },- };-- const billingSubscription = {- billingSubscriptionItems: [meteredItem, licensedItem],- } as unknown as BillingSubscriptionEntity;-- const result =- getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription);-- expect(result).toBe(licensedItem);- });-- it('returns the first licensed item when multiple licensed items exist', () => {- const firstLicensedItem = {- id: 'item_licensed_1',- quantity: 5,- billingProduct: {- metadata: {- priceUsageBased: BillingUsageType.LICENSED,- },- },- };-- const secondLicensedItem = {- id: 'item_licensed_2',- quantity: 10,- billingProduct: {- metadata: {- priceUsageBased: BillingUsageType.LICENSED,- },- },- };-- const billingSubscription = {- billingSubscriptionItems: [firstLicensedItem, secondLicensedItem],- } as unknown as BillingSubscriptionEntity;-- const result =- getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription);-- expect(result).toBe(firstLicensedItem);- });-- it('throws when no licensed billing subscription item is found', () => {- const meteredItem = {- id: 'item_metered',- quantity: null,- billingProduct: {- metadata: {- priceUsageBased: BillingUsageType.METERED,- },- },- };-- const billingSubscription = {- billingSubscriptionItems: [meteredItem],- } as unknown as BillingSubscriptionEntity;-- expect(() =>- getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription),- ).toThrow();- });-- it('throws when subscription has no items', () => {- const billingSubscription = {- billingSubscriptionItems: [],- } as unknown as BillingSubscriptionEntity;-- expect(() =>- getCurrentLicensedBillingSubscriptionItemOrThrow(billingSubscription),- ).toThrow();- });-});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-metered-billing-subscription-item-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-metered-billing-subscription-item-or-throw.util.spec.tsdeleted file mode 100644index 68141e98279..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-metered-billing-subscription-item-or-throw.util.spec.ts+++ /dev/null@@ -1,56 +0,0 @@-import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import { BillingUsageType } from 'src/engine/core-modules/billing/enums/billing-usage-type.enum';-import { getCurrentMeteredBillingSubscriptionItemOrThrow } from 'src/engine/core-modules/billing/utils/get-metered-billing-subscription-item-or-throw.util';--describe('getCurrentMeteredBillingSubscriptionItemOrThrow', () => {- it('returns the metered billing subscription item when found', () => {- const licensedItem = {- id: 'item_licensed',- quantity: 5,- billingProduct: {- metadata: {- priceUsageBased: BillingUsageType.LICENSED,- },- },- };-- const meteredItem = {- id: 'item_metered',- quantity: null,- billingProduct: {- metadata: {- priceUsageBased: BillingUsageType.METERED,- },- },- };-- const billingSubscription = {- billingSubscriptionItems: [licensedItem, meteredItem],- } as unknown as BillingSubscriptionEntity;-- const result =- getCurrentMeteredBillingSubscriptionItemOrThrow(billingSubscription);-- expect(result).toBe(meteredItem);- });-- it('throws when no metered billing subscription item is found', () => {- const licensedItem = {- id: 'item_licensed',- quantity: 5,- billingProduct: {- metadata: {- priceUsageBased: BillingUsageType.LICENSED,- },- },- };-- const billingSubscription = {- billingSubscriptionItems: [licensedItem],- } as unknown as BillingSubscriptionEntity;-- expect(() =>- getCurrentMeteredBillingSubscriptionItemOrThrow(billingSubscription),- ).toThrow();- });-});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-subscription-prices-from-schedule-phase.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-subscription-prices-from-schedule-phase.util.spec.tsdeleted file mode 100644index 21a54729808..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/get-subscription-prices-from-schedule-phase.util.spec.ts+++ /dev/null@@ -1,69 +0,0 @@-import { type Stripe } from 'stripe';--import { getSubscriptionPricesFromSchedulePhase } from 'src/engine/core-modules/billing/utils/get-subscription-prices-from-schedule-phase.util';--describe('getSubscriptionPricesFromSchedulePhase', () => {- it('returns licensed price id, metered price id, and seats from phase with string prices', () => {- const phase = {- items: [- { price: 'price_licensed_123', quantity: 10 },- { price: 'price_metered_456', quantity: undefined },- ],- } as unknown as Stripe.SubscriptionSchedule.Phase;-- const result = getSubscriptionPricesFromSchedulePhase(phase);-- expect(result).toEqual({- licensedPriceId: 'price_licensed_123',- meteredPriceId: 'price_metered_456',- seats: 10,- });- });-- it('returns licensed price id, metered price id, and seats from phase with object prices', () => {- const phase = {- items: [- { price: { id: 'price_licensed_abc' }, quantity: 5 },- { price: { id: 'price_metered_def' }, quantity: undefined },- ],- } as unknown as Stripe.SubscriptionSchedule.Phase;-- const result = getSubscriptionPricesFromSchedulePhase(phase);-- expect(result).toEqual({- licensedPriceId: 'price_licensed_abc',- meteredPriceId: 'price_metered_def',- seats: 5,- });- });-- it('throws when no licensed item is found', () => {- const phase = {- items: [- { price: 'price_metered_1', quantity: undefined },- { price: 'price_metered_2', quantity: undefined },- ],- } as unknown as Stripe.SubscriptionSchedule.Phase;-- expect(() => getSubscriptionPricesFromSchedulePhase(phase)).toThrow();- });-- it('throws when no metered item is found', () => {- const phase = {- items: [- { price: 'price_licensed_1', quantity: 5 },- { price: 'price_licensed_2', quantity: 10 },- ],- } as unknown as Stripe.SubscriptionSchedule.Phase;-- expect(() => getSubscriptionPricesFromSchedulePhase(phase)).toThrow();- });-- it('throws when phase has no items', () => {- const phase = {- items: [],- } as unknown as Stripe.SubscriptionSchedule.Phase;-- expect(() => getSubscriptionPricesFromSchedulePhase(phase)).toThrow();- });-});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-resource-credit-price-for-subscription.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-resource-credit-price-for-subscription.util.spec.tsnew file mode 100644index 00000000000..169b618d821--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-resource-credit-price-for-subscription.util.spec.ts@@ -0,0 +1,61 @@+/* @license Enterprise */++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 { isResourceCreditPriceForSubscription } from 'src/engine/core-modules/billing/utils/is-resource-credit-price-for-subscription.util';++const buildPrice = (+ interval: SubscriptionInterval,+ planKey: BillingPlanKey | undefined,+) => ({+ interval,+ billingProduct: { metadata: { planKey } },+});++describe('isResourceCreditPriceForSubscription', () => {+ it('accepts a price on the same interval and plan', () => {+ expect(+ isResourceCreditPriceForSubscription({+ billingPrice: buildPrice(+ SubscriptionInterval.Month,+ BillingPlanKey.PRO,+ ),+ interval: SubscriptionInterval.Month,+ planKey: BillingPlanKey.PRO,+ }),+ ).toBe(true);+ });++ it('refuses a price from the other interval', () => {+ expect(+ isResourceCreditPriceForSubscription({+ billingPrice: buildPrice(SubscriptionInterval.Year, BillingPlanKey.PRO),+ interval: SubscriptionInterval.Month,+ planKey: BillingPlanKey.PRO,+ }),+ ).toBe(false);+ });++ it('refuses a price from another plan', () => {+ expect(+ isResourceCreditPriceForSubscription({+ billingPrice: buildPrice(+ SubscriptionInterval.Month,+ BillingPlanKey.ENTERPRISE,+ ),+ interval: SubscriptionInterval.Month,+ planKey: BillingPlanKey.PRO,+ }),+ ).toBe(false);+ });++ it('refuses a price whose product carries no plan', () => {+ expect(+ isResourceCreditPriceForSubscription({+ billingPrice: { interval: SubscriptionInterval.Month },+ interval: SubscriptionInterval.Month,+ planKey: BillingPlanKey.PRO,+ }),+ ).toBe(false);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-same-phase-signature.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-same-phase-signature.util.spec.tsnew file mode 100644index 00000000000..2703a253aa5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-same-phase-signature.util.spec.ts@@ -0,0 +1,73 @@+/* @license Enterprise */++import { isSamePhaseSignature } from 'src/engine/core-modules/billing/utils/is-same-phase-signature.util';++const BASE_PRICE_ID = 'price_base_month';+const CREDIT_PRICE_ID = 'price_credit_month';+const ADD_ON_PRICE_ID = 'price_add_on_month';++const buildPhase = (items: Array<{ price: string; quantity?: number }>) => ({+ start_date: 1_700_000_000,+ proration_behavior: 'none' as const,+ items,+});++describe('isSamePhaseSignature', () => {+ it('ignores item order', () => {+ expect(+ isSamePhaseSignature(+ buildPhase([+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ ]),+ buildPhase([+ { price: CREDIT_PRICE_ID, quantity: 1 },+ { price: BASE_PRICE_ID, quantity: 3 },+ ]),+ ),+ ).toBe(true);+ });++ it('separates two phases that differ only by an extra item', () => {+ expect(+ isSamePhaseSignature(+ buildPhase([+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ ]),+ buildPhase([+ { price: BASE_PRICE_ID, quantity: 3 },+ { price: CREDIT_PRICE_ID, quantity: 1 },+ { price: ADD_ON_PRICE_ID, quantity: 1 },+ ]),+ ),+ ).toBe(false);+ });++ it('separates two phases that differ by a quantity', () => {+ expect(+ isSamePhaseSignature(+ buildPhase([{ price: BASE_PRICE_ID, quantity: 3 }]),+ buildPhase([{ price: BASE_PRICE_ID, quantity: 4 }]),+ ),+ ).toBe(false);+ });++ it('separates two phases that differ by a price', () => {+ expect(+ isSamePhaseSignature(+ buildPhase([{ price: BASE_PRICE_ID, quantity: 3 }]),+ buildPhase([{ price: 'price_base_year', quantity: 3 }]),+ ),+ ).toBe(false);+ });++ it('separates an item carrying no quantity from the same item carrying one', () => {+ expect(+ isSamePhaseSignature(+ buildPhase([{ price: BASE_PRICE_ID }]),+ buildPhase([{ price: BASE_PRICE_ID, quantity: 1 }]),+ ),+ ).toBe(false);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-managed-item-price.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-managed-item-price.util.spec.tsnew file mode 100644index 00000000000..85e42ae6541--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-managed-item-price.util.spec.ts@@ -0,0 +1,36 @@+/* @license Enterprise */++import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { resolveManagedItemPrice } from 'src/engine/core-modules/billing/utils/resolve-managed-item-price.util';++const toUpdatePrices = {+ baseProductPriceId: 'price_base_year',+ seats: 7,+ resourceCreditPriceId: 'price_credit_year',+};++describe('resolveManagedItemPrice', () => {+ it('prices the base product at the seat count', () => {+ expect(+ resolveManagedItemPrice({+ productKey: BillingProductKey.BASE_PRODUCT,+ toUpdatePrices,+ }),+ ).toEqual({ price: 'price_base_year', quantity: 7 });+ });++ it('prices the resource credit at a single unit', () => {+ expect(+ resolveManagedItemPrice({+ productKey: BillingProductKey.RESOURCE_CREDIT,+ toUpdatePrices,+ }),+ ).toEqual({ price: 'price_credit_year', quantity: 1 });+ });++ it('leaves an unresolved product key unmanaged', () => {+ expect(+ resolveManagedItemPrice({ productKey: undefined, toUpdatePrices }),+ ).toBeUndefined();+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/to-phase-update-params.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/to-phase-update-params.util.spec.tsnew file mode 100644index 00000000000..4b2afbed1b4--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/to-phase-update-params.util.spec.ts@@ -0,0 +1,73 @@+/* @license Enterprise */++import type Stripe from 'stripe';++import { toPhaseUpdateParams } from 'src/engine/core-modules/billing/utils/to-phase-update-params.util';++const buildPhase = (+ phase: Partial<+ Omit<Stripe.SubscriptionSchedule.Phase, 'end_date'> & {+ end_date: number | null;+ }+ >,+): Stripe.SubscriptionSchedule.Phase =>+ ({+ start_date: 1_700_000_000,+ end_date: 1_800_000_000,+ items: [],+ ...phase,+ }) as Stripe.SubscriptionSchedule.Phase;++describe('toPhaseUpdateParams', () => {+ it('normalizes a price object reference to its id', () => {+ const phase = toPhaseUpdateParams(+ buildPhase({+ items: [+ { price: { id: 'price_base' }, quantity: 3 },+ ] as unknown as Stripe.SubscriptionSchedule.Phase['items'],+ }),+ );++ expect(phase.items).toEqual([{ price: 'price_base', quantity: 3 }]);+ });++ it('carries a null quantity through as undefined', () => {+ const phase = toPhaseUpdateParams(+ buildPhase({+ items: [+ { price: 'price_metered', quantity: null },+ ] as unknown as Stripe.SubscriptionSchedule.Phase['items'],+ }),+ );++ expect(phase.items).toEqual([+ { price: 'price_metered', quantity: undefined },+ ]);+ });++ it('omits billing thresholds when the phase carries none', () => {+ const phase = toPhaseUpdateParams(buildPhase({ billing_thresholds: null }));++ expect('billing_thresholds' in phase).toBe(false);+ });++ it('keeps billing thresholds when the phase carries them', () => {+ const billingThresholds = {+ amount_gte: 1000,+ reset_billing_cycle_anchor: null,+ } as Stripe.SubscriptionSchedule.Phase['billing_thresholds'];++ const phase = toPhaseUpdateParams(+ buildPhase({ billing_thresholds: billingThresholds }),+ );++ expect(phase.billing_thresholds).toEqual(billingThresholds);+ expect(phase.proration_behavior).toBe('none');+ });++ it('turns a null end date into undefined', () => {+ const phase = toPhaseUpdateParams(buildPhase({ end_date: null }));++ expect(phase.end_date).toBeUndefined();+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-phase-update-params-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-phase-update-params-or-throw.util.tsnew file mode 100644index 00000000000..e1b1093655e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-phase-update-params-or-throw.util.ts@@ -0,0 +1,68 @@+/* @license Enterprise */++import { msg } from '@lingui/core/macro';+import { isDefined } from 'twenty-shared/utils';++import type Stripe from 'stripe';++import {+ BillingException,+ BillingExceptionCode,+} from 'src/engine/core-modules/billing/billing.exception';+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { type SubscriptionStripePrices } from 'src/engine/core-modules/billing/types/subscription-stripe-prices.type';+import { resolveManagedItemPrice } from 'src/engine/core-modules/billing/utils/resolve-managed-item-price.util';++export const buildPhaseUpdateParamsOrThrow = ({+ currentPhase,+ productKeyByPriceId,+ toUpdatePrices,+ startDate,+ endDate,+}: {+ currentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase;+ productKeyByPriceId: Map<string, BillingProductKey>;+ toUpdatePrices: SubscriptionStripePrices;+ startDate: Stripe.SubscriptionScheduleUpdateParams.Phase['start_date'];+ endDate: number | undefined;+}): Stripe.SubscriptionScheduleUpdateParams.Phase => {+ const currentItems = currentPhase.items ?? [];++ const getProductKey = (price: string | undefined) =>+ isDefined(price) ? productKeyByPriceId.get(price) : undefined;++ const resolvedProductKeys = currentItems.map(({ price }) =>+ getProductKey(price),+ );++ const assertPhaseHolds = (productKey: BillingProductKey, label: string) => {+ if (resolvedProductKeys.includes(productKey)) {+ return;+ }++ throw new BillingException(+ `Subscription schedule phase has no ${label} item`,+ BillingExceptionCode.BILLING_SUBSCRIPTION_INVALID,+ {+ userFriendlyMessage: msg`Your billing subscription is corrupted. Please contact support.`,+ },+ );+ };++ assertPhaseHolds(BillingProductKey.BASE_PRODUCT, 'base product');+ assertPhaseHolds(BillingProductKey.RESOURCE_CREDIT, 'resource credit');++ return {+ start_date: startDate,+ ...(isDefined(endDate) ? { end_date: endDate } : {}),+ proration_behavior: 'none',+ items: currentItems.map((item, index) => {+ const managedPrice = resolveManagedItemPrice({+ productKey: resolvedProductKeys[index],+ toUpdatePrices,+ });++ return managedPrice ?? item;+ }),+ };+};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-schedule-phases-update.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-schedule-phases-update.util.tsnew file mode 100644index 00000000000..da357ad4cca--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-schedule-phases-update.util.ts@@ -0,0 +1,45 @@+/* @license Enterprise */++import { isDefined } from 'twenty-shared/utils';++import type Stripe from 'stripe';++import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { type SubscriptionStripePrices } from 'src/engine/core-modules/billing/types/subscription-stripe-prices.type';+import { buildPhaseUpdateParamsOrThrow } from 'src/engine/core-modules/billing/utils/build-phase-update-params-or-throw.util';++export const buildSchedulePhasesUpdate = ({+ currentPhase,+ nextPhase,+ productKeyByPriceId,+ toUpdateCurrentPrices,+ toUpdateNextPrices,+ subscriptionCurrentPeriodEnd,+}: {+ currentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase;+ nextPhase: Stripe.SubscriptionScheduleUpdateParams.Phase | undefined;+ productKeyByPriceId: Map<string, BillingProductKey>;+ toUpdateCurrentPrices: SubscriptionStripePrices | undefined;+ toUpdateNextPrices: SubscriptionStripePrices;+ subscriptionCurrentPeriodEnd: number;+}): {+ toUpdateCurrentPhase: Stripe.SubscriptionScheduleUpdateParams.Phase;+ toUpdateNextPhase: Stripe.SubscriptionScheduleUpdateParams.Phase;+} => ({+ toUpdateCurrentPhase: isDefined(toUpdateCurrentPrices)+ ? buildPhaseUpdateParamsOrThrow({+ currentPhase,+ productKeyByPriceId,+ toUpdatePrices: toUpdateCurrentPrices,+ endDate: subscriptionCurrentPeriodEnd,+ startDate: currentPhase.start_date,+ })+ : { ...currentPhase, end_date: subscriptionCurrentPeriodEnd },+ toUpdateNextPhase: buildPhaseUpdateParamsOrThrow({+ currentPhase: nextPhase ?? currentPhase,+ productKeyByPriceId,+ toUpdatePrices: toUpdateNextPrices,+ startDate: subscriptionCurrentPeriodEnd,+ endDate: undefined,+ }),+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-subscription-items-update.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-subscription-items-update.util.tsnew file mode 100644index 00000000000..f960ee4b74b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-subscription-items-update.util.ts@@ -0,0 +1,39 @@+/* @license Enterprise */++import { isDefined } from 'twenty-shared/utils';++import type Stripe from 'stripe';++import { type BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';+import { type BillingProductMetadata } from 'src/engine/core-modules/billing/types/billing-product-metadata.type';+import { type SubscriptionStripePrices } from 'src/engine/core-modules/billing/types/subscription-stripe-prices.type';+import { resolveManagedItemPrice } from 'src/engine/core-modules/billing/utils/resolve-managed-item-price.util';++type SubscriptionItemToUpdate = Pick<+ BillingSubscriptionItemEntity,+ 'stripeSubscriptionItemId'+> & {+ billingProduct?: {+ metadata?: Pick<BillingProductMetadata, 'productKey'> | null;+ } | null;+};++export const buildSubscriptionItemsUpdate = ({+ billingSubscriptionItems,+ toUpdatePrices,+}: {+ billingSubscriptionItems: SubscriptionItemToUpdate[];+ toUpdatePrices: SubscriptionStripePrices;+}): Stripe.SubscriptionUpdateParams.Item[] =>+ billingSubscriptionItems.flatMap(+ ({ stripeSubscriptionItemId, billingProduct }) => {+ const managedPrice = resolveManagedItemPrice({+ productKey: billingProduct?.metadata?.productKey,+ toUpdatePrices,+ });++ return isDefined(managedPrice)+ ? [{ id: stripeSubscriptionItemId, ...managedPrice }]+ : [];+ },+ );diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-base-product-subscription-item-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-base-product-subscription-item-or-throw.util.tsindex 3959c7721d1..cec2f89898f 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/get-base-product-subscription-item-or-throw.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/get-base-product-subscription-item-or-throw.util.ts@@ -4,16 +4,14 @@ import { findOrThrow } from 'twenty-shared/utils';import { type 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 { type LicensedBillingSubscriptionItem } from 'src/engine/core-modules/billing/types/billing-subscription-item.type';+import { type BaseProductSubscriptionItem } from 'src/engine/core-modules/billing/types/base-product-subscription-item.type';-// V2 counterpart of get-licensed-billing-subscription-item-or-throw.util.ts-// Identifies the base plan item by productKey === BASE_PRODUCT (not quantity != null)export const getBaseProductSubscriptionItemOrThrow = (billingSubscription: BillingSubscriptionEntity,-): LicensedBillingSubscriptionItem => {+): BaseProductSubscriptionItem => {return findOrThrow(billingSubscription.billingSubscriptionItems,({ billingProduct }) =>- billingProduct.metadata.productKey === BillingProductKey.BASE_PRODUCT,- ) as LicensedBillingSubscriptionItem;+ billingProduct?.metadata?.productKey === BillingProductKey.BASE_PRODUCT,+ ) as BaseProductSubscriptionItem;};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-licensed-billing-subscription-item-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-licensed-billing-subscription-item-or-throw.util.tsdeleted file mode 100644index f65f32abea1..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/utils/get-licensed-billing-subscription-item-or-throw.util.ts+++ /dev/null@@ -1,15 +0,0 @@-import { findOrThrow } from 'twenty-shared/utils';--import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import { BillingUsageType } from 'src/engine/core-modules/billing/enums/billing-usage-type.enum';-import { type LicensedBillingSubscriptionItem } from 'src/engine/core-modules/billing/types/billing-subscription-item.type';--export const getCurrentLicensedBillingSubscriptionItemOrThrow = (- billingSubscription: BillingSubscriptionEntity,-) => {- return findOrThrow(- billingSubscription.billingSubscriptionItems,- ({ billingProduct }) =>- billingProduct.metadata.priceUsageBased === BillingUsageType.LICENSED,- ) as LicensedBillingSubscriptionItem;-};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-metered-billing-subscription-item-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-metered-billing-subscription-item-or-throw.util.tsdeleted file mode 100644index aed699ff8a9..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/utils/get-metered-billing-subscription-item-or-throw.util.ts+++ /dev/null@@ -1,15 +0,0 @@-import { findOrThrow } from 'twenty-shared/utils';--import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import { BillingUsageType } from 'src/engine/core-modules/billing/enums/billing-usage-type.enum';-import { type MeteredBillingSubscriptionItem } from 'src/engine/core-modules/billing/types/billing-subscription-item.type';--export const getCurrentMeteredBillingSubscriptionItemOrThrow = (- billingSubscription: BillingSubscriptionEntity,-) => {- return findOrThrow(- billingSubscription.billingSubscriptionItems,- ({ billingProduct }) =>- billingProduct.metadata.priceUsageBased === BillingUsageType.METERED,- ) as MeteredBillingSubscriptionItem;-};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-resource-credit-subscription-item-or-throw.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-resource-credit-subscription-item-or-throw.util.tsindex 2bb1c7a2478..1019e95a9e7 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/get-resource-credit-subscription-item-or-throw.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/get-resource-credit-subscription-item-or-throw.util.ts@@ -5,14 +5,13 @@ import { findOrThrow } from 'twenty-shared/utils';import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';-// V2 counterpart of get-metered-billing-subscription-item-or-throw.util.ts-// Identifies the credit item by productKey === RESOURCE_CREDIT (not quantity == null)export const getCurrentResourceCreditSubscriptionItemOrThrow = (billingSubscription: BillingSubscriptionEntity,) => {return findOrThrow(billingSubscription.billingSubscriptionItems,({ billingProduct }) =>- billingProduct.metadata.productKey === BillingProductKey.RESOURCE_CREDIT,+ billingProduct?.metadata?.productKey ===+ BillingProductKey.RESOURCE_CREDIT,);};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-subscription-prices-from-schedule-phase.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-subscription-prices-from-schedule-phase.util.tsdeleted file mode 100644index 7eea42e8a8a..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/utils/get-subscription-prices-from-schedule-phase.util.ts+++ /dev/null@@ -1,22 +0,0 @@-import { type Stripe } from 'stripe';-import { assertIsDefinedOrThrow, findOrThrow } from 'twenty-shared/utils';--import { normalizePriceRef } from 'src/engine/core-modules/billing/utils/normalize-price-ref.utils';--export const getSubscriptionPricesFromSchedulePhase = (- phase: Stripe.SubscriptionSchedule.Phase,-) => {- const licensedItem = findOrThrow(- phase.items,- (item) => item.quantity != null,- );-- assertIsDefinedOrThrow(licensedItem.quantity);- const meteredItem = findOrThrow(phase.items, (item) => item.quantity == null);-- return {- licensedPriceId: normalizePriceRef(licensedItem.price),- meteredPriceId: normalizePriceRef(meteredItem.price),- seats: licensedItem.quantity,- };-};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/is-resource-credit-price-for-subscription.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/is-resource-credit-price-for-subscription.util.tsnew file mode 100644index 00000000000..e3fd974478a--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/is-resource-credit-price-for-subscription.util.ts@@ -0,0 +1,21 @@+/* @license Enterprise */++import { type BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';+import { type SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';++type ResourceCreditPriceForSubscription = {+ interval: SubscriptionInterval;+ billingProduct?: { metadata?: { planKey?: BillingPlanKey } | null } | null;+};++export const isResourceCreditPriceForSubscription = ({+ billingPrice,+ interval,+ planKey,+}: {+ billingPrice: ResourceCreditPriceForSubscription;+ interval: SubscriptionInterval;+ planKey: BillingPlanKey | undefined;+}): boolean =>+ billingPrice.interval === interval &&+ billingPrice.billingProduct?.metadata?.planKey === planKey;diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/is-same-phase-signature.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/is-same-phase-signature.util.tsnew file mode 100644index 00000000000..ed770b1255a--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/is-same-phase-signature.util.ts@@ -0,0 +1,20 @@+/* @license Enterprise */++import type Stripe from 'stripe';++const buildItemSignature = (+ phase: Stripe.SubscriptionScheduleUpdateParams.Phase,+): string =>+ JSON.stringify(+ (phase.items ?? [])+ .map(({ price, quantity }): [string, number | undefined] => [+ price ?? '',+ quantity,+ ])+ .sort(([priceA], [priceB]) => priceA.localeCompare(priceB)),+ );++export const isSamePhaseSignature = (+ a: Stripe.SubscriptionScheduleUpdateParams.Phase,+ b: Stripe.SubscriptionScheduleUpdateParams.Phase,+): boolean => buildItemSignature(a) === buildItemSignature(b);diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-managed-item-price.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-managed-item-price.util.tsnew file mode 100644index 00000000000..eed26ad55ea--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-managed-item-price.util.ts@@ -0,0 +1,24 @@+/* @license Enterprise */++import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { type SubscriptionStripePrices } from 'src/engine/core-modules/billing/types/subscription-stripe-prices.type';++export const resolveManagedItemPrice = ({+ productKey,+ toUpdatePrices,+}: {+ productKey: BillingProductKey | undefined | null;+ toUpdatePrices: SubscriptionStripePrices;+}): { price: string; quantity: number } | undefined => {+ switch (productKey) {+ case BillingProductKey.BASE_PRODUCT:+ return {+ price: toUpdatePrices.baseProductPriceId,+ quantity: toUpdatePrices.seats,+ };+ case BillingProductKey.RESOURCE_CREDIT:+ return { price: toUpdatePrices.resourceCreditPriceId, quantity: 1 };+ default:+ return undefined;+ }+};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/to-phase-update-params.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/to-phase-update-params.util.tsnew file mode 100644index 00000000000..0408ed3519b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/to-phase-update-params.util.ts@@ -0,0 +1,23 @@+/* @license Enterprise */++import { isDefined } from 'twenty-shared/utils';++import type Stripe from 'stripe';++import { normalizePriceRef } from 'src/engine/core-modules/billing/utils/normalize-price-ref.utils';++export const toPhaseUpdateParams = (+ phase: Stripe.SubscriptionSchedule.Phase,+): Stripe.SubscriptionScheduleUpdateParams.Phase =>+ ({+ start_date: phase.start_date,+ end_date: phase.end_date ?? undefined,+ items: (phase.items || []).map((item) => ({+ price: normalizePriceRef(item.price) as string,+ quantity: item.quantity ?? undefined,+ })),+ ...(isDefined(phase.billing_thresholds)+ ? { billing_thresholds: phase.billing_thresholds }+ : {}),+ proration_behavior: 'none',+ }) as Stripe.SubscriptionScheduleUpdateParams.Phase;