Skip to content

The open alternative to Salesforce, designed for AI.

fix(billing): skip the Stripe update when prices and seats are unchanged (#26907)

Etienne1fca18a8bb79
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.ts
index a237c955227..d665a9b5da6 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
@@ -76,8 +76,6 @@ const baseProductYear = buildPrice({
product: baseProduct,
});
-// The resource-credit product carries one price per credit package. This is the
-// shape that made the single-price-per-interval guard throw in production.
const creditMonthPackages = [50, 100, 200].map((creditAmount) =>
buildPrice({
stripePriceId: `price_credits_month_${creditAmount}`,
@@ -102,8 +100,6 @@ const allPrices = [
...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(baseProductMonth, baseProductYear);
resourceCreditProduct.billingPrices.push(
...creditMonthPackages,
@@ -146,9 +142,6 @@ describe('BillingSubscriptionUpdateService interval switch', () => {
BillingSubscriptionUpdateService,
{
provide: BillingPriceService,
- // The real service, so the package scaling runs rather than a canned
- // answer: a mocked helper would pass even if the caller stopped
- // scaling across the interval change.
useValue: new BillingPriceService(
noop as never,
billingPriceRepository as never,
@@ -212,9 +205,6 @@ describe('BillingSubscriptionUpdateService interval switch', () => {
});
it('switches interval on a product holding several packages at that interval', async () => {
- // The regression this pins: resolving the resource-credit item as "the one
- // billable price at the interval" throws here, because the product
- // legitimately holds three.
expect(
resourceCreditProduct.billingPrices.filter(
(price) => price.interval === SubscriptionInterval.Year,
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.ts
index 5c88cbaf3b0..e44e4c01a23 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
@@ -34,6 +34,7 @@ import {
type SubscriptionUpdate,
SubscriptionUpdateType,
} from 'src/engine/core-modules/billing/types/billing-subscription-update.type';
+import { computeImmediateSubscriptionUpdate } from 'src/engine/core-modules/billing/utils/compute-immediate-subscription-update.util';
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';
@@ -238,9 +239,18 @@ export class BillingSubscriptionUpdateService {
},
);
- const baseProductItem = getBaseProductSubscriptionItemOrThrow(subscription);
- const resourceCreditItem =
- getCurrentResourceCreditSubscriptionItemOrThrow(subscription);
+ const {
+ subscription: stripeSubscription,
+ schedule,
+ currentPhase,
+ nextPhase,
+ } = await this.stripeSubscriptionScheduleService.loadSubscriptionSchedule(
+ subscription.stripeSubscriptionId,
+ );
+
+ const currentPrices = await this.getSubscriptionPricesFromItems(
+ stripeSubscription.items.data,
+ );
const seats =
subscriptionUpdate.type === SubscriptionUpdateType.SEATS
@@ -249,18 +259,9 @@ export class BillingSubscriptionUpdateService {
const toUpdateCurrentPrices = await this.computeSubscriptionPricesUpdate(
subscriptionUpdate,
- {
- baseProductPriceId: baseProductItem.stripePriceId,
- resourceCreditPriceId: resourceCreditItem.stripePriceId,
- seats: seats > 0 ? seats : baseProductItem.quantity,
- },
+ { ...currentPrices, seats: seats > 0 ? seats : currentPrices.seats },
);
- const { schedule, currentPhase, nextPhase } =
- await this.stripeSubscriptionScheduleService.loadSubscriptionSchedule(
- subscription.stripeSubscriptionId,
- );
-
const shouldUpdateAtPeriodEnd =
await this.shouldUpdateAtSubscriptionPeriodEnd(
subscription,
@@ -287,8 +288,9 @@ export class BillingSubscriptionUpdateService {
assertIsDefinedOrThrow(nextPhase);
assertIsDefinedOrThrow(currentPhase);
- const nextPhasePrices =
- await this.getSubscriptionPricesFromSchedulePhase(nextPhase);
+ const nextPhasePrices = await this.getSubscriptionPricesFromItems(
+ nextPhase.items,
+ );
const toUpdateNextPrices = await this.computeSubscriptionPricesUpdate(
subscriptionUpdate,
@@ -307,34 +309,21 @@ export class BillingSubscriptionUpdateService {
});
}
} else {
- const subscriptionOptions = computeSubscriptionUpdateOptions(
+ const immediateSubscriptionUpdate = computeImmediateSubscriptionUpdate({
subscriptionUpdate,
- {
- currentSeats: baseProductItem.quantity,
- isTrialing: subscription.status === SubscriptionStatus.Trialing,
- },
- );
-
- if (
- subscriptionUpdate.type === SubscriptionUpdateType.RESOURCE_CREDIT_PRICE
- ) {
- assertIsDefinedOrThrow(resourceCreditItem);
- await this.createResourceCreditUpgradeInvoice({
- subscription,
- currentResourceCreditPriceId: resourceCreditItem.stripePriceId,
- newResourceCreditPriceId: subscriptionUpdate.newResourceCreditPriceId,
- });
- }
-
- await this.runSubscriptionUpdate({
- stripeSubscriptionId: subscription.stripeSubscriptionId,
- items: buildSubscriptionItemsUpdate({
- billingSubscriptionItems: subscription.billingSubscriptionItems,
- toUpdatePrices: toUpdateCurrentPrices,
- }),
- ...subscriptionOptions,
+ currentPrices,
+ toUpdatePrices: toUpdateCurrentPrices,
});
+ const updatedStripeSubscription = isDefined(immediateSubscriptionUpdate)
+ ? await this.applyImmediateSubscriptionUpdate({
+ subscription,
+ subscriptionUpdate: immediateSubscriptionUpdate,
+ currentPrices,
+ toUpdateCurrentPrices,
+ })
+ : undefined;
+
if (isDefined(nextPhase)) {
assertIsDefinedOrThrow(schedule);
const { currentPhase: refreshedCurrentPhase } =
@@ -344,8 +333,9 @@ export class BillingSubscriptionUpdateService {
assertIsDefinedOrThrow(refreshedCurrentPhase);
- const nextPhasePrices =
- await this.getSubscriptionPricesFromSchedulePhase(nextPhase);
+ const nextPhasePrices = await this.getSubscriptionPricesFromItems(
+ nextPhase.items,
+ );
const toUpdateNextPrices = await this.computeSubscriptionPricesUpdate(
subscriptionUpdate,
nextPhasePrices,
@@ -357,9 +347,9 @@ export class BillingSubscriptionUpdateService {
toUpdateCurrentPrices: undefined,
currentPhase: toPhaseUpdateParams(refreshedCurrentPhase),
nextPhase: toPhaseUpdateParams(nextPhase),
- subscriptionCurrentPeriodEnd: Math.floor(
- subscription.currentPeriodEnd.getTime() / 1000,
- ),
+ subscriptionCurrentPeriodEnd:
+ updatedStripeSubscription?.items.data[0].current_period_end ??
+ Math.floor(subscription.currentPeriodEnd.getTime() / 1000),
});
}
}
@@ -452,10 +442,10 @@ export class BillingSubscriptionUpdateService {
);
}
- private async getSubscriptionPricesFromSchedulePhase(
- phase: Stripe.SubscriptionSchedule.Phase,
+ private async getSubscriptionPricesFromItems(
+ items: { price: string | { id: string }; quantity?: number }[],
): Promise<SubscriptionStripePrices> {
- const phaseItemPriceIds = phase.items.map((item) =>
+ const phaseItemPriceIds = items.map((item) =>
normalizePriceRef(item.price),
);
@@ -473,7 +463,7 @@ export class BillingSubscriptionUpdateService {
assertIsDefinedOrThrow(basePlanPrice);
const basePlanPhaseItem = findOrThrow(
- phase.items,
+ items,
(item) => normalizePriceRef(item.price) === basePlanPrice.stripePriceId,
);
@@ -494,26 +484,45 @@ export class BillingSubscriptionUpdateService {
};
}
- private async runSubscriptionUpdate({
- stripeSubscriptionId,
- items,
- anchor,
- proration,
- metadata,
+ private async applyImmediateSubscriptionUpdate({
+ subscription,
+ subscriptionUpdate,
+ currentPrices,
+ toUpdateCurrentPrices,
}: {
- stripeSubscriptionId: string;
- items: Stripe.SubscriptionUpdateParams.Item[];
- anchor?: Stripe.SubscriptionUpdateParams.BillingCycleAnchor;
- proration?: Stripe.SubscriptionUpdateParams.ProrationBehavior;
- metadata?: Record<string, string>;
- }) {
+ subscription: BillingSubscriptionEntity;
+ subscriptionUpdate: SubscriptionUpdate;
+ currentPrices: SubscriptionStripePrices;
+ toUpdateCurrentPrices: SubscriptionStripePrices;
+ }): Promise<Stripe.Subscription> {
+ if (
+ subscriptionUpdate.type === SubscriptionUpdateType.RESOURCE_CREDIT_PRICE
+ ) {
+ await this.createResourceCreditUpgradeInvoice({
+ subscription,
+ currentResourceCreditPriceId: currentPrices.resourceCreditPriceId,
+ newResourceCreditPriceId: subscriptionUpdate.newResourceCreditPriceId,
+ });
+ }
+
+ const { proration, anchor, metadata } = computeSubscriptionUpdateOptions(
+ subscriptionUpdate,
+ {
+ currentSeats: currentPrices.seats,
+ isTrialing: subscription.status === SubscriptionStatus.Trialing,
+ },
+ );
+
return await this.stripeSubscriptionService.updateSubscription(
- stripeSubscriptionId,
+ subscription.stripeSubscriptionId,
{
- items,
- ...(anchor ? { billing_cycle_anchor: anchor } : {}),
- ...(proration ? { proration_behavior: proration } : {}),
- ...(metadata ? { metadata } : {}),
+ items: buildSubscriptionItemsUpdate({
+ billingSubscriptionItems: subscription.billingSubscriptionItems,
+ toUpdatePrices: toUpdateCurrentPrices,
+ }),
+ proration_behavior: proration,
+ billing_cycle_anchor: anchor,
+ metadata,
},
);
}
@@ -813,8 +822,6 @@ export class BillingSubscriptionUpdateService {
return currentPrices;
}
- // 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 targetBaseProductPrice = findProductPriceForIntervalOrThrow(
currentBillingProduct,
newInterval,
@@ -830,8 +837,6 @@ export class BillingSubscriptionUpdateService {
currentResourceCreditPrice,
);
- // Resource credit has one price per package, not per interval, so match the
- // equivalent package scaled for the interval change.
const targetResourceCreditPrice =
await this.billingPriceService.findEquivalentResourceCreditPrice({
referencePrice: currentResourceCreditPrice,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service.ts
index a0c2acf24e3..c65f79c622e 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service.ts
@@ -120,7 +120,7 @@ export class StripeSubscriptionScheduleService {
await this.getSubscriptionWithSchedule(stripeSubscriptionId);
if (!isDefined(subscriptionWithSchedule.schedule)) {
- return {};
+ return { subscription: subscriptionWithSchedule };
}
const { currentPhase, nextPhase } = this.getPhases(
@@ -132,10 +132,11 @@ export class StripeSubscriptionScheduleService {
subscriptionWithSchedule.schedule.id,
);
- return {};
+ return { subscription: subscriptionWithSchedule };
}
return {
+ subscription: subscriptionWithSchedule,
schedule: subscriptionWithSchedule.schedule,
currentPhase,
nextPhase,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-immediate-subscription-update.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-immediate-subscription-update.util.spec.ts
new file mode 100644
index 00000000000..ca214635721
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-immediate-subscription-update.util.spec.ts
@@ -0,0 +1,78 @@
+/* @license Enterprise */
+
+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
+import { SubscriptionUpdateType } from 'src/engine/core-modules/billing/types/billing-subscription-update.type';
+import { computeImmediateSubscriptionUpdate } from 'src/engine/core-modules/billing/utils/compute-immediate-subscription-update.util';
+
+const subscriptionUpdate = {
+ type: SubscriptionUpdateType.INTERVAL,
+ newInterval: SubscriptionInterval.Year,
+} as const;
+
+const currentPrices = {
+ baseProductPriceId: 'price_base_year',
+ seats: 3,
+ resourceCreditPriceId: 'price_credit_year',
+};
+
+describe('computeImmediateSubscriptionUpdate', () => {
+ it('returns undefined when prices and seats are unchanged', () => {
+ expect(
+ computeImmediateSubscriptionUpdate({
+ subscriptionUpdate,
+ currentPrices,
+ toUpdatePrices: currentPrices,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('returns the requested update when the base price changes', () => {
+ expect(
+ computeImmediateSubscriptionUpdate({
+ subscriptionUpdate,
+ currentPrices,
+ toUpdatePrices: {
+ ...currentPrices,
+ baseProductPriceId: 'price_base_month',
+ },
+ }),
+ ).toBe(subscriptionUpdate);
+ });
+
+ it('returns the requested update when the resource credit price changes', () => {
+ expect(
+ computeImmediateSubscriptionUpdate({
+ subscriptionUpdate,
+ currentPrices,
+ toUpdatePrices: {
+ ...currentPrices,
+ resourceCreditPriceId: 'price_credit_month',
+ },
+ }),
+ ).toBe(subscriptionUpdate);
+ });
+
+ it('returns a seats update when only the seat count changes', () => {
+ expect(
+ computeImmediateSubscriptionUpdate({
+ subscriptionUpdate,
+ currentPrices,
+ toUpdatePrices: { ...currentPrices, seats: 4 },
+ }),
+ ).toEqual({ type: SubscriptionUpdateType.SEATS, newSeats: 4 });
+ });
+
+ it('returns the requested update when a price and the seat count both change', () => {
+ expect(
+ computeImmediateSubscriptionUpdate({
+ subscriptionUpdate,
+ currentPrices,
+ toUpdatePrices: {
+ ...currentPrices,
+ baseProductPriceId: 'price_base_month',
+ seats: 4,
+ },
+ }),
+ ).toBe(subscriptionUpdate);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-immediate-subscription-update.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-immediate-subscription-update.util.ts
new file mode 100644
index 00000000000..ac203ae49cd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-immediate-subscription-update.util.ts
@@ -0,0 +1,30 @@
+/* @license Enterprise */
+
+import {
+ type SubscriptionUpdate,
+ SubscriptionUpdateType,
+} from 'src/engine/core-modules/billing/types/billing-subscription-update.type';
+import { type SubscriptionStripePrices } from 'src/engine/core-modules/billing/types/subscription-stripe-prices.type';
+
+export const computeImmediateSubscriptionUpdate = ({
+ subscriptionUpdate,
+ currentPrices,
+ toUpdatePrices,
+}: {
+ subscriptionUpdate: SubscriptionUpdate;
+ currentPrices: SubscriptionStripePrices;
+ toUpdatePrices: SubscriptionStripePrices;
+}): SubscriptionUpdate | undefined => {
+ if (
+ toUpdatePrices.baseProductPriceId !== currentPrices.baseProductPriceId ||
+ toUpdatePrices.resourceCreditPriceId !== currentPrices.resourceCreditPriceId
+ ) {
+ return subscriptionUpdate;
+ }
+
+ if (toUpdatePrices.seats === currentPrices.seats) {
+ return undefined;
+ }
+
+ return { type: SubscriptionUpdateType.SEATS, newSeats: toUpdatePrices.seats };
+};