Skip to content

The open alternative to Salesforce, designed for AI.

Billing - fix duplicate key value violates unique constraint "IndexOnActiveSubscriptionPerWorkspace" (#16676)

Etienne65f0a5bb18e7
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
index 520e90cd1af..db8f0b008d0 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
@@ -3,7 +3,7 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { findOrThrow, isDefined } from 'twenty-shared/utils';
+import { findOrThrow, isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import { Not, Repository } from 'typeorm';
import type Stripe from 'stripe';
@@ -93,6 +93,18 @@ export class BillingPortalWorkspaceService {
successUrlPath,
});
+ if (
+ isNonEmptyArray(customer?.billingSubscriptions) &&
+ customer.billingSubscriptions.some(
+ (subscription) => subscription.status !== SubscriptionStatus.Canceled,
+ )
+ ) {
+ throw new BillingException(
+ 'Customer already has a non-canceled billing subscription',
+ BillingExceptionCode.BILLING_SUBSCRIPTION_INVALID,
+ );
+ }
+
const subscription =
await this.stripeCheckoutService.createDirectSubscription({
user,