Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit): set quota and stock default values per billing plan (#27890)

Etienne4f58f362f91e
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts
index e1aed76ae4f..6672c8b9635 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts
@@ -60,6 +60,12 @@ export class BillingCreditAllowanceProvider extends CreditAllowanceProvider {
};
}
+ async getPlanKey(workspaceId: string): Promise<string | null> {
+ const subscription = await this.findCurrentBillingSubscription(workspaceId);
+
+ return subscription?.planKey ?? null;
+ }
+
private async findCurrentBillingSubscription(
workspaceId: string,
): Promise<FlatBillingSubscription | null> {
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service.ts
index 85647b6a8b6..f721dcd1bd2 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service.ts
@@ -10,6 +10,7 @@ import { BillingUsageService } from 'src/engine/core-modules/billing/services/bi
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';
+import { isBaseProductSubscriptionItem } from 'src/engine/core-modules/billing/utils/is-base-product-subscription-item.util';
import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
import { WorkspaceCacheProvider } from 'src/engine/workspace-cache/interfaces/workspace-cache-provider.service';
import { type WorkspaceCacheProviderContext } from 'src/engine/workspace-cache/types/workspace-cache-provider-context.type';
@@ -59,6 +60,10 @@ export class WorkspaceCurrentBillingSubscriptionCacheService extends WorkspaceCa
collectionMethod: subscription.collectionMethod,
planAllowanceMicro:
this.billingUsageService.findResourceUsageCap(subscription),
+ planKey:
+ subscription.billingSubscriptionItems.find(
+ isBaseProductSubscriptionItem,
+ )?.billingProduct?.metadata.planKey ?? null,
creditGrants: unexpiredGrants.map(
({ amountMicro, effectiveAt, expiresAt }) => ({
amountMicro,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/flat-billing-subscription.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/flat-billing-subscription.type.ts
index c98ceff99f1..3389479512b 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/types/flat-billing-subscription.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/types/flat-billing-subscription.type.ts
@@ -1,6 +1,7 @@
/* @license Enterprise */
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
+import { type BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';
import { type BillingSubscriptionCollectionMethod } from 'src/engine/core-modules/billing/enums/billing-subscription-collection-method.enum';
import { type SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
import { type SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
@@ -24,6 +25,7 @@ export type FlatBillingSubscription = {
trialEnd: Date | null;
collectionMethod: BillingSubscriptionCollectionMethod;
planAllowanceMicro: number | null;
+ planKey: BillingPlanKey | null;
creditGrants: CreditAllowanceGrant[];
};
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.ts
index cec2f89898f..930d5542f04 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
@@ -3,15 +3,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 BaseProductSubscriptionItem } from 'src/engine/core-modules/billing/types/base-product-subscription-item.type';
+import { isBaseProductSubscriptionItem } from 'src/engine/core-modules/billing/utils/is-base-product-subscription-item.util';
export const getBaseProductSubscriptionItemOrThrow = (
billingSubscription: BillingSubscriptionEntity,
): BaseProductSubscriptionItem => {
return findOrThrow(
billingSubscription.billingSubscriptionItems,
- ({ billingProduct }) =>
- billingProduct?.metadata?.productKey === BillingProductKey.BASE_PRODUCT,
+ isBaseProductSubscriptionItem,
) as BaseProductSubscriptionItem;
};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/is-base-product-subscription-item.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/is-base-product-subscription-item.util.ts
new file mode 100644
index 00000000000..12f6b77b20c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/is-base-product-subscription-item.util.ts
@@ -0,0 +1,9 @@
+/* @license Enterprise */
+
+import { type BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';
+
+export const isBaseProductSubscriptionItem = ({
+ billingProduct,
+}: Pick<BillingSubscriptionItemEntity, 'billingProduct'>): boolean =>
+ billingProduct?.metadata?.productKey === BillingProductKey.BASE_PRODUCT;
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index 5403e9617d5..785d32adbaf 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -63,6 +63,7 @@ import {
ConfigVariableExceptionCode,
} from 'src/engine/core-modules/twenty-config/twenty-config.exception';
import { type OnboardingEnrichmentCreditRewardTier } from 'src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type';
+import { type PlanUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/types/plan-usage-limit-defaults.type';
import { type AiProvidersConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-providers-config.type';
import {
DEFAULT_DISABLED_MODELS,
@@ -711,7 +712,7 @@ export class ConfigVariables {
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.STORAGE_CONFIG,
description:
- 'Maximum bytes of file storage a single workspace may hold, all its files counted. No limit when unset',
+ 'Maximum bytes of file storage a single workspace may hold, all its files counted. No limit when unset. USAGE_LIMIT_DEFAULTS_BY_PLAN can set it per billing plan',
type: ConfigVariableType.NUMBER,
})
@CastToPositiveNumber()
@@ -721,7 +722,7 @@ export class ConfigVariables {
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.STORAGE_CONFIG,
description:
- 'Maximum number of records a single workspace may hold across its objects, system objects other than messages and calendar events left out, soft-deleted records included. No limit when unset',
+ 'Maximum number of records a single workspace may hold across its objects, system objects other than messages and calendar events left out, soft-deleted records included. No limit when unset. USAGE_LIMIT_DEFAULTS_BY_PLAN can set it per billing plan',
type: ConfigVariableType.NUMBER,
})
@CastToPositiveNumber()
@@ -999,6 +1000,16 @@ export class ConfigVariables {
@ValidateIf((env) => env.IS_BILLING_ENABLED === true)
BILLING_FREE_WORKFLOW_CREDITS_FOR_TRIAL_PERIOD_WITH_CREDIT_CARD = 2_500_000;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.BILLING_CONFIG,
+ description:
+ 'Quota and stock usage limit default values per billing plan, keyed by plan key then by the default\'s config variable, as {"PRO":{"WORKSPACE_RECORD_LIMIT":1000000},"ENTERPRISE":{"WORKSPACE_RECORD_LIMIT":null}}. null means no limit, and a variable left out keeps its own value',
+ isHiddenInAdminPanel: true,
+ type: ConfigVariableType.JSON,
+ })
+ @IsOptional()
+ USAGE_LIMIT_DEFAULTS_BY_PLAN: Record<string, PlanUsageLimitDefaults> = {};
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.BILLING_CONFIG,
description:
@@ -1784,7 +1795,7 @@ export class ConfigVariables {
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.RATE_LIMITING,
description:
- 'Maximum number of emails a single workspace may send per UTC day, campaign and one-off sends counted together. A workspace limit configured in the app replaces it',
+ 'Maximum number of emails a single workspace may send per UTC day, campaign and one-off sends counted together. USAGE_LIMIT_DEFAULTS_BY_PLAN can set it per billing plan, and a workspace limit configured in the app replaces it',
type: ConfigVariableType.NUMBER,
})
@CastToPositiveNumber()
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts
index cb944c57f98..ed3362c304b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts
@@ -14,4 +14,6 @@ export abstract class CreditAllowanceProvider {
abstract getCreditAllowance(
workspaceId: string,
): Promise<CreditAllowance | null>;
+
+ abstract getPlanKey(workspaceId: string): Promise<string | null>;
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/no-credit-allowance-provider.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/no-credit-allowance-provider.service.ts
index 08d458e31b5..3ad5fb49ff6 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/no-credit-allowance-provider.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/no-credit-allowance-provider.service.ts
@@ -14,4 +14,8 @@ export class NoCreditAllowanceProvider extends CreditAllowanceProvider {
async getCreditAllowance(): Promise<CreditAllowance | null> {
return null;
}
+
+ async getPlanKey(): Promise<string | null> {
+ return null;
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-default-value.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-default-value.service.ts
new file mode 100644
index 00000000000..a95967ece8d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-default-value.service.ts
@@ -0,0 +1,64 @@
+import { Injectable, type OnModuleInit } from '@nestjs/common';
+import { DiscoveryService } from '@nestjs/core';
+
+import { isUndefined } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { type OptionalNumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/optional-numeric-config-variable-key.type';
+import { type CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';
+import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util';
+import { getPlanLimitDefaultValue } from 'src/engine/core-modules/usage-limit/utils/get-plan-limit-default-value.util';
+
+@Injectable()
+export class UsageLimitDefaultValueService implements OnModuleInit {
+ private creditAllowanceProvider: CreditAllowanceProvider;
+
+ constructor(
+ private readonly discoveryService: DiscoveryService,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ onModuleInit() {
+ this.creditAllowanceProvider = findCreditAllowanceProvider(
+ this.discoveryService,
+ );
+ }
+
+ async findDefaultLimitValue({
+ workspaceId,
+ limitValueConfigVariable,
+ }: {
+ workspaceId: string;
+ limitValueConfigVariable: OptionalNumericConfigVariableKey;
+ }): Promise<number | null> {
+ const instanceValue =
+ this.twentyConfigService.get(limitValueConfigVariable) ?? null;
+
+ const usageLimitDefaultsByPlan = this.twentyConfigService.get(
+ 'USAGE_LIMIT_DEFAULTS_BY_PLAN',
+ );
+
+ const isSetByAPlan = Object.values(usageLimitDefaultsByPlan).some(
+ (planUsageLimitDefaults) =>
+ !isUndefined(planUsageLimitDefaults[limitValueConfigVariable]),
+ );
+
+ if (!isSetByAPlan) {
+ return instanceValue;
+ }
+
+ const planKey = await this.creditAllowanceProvider.getPlanKey(workspaceId);
+
+ if (!isDefined(planKey)) {
+ return instanceValue;
+ }
+
+ return getPlanLimitDefaultValue({
+ usageLimitDefaultsByPlan,
+ planKey,
+ limitValueConfigVariable,
+ instanceValue,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
index 1082f9816b2..6bf39e493d3 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
@@ -13,6 +13,7 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twent
import { WARM_AND_CONSUME_COUNTERS_SCRIPT } from 'src/engine/core-modules/usage-limit/constants/warm-and-consume-counters-script.constant';
import { UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';
+import { UsageLimitDefaultValueService } from 'src/engine/core-modules/usage-limit/services/usage-limit-default-value.service';
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
@@ -87,6 +88,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
private readonly usageRecorderService: UsageRecorderService,
private readonly discoveryService: DiscoveryService,
private readonly usageLimitEntitlementService: UsageLimitEntitlementService,
+ private readonly usageLimitDefaultValueService: UsageLimitDefaultValueService,
private readonly metricsService: MetricsService,
private readonly twentyConfigService: TwentyConfigService,
) {}
@@ -563,7 +565,10 @@ export class UsageLimitQuotaService implements OnModuleInit {
return [];
}
- const quotaLimitDefaults = this.buildQuotaLimitDefaults(resourceType);
+ const quotaLimitDefaults = await this.buildQuotaLimitDefaults({
+ workspaceId,
+ resourceType,
+ });
const quotaLimits = await this.findQuotaLimits({
workspaceId,
@@ -592,9 +597,13 @@ export class UsageLimitQuotaService implements OnModuleInit {
});
}
- private buildQuotaLimitDefaults(
- resourceType: UsageResourceType,
- ): QuotaLimitDefault[] {
+ private async buildQuotaLimitDefaults({
+ workspaceId,
+ resourceType,
+ }: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ }): Promise<QuotaLimitDefault[]> {
if (!this.twentyConfigService.get('CLICKHOUSE_URL')) {
return [];
}
@@ -604,12 +613,26 @@ export class UsageLimitQuotaService implements OnModuleInit {
limitKind: 'quota',
});
- return (definition?.defaults ?? []).map(
- ({ limitValueConfigVariable, ...quotaLimitDefaultDefinition }) => ({
- ...quotaLimitDefaultDefinition,
- limitValue: this.twentyConfigService.get(limitValueConfigVariable),
- }),
+ const quotaLimitDefaults = await Promise.all(
+ (definition?.defaults ?? []).map(
+ async ({
+ limitValueConfigVariable,
+ ...quotaLimitDefaultDefinition
+ }) => {
+ const limitValue =
+ await this.usageLimitDefaultValueService.findDefaultLimitValue({
+ workspaceId,
+ limitValueConfigVariable,
+ });
+
+ return isDefined(limitValue)
+ ? [{ ...quotaLimitDefaultDefinition, limitValue }]
+ : [];
+ },
+ ),
);
+
+ return quotaLimitDefaults.flat();
}
private async buildAllowanceCounterAdmittingOnFailure(
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
index c11b9f1c895..418c5ff7d36 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
@@ -14,6 +14,7 @@ import {
UsageLimitException,
UsageLimitExceptionCode,
} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { UsageLimitDefaultValueService } from 'src/engine/core-modules/usage-limit/services/usage-limit-default-value.service';
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { type ComputeUsedStock } from 'src/engine/core-modules/usage-limit/types/compute-used-stock.type';
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
@@ -57,6 +58,7 @@ export class UsageLimitStockService {
private readonly cacheStorage: CacheStorageService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly usageLimitEntitlementService: UsageLimitEntitlementService,
+ private readonly usageLimitDefaultValueService: UsageLimitDefaultValueService,
private readonly metricsService: MetricsService,
private readonly twentyConfigService: TwentyConfigService,
) {}
@@ -248,46 +250,56 @@ export class UsageLimitStockService {
operationType,
spenders,
limits: enforceableLimits,
- stockLimitDefaults: this.buildStockLimitDefaults({
+ stockLimitDefaults: await this.buildStockLimitDefaults({
+ workspaceId,
resourceType,
operationType,
}),
});
}
- private buildStockLimitDefaults({
+ private async buildStockLimitDefaults({
+ workspaceId,
resourceType,
operationType,
}: {
+ workspaceId: string;
resourceType: StockResourceType;
operationType: UsageOperationType;
- }): StockLimitDefault[] {
+ }): Promise<StockLimitDefault[]> {
const definition = findUsageLimitDefinition({
resourceType,
limitKind: 'stock',
});
- return (definition?.defaults ?? [])
- .filter(
- (stockLimitDefaultDefinition) =>
- stockLimitDefaultDefinition.operationType === operationType,
- )
- .flatMap((stockLimitDefaultDefinition) => {
- const limitValue = this.twentyConfigService.get(
- stockLimitDefaultDefinition.limitValueConfigVariable,
- );
-
- return isDefined(limitValue)
- ? [
- {
- spenderType: stockLimitDefaultDefinition.spenderType,
- unit: stockLimitDefaultDefinition.unit,
- isOverridable: stockLimitDefaultDefinition.isOverridable,
- limitValue,
- },
- ]
- : [];
- });
+ const stockLimitDefaults = await Promise.all(
+ (definition?.defaults ?? [])
+ .filter(
+ (stockLimitDefaultDefinition) =>
+ stockLimitDefaultDefinition.operationType === operationType,
+ )
+ .map(async (stockLimitDefaultDefinition) => {
+ const limitValue =
+ await this.usageLimitDefaultValueService.findDefaultLimitValue({
+ workspaceId,
+ limitValueConfigVariable:
+ stockLimitDefaultDefinition.limitValueConfigVariable,
+ });
+
+ return isDefined(limitValue)
+ ? [
+ {
+ spenderType: stockLimitDefaultDefinition.spenderType,
+ unit: stockLimitDefaultDefinition.unit,
+ isOverridable: stockLimitDefaultDefinition.isOverridable,
+ limitValue,
+ },
+ ]
+ : [];
+ }),
+ );
+
+ return stockLimitDefaults.flat();
}
private async warmHeldValues({
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/plan-usage-limit-defaults.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/plan-usage-limit-defaults.type.ts
new file mode 100644
index 00000000000..95d6f7e3b6d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/plan-usage-limit-defaults.type.ts
@@ -0,0 +1,5 @@
+import { type ConfigVariables } from 'src/engine/core-modules/twenty-config/config-variables';
+
+export type PlanUsageLimitDefaults = Partial<
+ Record<keyof ConfigVariables, number | null>
+>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
index 3960dde637d..25db342d843 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
@@ -15,6 +15,7 @@ import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/ag
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
import { UsageQuotaConsumptionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-consumption.service';
import { UsageQuotaDefinitionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-definition.service';
+import { UsageLimitDefaultValueService } from 'src/engine/core-modules/usage-limit/services/usage-limit-default-value.service';
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
import { UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
@@ -51,6 +52,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
UsageLimitStockService,
WorkspaceRecordStockService,
UsageLimitEntitlementService,
+ UsageLimitDefaultValueService,
UsageLimitsCacheService,
UsagePeriodService,
UsageLimitService,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-plan-limit-default-value.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-plan-limit-default-value.util.spec.ts
new file mode 100644
index 00000000000..d3abd863802
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-plan-limit-default-value.util.spec.ts
@@ -0,0 +1,30 @@
+import { type OptionalNumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/optional-numeric-config-variable-key.type';
+import { type PlanUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/types/plan-usage-limit-defaults.type';
+import { getPlanLimitDefaultValue } from 'src/engine/core-modules/usage-limit/utils/get-plan-limit-default-value.util';
+
+const INSTANCE_VALUE = 7;
+
+const usageLimitDefaultsByPlan: Record<string, PlanUsageLimitDefaults> = {
+ PRO: {
+ WORKSPACE_RECORD_LIMIT: 1_000,
+ EMAIL_SEND_WORKSPACE_DAILY_LIMIT: null,
+ },
+};
+
+describe('getPlanLimitDefaultValue', () => {
+ it.each<[string, OptionalNumericConfigVariableKey, number | null]>([
+ ['PRO', 'WORKSPACE_RECORD_LIMIT', 1_000],
+ ['PRO', 'EMAIL_SEND_WORKSPACE_DAILY_LIMIT', null],
+ ['PRO', 'WORKSPACE_STORAGE_LIMIT_BYTES', INSTANCE_VALUE],
+ ['UNKNOWN', 'WORKSPACE_RECORD_LIMIT', INSTANCE_VALUE],
+ ])('on %s, %s is %p', (planKey, limitValueConfigVariable, expected) => {
+ expect(
+ getPlanLimitDefaultValue({
+ usageLimitDefaultsByPlan,
+ planKey,
+ limitValueConfigVariable,
+ instanceValue: INSTANCE_VALUE,
+ }),
+ ).toBe(expected);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-plan-limit-default-value.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-plan-limit-default-value.util.ts
new file mode 100644
index 00000000000..8f139c17455
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-plan-limit-default-value.util.ts
@@ -0,0 +1,21 @@
+import { isUndefined } from '@sniptt/guards';
+
+import { type OptionalNumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/optional-numeric-config-variable-key.type';
+import { type PlanUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/types/plan-usage-limit-defaults.type';
+
+export const getPlanLimitDefaultValue = ({
+ usageLimitDefaultsByPlan,
+ planKey,
+ limitValueConfigVariable,
+ instanceValue,
+}: {
+ usageLimitDefaultsByPlan: Record<string, PlanUsageLimitDefaults>;
+ planKey: string;
+ limitValueConfigVariable: OptionalNumericConfigVariableKey;
+ instanceValue: number | null;
+}): number | null => {
+ const planValue =
+ usageLimitDefaultsByPlan[planKey]?.[limitValueConfigVariable];
+
+ return isUndefined(planValue) ? instanceValue : planValue;
+};