The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
refactor(usage-limit): import billing directly instead of discovering its providers (#27926)
Etiennebfdc4a3ef49e
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.tsindex 6ace649a236..1a68b67c7e5 100644--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts@@ -25,10 +25,10 @@ import { isDefined } from 'twenty-shared/utils';import { AppBillingService } from 'src/engine/core-modules/billing/app-billing/app-billing.service';import { ChargeDto } from 'src/engine/core-modules/billing/app-billing/dtos/charge.dto';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';@@ -60,7 +60,7 @@ const CREDIT_UNAVAILABLE_REASON_BY_SERVER_REASON: Record<export class AppBillingController {constructor(private readonly appBillingService: AppBillingService,- private readonly billingUsageService: BillingUsageService,+ private readonly usageQuotaAdmissionService: UsageQuotaAdmissionService,private readonly throttlerService: ThrottlerService,private readonly twentyConfigService: TwentyConfigService,) {}@@ -82,7 +82,7 @@ export class AppBillingController {);const creditAvailability =- await this.billingUsageService.getCreditAvailability(+ await this.usageQuotaAdmissionService.getCreditAvailability(request.workspace.id,);diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.tsindex 2108f03439a..f5bb025ba2e 100644--- a/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/billing-subscription-item.resolver.ts@@ -1,6 +1,6 @@/* @license Enterprise */-import { Logger, UseFilters, UsePipes } from '@nestjs/common';+import { UseFilters, UsePipes } from '@nestjs/common';import { Parent, ResolveField } from '@nestjs/graphql';import { InjectRepository } from '@nestjs/typeorm';@@ -11,9 +11,6 @@ import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decoratoimport { BillingSubscriptionItemDTO } from 'src/engine/core-modules/billing/dtos/billing-subscription-item.dto';import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';-import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';@@ -22,14 +19,7 @@ import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display@UsePipes(ResolverValidationPipe)@UseFilters(PreventNestToAutoLogGraphqlErrorsFilter)export class BillingSubscriptionItemResolver {- private readonly logger = new Logger(BillingSubscriptionItemResolver.name);-constructor(- private readonly billingUsageService: BillingUsageService,- // Field resolver: the workspace comes from the parent item's subscription row- // eslint-disable-next-line twenty/prefer-workspace-scoped-repository- @InjectRepository(BillingSubscriptionEntity)- private readonly billingSubscriptionRepository: Repository<BillingSubscriptionEntity>,@InjectRepository(BillingPriceEntity)private readonly billingPriceRepository: Repository<BillingPriceEntity>,) {}@@ -84,45 +74,4 @@ export class BillingSubscriptionItemResolver {})));}-- // Derived from the live balance: a stored flag drifts as soon as one balance-mutating path misses it- @ResolveField(() => Boolean)- async hasReachedCurrentPeriodCap(- @Parent() billingSubscriptionItem: BillingSubscriptionItemEntity,- ): Promise<boolean> {- if (- billingSubscriptionItem.billingProduct?.metadata?.productKey !==- BillingProductKey.RESOURCE_CREDIT- ) {- return false;- }-- // Rides on currentWorkspace (app boot): a billing read failure must degrade to no banner, never fail the query- try {- const billingSubscription =- await this.billingSubscriptionRepository.findOne({- where: { id: billingSubscriptionItem.billingSubscriptionId },- });-- if (!isDefined(billingSubscription)) {- return false;- }-- const creditAvailability =- await this.billingUsageService.getCreditAvailability(- billingSubscription.workspaceId,- );-- return (- !creditAvailability.hasAvailableCredits &&- creditAvailability.reason === 'NO_CREDITS'- );- } catch (error) {- this.logger.warn(- `Failed to derive hasReachedCurrentPeriodCap for billing subscription item ${billingSubscriptionItem.id}: ${error instanceof Error ? error.message : String(error)}`,- );-- return false;- }- }}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 75f65d30fe7..a01b9170e5c 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@@ -21,6 +21,7 @@ import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/eimport { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { BillingRestApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-api-exception.filter';import { BillingWorkspaceMemberListener } from 'src/engine/core-modules/billing/listeners/billing-workspace-member.listener';+import { BillingCreditAllowanceService } from 'src/engine/core-modules/billing/services/billing-credit-allowance.service';import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.service';import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';@@ -30,8 +31,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 { 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';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';@@ -47,7 +46,6 @@ import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/userimport { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';-import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';import { UsageAnalyticsModule } from 'src/engine/core-modules/usage/usage-analytics.module';import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';@@ -74,7 +72,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheMetricsModule,EnterpriseModule,UsageAnalyticsModule,- UsageLimitModule,WorkspaceIteratorModule,],providers: [@@ -93,8 +90,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingUpdateSubscriptionPriceCommand,BillingSyncPlansDataCommand,BillingUsageService,- BillingCreditAllowanceProvider,- BillingUsageLimitEntitlementProvider,+ BillingCreditAllowanceService,BillingPriceService,BillingCreditRolloverService,BillingCreditGrantService,@@ -109,6 +105,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache],exports: [BillingSubscriptionService,+ BillingCreditAllowanceService,BillingSubscriptionUpdateService,BillingService,BillingUsageService,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.service.tssimilarity index 92%rename from packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.tsrename to packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance.service.tsindex 6672c8b9635..cb01645aae1 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.service.ts@@ -7,19 +7,16 @@ import { isDefined } from 'twenty-shared/utils';import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';import { type FlatBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';-import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';import { type CreditAllowance } from 'src/engine/core-modules/usage-limit/types/credit-allowance.type';import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';@Injectable()-export class BillingCreditAllowanceProvider extends CreditAllowanceProvider {+export class BillingCreditAllowanceService {constructor(private readonly twentyConfigService: TwentyConfigService,private readonly workspaceCacheService: WorkspaceCacheService,- ) {- super();- }+ ) {}async isCreditAllowanceEnabled(): Promise<boolean> {return this.twentyConfigService.get('IS_BILLING_ENABLED');diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-limit-entitlement-provider.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-limit-entitlement-provider.service.tsdeleted file mode 100644index d90d5e58882..00000000000--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-limit-entitlement-provider.service.ts+++ /dev/null@@ -1,25 +0,0 @@-/* @license Enterprise */--import { Injectable } from '@nestjs/common';--import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';-import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';-import { UsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service';--@Injectable()-export class BillingUsageLimitEntitlementProvider extends UsageLimitEntitlementProvider {- constructor(- private readonly billingSubscriptionService: BillingSubscriptionService,- ) {- super();- }-- async hasIntraWorkspaceLimitEntitlement(- workspaceId: string,- ): Promise<boolean> {- return this.billingSubscriptionService.getWorkspaceEntitlementValue(- workspaceId,- BillingEntitlementKey.USAGE_LIMIT,- );- }-}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.tsindex 301ea276120..6e2f36349d9 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts@@ -20,19 +20,11 @@ import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billinimport { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';-import { type CreditAvailability } from 'src/engine/core-modules/billing/types/credit-availability.type';import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';-import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';-import { buildUsageRefusalException } from 'src/engine/core-modules/billing/utils/build-usage-refusal-exception.util';import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';-import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';-import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';-import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';-import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';-import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';@@ -40,14 +32,6 @@ type UsageSumRow = {total: string | number | null;};-type UsageQuotaScope = {- workspaceId: string;- resourceType: UsageResourceType;- operationType: UsageOperationType;- spenders: UsageSpenders;- cost?: QuotaCost;-};-@Injectable()export class BillingUsageService {protected readonly logger = new Logger(BillingUsageService.name);@@ -59,47 +43,9 @@ export class BillingUsageService {private readonly workspaceCacheService: WorkspaceCacheService,private readonly clickHouseService: ClickHouseService,private readonly coreEntityCacheService: CoreEntityCacheService,- private readonly usageLimitQuotaService: UsageLimitQuotaService,private readonly usageAnalyticsService: UsageAnalyticsService,) {}- async assertUsageAllowed(scope: UsageQuotaScope): Promise<void> {- const usageRefusal = await this.findUsageRefusal(scope);-- if (isDefined(usageRefusal)) {- throw buildUsageRefusalException({- usageRefusal,- workspaceId: scope.workspaceId,- });- }- }-- async findUsageRefusal({- workspaceId,- resourceType,- operationType,- spenders,- cost,- }: UsageQuotaScope): Promise<UsageRefusal | null> {- const subscriptionInactiveReason =- await this.getSubscriptionInactiveReason(workspaceId);-- if (isDefined(subscriptionInactiveReason)) {- return {- kind: 'subscriptionInactive',- reason: subscriptionInactiveReason,- };- }-- const exhaustedScope = await this.usageLimitQuotaService.findExhaustedScope(- { workspaceId, resourceType, operationType, spenders, cost },- );-- return isDefined(exhaustedScope)- ? { kind: 'quotaExhausted', exhaustedScope }- : null;- }-async getSubscriptionInactiveReason(workspaceId: string,): Promise<SubscriptionInactiveReason | null> {@@ -129,33 +75,6 @@ export class BillingUsageService {return null;}- async getCreditAvailability(- workspaceId: string,- ): Promise<CreditAvailability> {- const subscriptionInactiveReason =- await this.getSubscriptionInactiveReason(workspaceId);-- if (isDefined(subscriptionInactiveReason)) {- return { hasAvailableCredits: false, reason: subscriptionInactiveReason };- }-- const remainingMicro =- await this.usageLimitQuotaService.getAllowanceRemainingMicro(workspaceId);-- if (isDefined(remainingMicro) && remainingMicro <= 0) {- return { hasAvailableCredits: false, reason: 'NO_CREDITS' };- }-- return { hasAvailableCredits: true };- }-- async hasAvailableCredits(workspaceId: string): Promise<boolean> {- const { hasAvailableCredits } =- await this.getCreditAvailability(workspaceId);-- return hasAvailableCredits;- }-async getResourceCreditProductUsage(workspace: WorkspaceEntity,): Promise<BillingResourceCreditUsageDTO[]> {diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.tsindex b2f91a10635..5011fba0b77 100644--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts@@ -33,7 +33,6 @@ import { type FlatApplicationVariableMaps } from 'src/engine/metadata-modules/flimport { ApplicationService } from 'src/engine/core-modules/application/application.service';import { FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';import { ApplicationTokenService } from 'src/engine/core-modules/auth/token/services/application-token.service';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';import { LOGIC_FUNCTION_EXECUTED_EVENT } from 'src/engine/core-modules/event-logs/emit/events/workspace-event/logic-function/logic-function-executed';@@ -51,6 +50,7 @@ import {import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';+import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/user/utils/resolve-workspace-member-id-for-user.util';@@ -111,7 +111,7 @@ export class LogicFunctionExecutorService {private readonly subscriptionService: SubscriptionService,private readonly eventLogLiveService: EventLogLiveService,private readonly eventLogEmitterService: EventLogEmitterService,- private readonly billingUsageService: BillingUsageService,+ private readonly usageQuotaAdmissionService: UsageQuotaAdmissionService,private readonly usageLimitQuotaService: UsageLimitQuotaService,private readonly workspaceDomainsService: WorkspaceDomainsService,private readonly applicationService: ApplicationService,@@ -264,7 +264,7 @@ export class LogicFunctionExecutorService {return;}- await this.billingUsageService.assertUsageAllowed({+ await this.usageQuotaAdmissionService.assertUsageAllowed({workspaceId,resourceType: UsageResourceType.LOGIC_FUNCTION,operationType: UsageOperationType.CODE_EXECUTION,diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/billing-subscription-item-cap.resolver.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/billing-subscription-item-cap.resolver.tsnew file mode 100644index 00000000000..b7786ec5eff--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/billing-subscription-item-cap.resolver.ts@@ -0,0 +1,63 @@+/* @license Enterprise */++import { Logger, UseFilters, UsePipes } from '@nestjs/common';+import { Parent, ResolveField } from '@nestjs/graphql';++import { isDefined } from 'twenty-shared/utils';++import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';+import { BillingSubscriptionItemDTO } from 'src/engine/core-modules/billing/dtos/billing-subscription-item.dto';+import { 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';+import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';+import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';++@MetadataResolver(() => BillingSubscriptionItemDTO)+@UsePipes(ResolverValidationPipe)+@UseFilters(PreventNestToAutoLogGraphqlErrorsFilter)+export class BillingSubscriptionItemCapResolver {+ private readonly logger = new Logger(BillingSubscriptionItemCapResolver.name);++ constructor(+ private readonly usageQuotaAdmissionService: UsageQuotaAdmissionService,+ ) {}++ @ResolveField(() => Boolean)+ async hasReachedCurrentPeriodCap(+ @Parent() billingSubscriptionItem: BillingSubscriptionItemEntity,+ @AuthWorkspace({ allowUndefined: true })+ workspace: WorkspaceEntity | undefined,+ ): Promise<boolean> {+ if (!isDefined(workspace)) {+ return false;+ }++ if (+ billingSubscriptionItem.billingProduct?.metadata?.productKey !==+ BillingProductKey.RESOURCE_CREDIT+ ) {+ return false;+ }++ try {+ const creditAvailability =+ await this.usageQuotaAdmissionService.getCreditAvailability(+ workspace.id,+ );++ return (+ !creditAvailability.hasAvailableCredits &&+ creditAvailability.reason === 'NO_CREDITS'+ );+ } catch (error) {+ this.logger.warn(+ `Failed to derive hasReachedCurrentPeriodCap for billing subscription item ${billingSubscriptionItem.id}: ${error instanceof Error ? error.message : String(error)}`,+ );++ return false;+ }+ }+}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.tsdeleted file mode 100644index ed3362c304b..00000000000--- a/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts+++ /dev/null@@ -1,19 +0,0 @@-import { Injectable } from '@nestjs/common';--import { type CreditAllowance } from 'src/engine/core-modules/usage-limit/types/credit-allowance.type';-import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';--@Injectable()-export abstract class CreditAllowanceProvider {- abstract isCreditAllowanceEnabled(): Promise<boolean>;-- abstract getCreditAllowancePeriod(- workspaceId: string,- ): Promise<UsagePeriod | null>;-- 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/interfaces/usage-limit-entitlement-provider.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service.tsdeleted file mode 100644index 11abcab6986..00000000000--- a/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service.ts+++ /dev/null@@ -1,8 +0,0 @@-import { Injectable } from '@nestjs/common';--@Injectable()-export abstract class UsageLimitEntitlementProvider {- abstract hasIntraWorkspaceLimitEntitlement(- workspaceId: string,- ): Promise<boolean>;-}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.tsdeleted file mode 100644index 3ad5fb49ff6..00000000000--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/no-credit-allowance-provider.service.ts+++ /dev/null@@ -1,21 +0,0 @@-import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';-import { type CreditAllowance } from 'src/engine/core-modules/usage-limit/types/credit-allowance.type';-import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';--export class NoCreditAllowanceProvider extends CreditAllowanceProvider {- async isCreditAllowanceEnabled(): Promise<boolean> {- return false;- }-- async getCreditAllowancePeriod(): Promise<UsagePeriod | null> {- return null;- }-- 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/no-usage-limit-entitlement-provider.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/no-usage-limit-entitlement-provider.service.tsdeleted file mode 100644index 0cf1d5e4e37..00000000000--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/no-usage-limit-entitlement-provider.service.ts+++ /dev/null@@ -1,7 +0,0 @@-import { UsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service';--export class NoUsageLimitEntitlementProvider extends UsageLimitEntitlementProvider {- async hasIntraWorkspaceLimitEntitlement(): Promise<boolean> {- return true;- }-}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.tsindex a95967ece8d..78395005330 100644--- 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@@ -1,30 +1,20 @@-import { Injectable, type OnModuleInit } from '@nestjs/common';-import { DiscoveryService } from '@nestjs/core';+import { Injectable } from '@nestjs/common';import { isUndefined } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';+import { BillingCreditAllowanceService } from 'src/engine/core-modules/billing/services/billing-credit-allowance.service';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;-+export class UsageLimitDefaultValueService {constructor(- private readonly discoveryService: DiscoveryService,+ private readonly billingCreditAllowanceService: BillingCreditAllowanceService,private readonly twentyConfigService: TwentyConfigService,) {}- onModuleInit() {- this.creditAllowanceProvider = findCreditAllowanceProvider(- this.discoveryService,- );- }-async findDefaultLimitValue({workspaceId,limitValueConfigVariable,@@ -48,7 +38,8 @@ export class UsageLimitDefaultValueService implements OnModuleInit {return instanceValue;}- const planKey = await this.creditAllowanceProvider.getPlanKey(workspaceId);+ const planKey =+ await this.billingCreditAllowanceService.getPlanKey(workspaceId);if (!isDefined(planKey)) {return instanceValue;diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service.tsindex 8acaf649609..c26e135f248 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service.ts@@ -1,29 +1,23 @@-import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';-import { DiscoveryService } from '@nestjs/core';+import { Injectable, Logger } from '@nestjs/common';-import { type UsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service';+import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';+import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';import { findEnforceableLimits } from 'src/engine/core-modules/usage-limit/utils/find-enforceable-limits.util';-import { findUsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-entitlement-provider.util';import { isIntraWorkspaceScoped } from 'src/engine/core-modules/usage-limit/utils/is-intra-workspace-scoped.util';@Injectable()-export class UsageLimitEntitlementService implements OnModuleInit {+export class UsageLimitEntitlementService {private readonly logger = new Logger(UsageLimitEntitlementService.name);- private entitlementProvider: UsageLimitEntitlementProvider;-- constructor(private readonly discoveryService: DiscoveryService) {}-- onModuleInit() {- this.entitlementProvider = findUsageLimitEntitlementProvider(- this.discoveryService,- );- }+ constructor(+ private readonly billingSubscriptionService: BillingSubscriptionService,+ ) {}async isIntraWorkspaceLimitEntitled(workspaceId: string): Promise<boolean> {- return this.entitlementProvider.hasIntraWorkspaceLimitEntitlement(+ return this.billingSubscriptionService.getWorkspaceEntitlementValue(workspaceId,+ BillingEntitlementKey.USAGE_LIMIT,);}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.tsindex 6bf39e493d3..28ad730081b 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@@ -1,9 +1,9 @@-import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';-import { DiscoveryService } from '@nestjs/core';+import { Injectable, Logger } from '@nestjs/common';import uniqBy from 'lodash.uniqby';import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { BillingCreditAllowanceService } from 'src/engine/core-modules/billing/services/billing-credit-allowance.service';import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';@@ -12,7 +12,6 @@ import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';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';@@ -37,7 +36,6 @@ import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/utimport { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';import { computeCreditAllowanceMicro } from 'src/engine/core-modules/usage-limit/utils/compute-credit-allowance-micro.util';import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';-import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util';import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';import { findSuppressedUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.util';import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';@@ -74,11 +72,9 @@ type QuotaConsumeResult = {};@Injectable()-export class UsageLimitQuotaService implements OnModuleInit {+export class UsageLimitQuotaService {private readonly logger = new Logger(UsageLimitQuotaService.name);- private creditAllowanceProvider: CreditAllowanceProvider;-constructor(@InjectCacheStorage(CacheStorageNamespace.EngineUsageLimit)private readonly cacheStorage: CacheStorageService,@@ -86,19 +82,13 @@ export class UsageLimitQuotaService implements OnModuleInit {private readonly usagePeriodService: UsagePeriodService,private readonly usageAnalyticsService: UsageAnalyticsService,private readonly usageRecorderService: UsageRecorderService,- private readonly discoveryService: DiscoveryService,+ private readonly billingCreditAllowanceService: BillingCreditAllowanceService,private readonly usageLimitEntitlementService: UsageLimitEntitlementService,private readonly usageLimitDefaultValueService: UsageLimitDefaultValueService,private readonly metricsService: MetricsService,private readonly twentyConfigService: TwentyConfigService,) {}- onModuleInit() {- this.creditAllowanceProvider = findCreditAllowanceProvider(- this.discoveryService,- );- }-async findExhaustedScope(args: QuotaConsumeArgs & { cost?: QuotaCost },): Promise<ExhaustedScope | null> {@@ -662,12 +652,14 @@ export class UsageLimitQuotaService implements OnModuleInit {private async buildAllowanceCounter(workspaceId: string,): Promise<AllowanceQuotaCounter | null> {- if (!(await this.creditAllowanceProvider.isCreditAllowanceEnabled())) {+ if (+ !(await this.billingCreditAllowanceService.isCreditAllowanceEnabled())+ ) {return null;}const allowance =- await this.creditAllowanceProvider.getCreditAllowance(workspaceId);+ await this.billingCreditAllowanceService.getCreditAllowance(workspaceId);if (!isDefined(allowance)) {return null;diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.tsindex 033cfec5159..e7a243cd0ec 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts@@ -1,36 +1,30 @@/* @license Enterprise */-import { Injectable, type OnModuleInit } from '@nestjs/common';-import { DiscoveryService } from '@nestjs/core';+import { Injectable } from '@nestjs/common';import { assertUnreachable, isDefined } from 'twenty-shared/utils';-import { type CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';+import { BillingCreditAllowanceService } from 'src/engine/core-modules/billing/services/billing-credit-allowance.service';import { type AnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/types/anchored-period-unit.type';import { type CalendarPeriodUnit } from 'src/engine/core-modules/usage-limit/types/calendar-period-unit.type';import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';-import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util';import { getCalendarDayPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-day-period.util';import { getCalendarMonthPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-month-period.util';import { getCalendarWeekPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-week-period.util';import { isAnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util';@Injectable()-export class UsagePeriodService implements OnModuleInit {- private creditAllowanceProvider: CreditAllowanceProvider;-- constructor(private readonly discoveryService: DiscoveryService) {}-- onModuleInit() {- this.creditAllowanceProvider = findCreditAllowanceProvider(- this.discoveryService,- );- }+export class UsagePeriodService {+ constructor(+ private readonly billingCreditAllowanceService: BillingCreditAllowanceService,+ ) {}async hasAllowancePeriod(workspaceId: string): Promise<boolean> {return isDefined(- await this.creditAllowanceProvider.getCreditAllowancePeriod(workspaceId),+ await this.billingCreditAllowanceService.getCreditAllowancePeriod(+ workspaceId,+ ),);}@@ -45,7 +39,9 @@ export class UsagePeriodService implements OnModuleInit {return this.getCalendarPeriod(periodUnit);}- return this.creditAllowanceProvider.getCreditAllowancePeriod(workspaceId);+ return this.billingCreditAllowanceService.getCreditAllowancePeriod(+ workspaceId,+ );}async findCurrentPeriodsByUnit({diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-admission.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-admission.service.tsnew file mode 100644index 00000000000..0d999aa4b5a--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-admission.service.ts@@ -0,0 +1,95 @@+/* @license Enterprise */++import { Injectable } from '@nestjs/common';++import { isDefined } from 'twenty-shared/utils';++import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';+import { type CreditAvailability } from 'src/engine/core-modules/billing/types/credit-availability.type';+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';+import { buildUsageRefusalException } from 'src/engine/core-modules/billing/utils/build-usage-refusal-exception.util';+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';+import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';++type UsageQuotaScope = {+ workspaceId: string;+ resourceType: UsageResourceType;+ operationType: UsageOperationType;+ spenders: UsageSpenders;+ cost?: QuotaCost;+};++@Injectable()+export class UsageQuotaAdmissionService {+ constructor(+ private readonly billingUsageService: BillingUsageService,+ private readonly usageLimitQuotaService: UsageLimitQuotaService,+ ) {}++ async assertUsageAllowed(scope: UsageQuotaScope): Promise<void> {+ const usageRefusal = await this.findUsageRefusal(scope);++ if (isDefined(usageRefusal)) {+ throw buildUsageRefusalException({+ usageRefusal,+ workspaceId: scope.workspaceId,+ });+ }+ }++ async findUsageRefusal({+ workspaceId,+ resourceType,+ operationType,+ spenders,+ cost,+ }: UsageQuotaScope): Promise<UsageRefusal | null> {+ const subscriptionInactiveReason =+ await this.billingUsageService.getSubscriptionInactiveReason(workspaceId);++ if (isDefined(subscriptionInactiveReason)) {+ return {+ kind: 'subscriptionInactive',+ reason: subscriptionInactiveReason,+ };+ }++ const exhaustedScope = await this.usageLimitQuotaService.findExhaustedScope(+ { workspaceId, resourceType, operationType, spenders, cost },+ );++ return isDefined(exhaustedScope)+ ? { kind: 'quotaExhausted', exhaustedScope }+ : null;+ }++ async getCreditAvailability(+ workspaceId: string,+ ): Promise<CreditAvailability> {+ const subscriptionInactiveReason =+ await this.billingUsageService.getSubscriptionInactiveReason(workspaceId);++ if (isDefined(subscriptionInactiveReason)) {+ return { hasAvailableCredits: false, reason: subscriptionInactiveReason };+ }++ const remainingMicro =+ await this.usageLimitQuotaService.getAllowanceRemainingMicro(workspaceId);++ if (isDefined(remainingMicro) && remainingMicro <= 0) {+ return { hasAvailableCredits: false, reason: 'NO_CREDITS' };+ }++ return { hasAvailableCredits: true };+ }++ async hasAvailableCredits(workspaceId: string): Promise<boolean> {+ const { hasAvailableCredits } =+ await this.getCreditAvailability(workspaceId);++ return hasAvailableCredits;+ }+}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.tsindex 25db342d843..620965ab31f 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@@ -1,10 +1,11 @@import { Module } from '@nestjs/common';-import { DiscoveryModule } from '@nestjs/core';import { TypeOrmModule } from '@nestjs/typeorm';import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';+import { BillingModule } from 'src/engine/core-modules/billing/billing.module';import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';+import { BillingSubscriptionItemCapResolver } from 'src/engine/core-modules/usage-limit/billing-subscription-item-cap.resolver';import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';import { UsageAnalyticsModule } from 'src/engine/core-modules/usage/usage-analytics.module';@@ -13,6 +14,7 @@ import { ApplicationEntity } from 'src/engine/core-modules/application/applicatiimport { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';+import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';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';@@ -40,7 +42,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache]),WorkspaceCacheModule,PermissionsModule,- DiscoveryModule,+ BillingModule,MetricsModule,ThrottlerModule,UsageAnalyticsModule,@@ -59,6 +61,8 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheUsageQuotaConsumptionService,UsageQuotaDefinitionService,UsageLimitResolver,+ UsageQuotaAdmissionService,+ BillingSubscriptionItemCapResolver,provideWorkspaceScopedRepository(UsageLimitEntity),provideWorkspaceScopedRepository(ApiKeyEntity),provideWorkspaceScopedRepository(ApplicationEntity),@@ -70,6 +74,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheUsageLimitEntitlementService,UsageLimitService,UsageLimitQuotaService,+ UsageQuotaAdmissionService,UsageLimitSpeedService,UsageLimitStockService,WorkspaceRecordStockService,diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util.tsdeleted file mode 100644index 8b3b1836b05..00000000000--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util.ts+++ /dev/null@@ -1,13 +0,0 @@-import { type DiscoveryService } from '@nestjs/core';--import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';-import { NoCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/services/no-credit-allowance-provider.service';-import { findProviderInstance } from 'src/engine/core-modules/usage-limit/utils/find-provider-instance.util';--export const findCreditAllowanceProvider = (- discoveryService: DiscoveryService,-): CreditAllowanceProvider =>- findProviderInstance({- discoveryService,- providerClass: CreditAllowanceProvider,- }) ?? new NoCreditAllowanceProvider();diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-provider-instance.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-provider-instance.util.tsdeleted file mode 100644index 9717cdfd675..00000000000--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-provider-instance.util.ts+++ /dev/null@@ -1,21 +0,0 @@-import { type DiscoveryService } from '@nestjs/core';--import { isDefined } from 'twenty-shared/utils';--export const findProviderInstance = <TProvider>({- discoveryService,- providerClass,-}: {- discoveryService: DiscoveryService;- providerClass: abstract new (...args: never[]) => TProvider;-}): TProvider | null => {- for (const wrapper of discoveryService.getProviders()) {- const { instance } = wrapper;-- if (isDefined(instance) && instance instanceof providerClass) {- return instance;- }- }-- return null;-};diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-usage-limit-entitlement-provider.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-usage-limit-entitlement-provider.util.tsdeleted file mode 100644index 3abcc72d61e..00000000000--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-usage-limit-entitlement-provider.util.ts+++ /dev/null@@ -1,13 +0,0 @@-import { type DiscoveryService } from '@nestjs/core';--import { UsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service';-import { NoUsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/services/no-usage-limit-entitlement-provider.service';-import { findProviderInstance } from 'src/engine/core-modules/usage-limit/utils/find-provider-instance.util';--export const findUsageLimitEntitlementProvider = (- discoveryService: DiscoveryService,-): UsageLimitEntitlementProvider =>- findProviderInstance({- discoveryService,- providerClass: UsageLimitEntitlementProvider,- }) ?? new NoUsageLimitEntitlementProvider();diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.tsindex 2c07177af0a..ecc9d0efa35 100644--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts@@ -6,18 +6,16 @@ import {type OnModuleDestroy,type OnModuleInit,} from '@nestjs/common';-import { DiscoveryService } from '@nestjs/core';import { isDefined } from 'twenty-shared/utils';import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';+import { BillingCreditAllowanceService } from 'src/engine/core-modules/billing/services/billing-credit-allowance.service';import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';import { type UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.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 { buildUsageEventEnvelopes } from 'src/engine/core-modules/usage/utils/build-usage-event-envelopes';import { UsageRollupBuffer } from 'src/engine/core-modules/usage/utils/usage-rollup-buffer';import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';@@ -30,20 +28,15 @@ export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {private readonly buffer = new UsageRollupBuffer(MAX_BUFFERED_ROLLUPS);private flushTimer: NodeJS.Timeout | null = null;private pendingFlush: Promise<void> = Promise.resolve();- private creditAllowanceProvider: CreditAllowanceProvider;constructor(private readonly workspaceEventEmitter: WorkspaceEventEmitter,private readonly eventLogEmitterService: EventLogEmitterService,private readonly twentyConfigService: TwentyConfigService,- private readonly discoveryService: DiscoveryService,+ private readonly billingCreditAllowanceService: BillingCreditAllowanceService,) {}onModuleInit() {- this.creditAllowanceProvider = findCreditAllowanceProvider(- this.discoveryService,- );-this.flushTimer = setInterval(() => void this.flush(),this.twentyConfigService.get('USAGE_ROLLUP_FLUSH_INTERVAL_MS'),@@ -176,7 +169,9 @@ export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {workspaceId: string,): Promise<Date | undefined> {const period =- await this.creditAllowanceProvider.getCreditAllowancePeriod(workspaceId);+ await this.billingCreditAllowanceService.getCreditAllowancePeriod(+ workspaceId,+ );return period?.periodStart;}diff --git a/packages/twenty-server/src/engine/core-modules/usage/usage.module.ts b/packages/twenty-server/src/engine/core-modules/usage/usage.module.tsindex 2866803dce1..750a917e96f 100644--- a/packages/twenty-server/src/engine/core-modules/usage/usage.module.ts+++ b/packages/twenty-server/src/engine/core-modules/usage/usage.module.ts@@ -1,9 +1,9 @@/* @license Enterprise */import { Module } from '@nestjs/common';-import { DiscoveryModule } from '@nestjs/core';import { TypeOrmModule } from '@nestjs/typeorm';+import { BillingModule } from 'src/engine/core-modules/billing/billing.module';import { EventLogEmitterModule } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.module';import { UsageEventListener } from 'src/engine/core-modules/usage/listeners/usage-event.listener';import { UsageAnalyticsModule } from 'src/engine/core-modules/usage/usage-analytics.module';@@ -16,7 +16,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache@Module({imports: [UsageAnalyticsModule,- DiscoveryModule,+ BillingModule,EventLogEmitterModule,PermissionsModule,TypeOrmModule.forFeature([UserWorkspaceEntity]),diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.tsindex 92341667174..1843add7130 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts@@ -1,7 +1,7 @@import { Injectable, Logger } from '@nestjs/common';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';+import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';@@ -31,7 +31,7 @@ export class AiBillingService {constructor(private readonly usageRecorderService: UsageRecorderService,private readonly aiModelRegistryService: AiModelRegistryService,- private readonly billingUsageService: BillingUsageService,+ private readonly usageQuotaAdmissionService: UsageQuotaAdmissionService,private readonly usageLimitQuotaService: UsageLimitQuotaService,) {}@@ -44,7 +44,7 @@ export class AiBillingService {operationType: UsageOperationType;spenders: UsageSpenders;}): Promise<void> {- await this.billingUsageService.assertUsageAllowed({+ await this.usageQuotaAdmissionService.assertUsageAllowed({workspaceId,resourceType: UsageResourceType.AI,operationType,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.tsindex 21149513373..39f7e72ea1d 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts@@ -8,9 +8,9 @@ import {type WorkspacePersonEnrichment,} from 'twenty-shared/workspace';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';+import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';@@ -49,7 +49,7 @@ export class WorkspaceSetupChatService {constructor(private readonly twentyConfigService: TwentyConfigService,- private readonly billingUsageService: BillingUsageService,+ private readonly usageQuotaAdmissionService: UsageQuotaAdmissionService,private readonly aiModelRegistryService: AiModelRegistryService,private readonly userWorkspaceService: UserWorkspaceService,private readonly i18nService: I18nService,@@ -149,7 +149,7 @@ export class WorkspaceSetupChatService {}const hasAvailableCredits =- await this.billingUsageService.hasAvailableCredits(workspace.id);+ await this.usageQuotaAdmissionService.hasAvailableCredits(workspace.id);if (!hasAvailableCredits) {return { outcome: WorkspaceSetupChatOutcome.UNAVAILABLE, thread: null };diff --git a/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts b/packages/twenty-server/src/modules/emailing/services/email-billing.service.tsindex 5b8d5037f13..2411bc8e8a1 100644--- a/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts+++ b/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts@@ -1,8 +1,8 @@import { Injectable } from '@nestjs/common';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';+import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';@@ -20,7 +20,7 @@ type EmailSendScope = EmailUsageScope & { emailCount?: number };@Injectable()export class EmailBillingService {constructor(- private readonly billingUsageService: BillingUsageService,+ private readonly usageQuotaAdmissionService: UsageQuotaAdmissionService,private readonly usageLimitQuotaService: UsageLimitQuotaService,) {}@@ -29,7 +29,7 @@ export class EmailBillingService {spenders,emailCount,}: EmailSendScope): Promise<void> {- await this.billingUsageService.assertUsageAllowed({+ await this.usageQuotaAdmissionService.assertUsageAllowed({workspaceId,resourceType: UsageResourceType.EMAIL,operationType: UsageOperationType.EMAIL_SEND,@@ -43,7 +43,7 @@ export class EmailBillingService {spenders,emailCount,}: EmailSendScope): Promise<UsageRefusal | null> {- return this.billingUsageService.findUsageRefusal({+ return this.usageQuotaAdmissionService.findUsageRefusal({workspaceId,resourceType: UsageResourceType.EMAIL,operationType: UsageOperationType.EMAIL_SEND,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.tsindex 0c3ed4598ac..e03436894dc 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts@@ -14,8 +14,8 @@ import {WorkflowStepExecutorException,WorkflowStepExecutorExceptionCode,} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';+import { UsageQuotaAdmissionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-admission.service';import { isUsageRefusedError } from 'src/engine/core-modules/billing/utils/is-usage-refused-error.util';import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';@@ -71,7 +71,7 @@ export class WorkflowExecutorWorkspaceService {private readonly workflowCoreSyncService: WorkflowCoreSyncService,private readonly workflowActionFactory: WorkflowActionFactory,private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,- private readonly billingUsageService: BillingUsageService,+ private readonly usageQuotaAdmissionService: UsageQuotaAdmissionService,private readonly usageLimitQuotaService: UsageLimitQuotaService,private readonly featureFlagService: FeatureFlagService,private readonly exceptionHandlerService: ExceptionHandlerService,@@ -414,7 +414,7 @@ export class WorkflowExecutorWorkspaceService {billingSpenders: WorkflowBillingSpenders;}): Promise<WorkflowActionOutput | undefined> {try {- await this.billingUsageService.assertUsageAllowed({+ await this.usageQuotaAdmissionService.assertUsageAllowed({workspaceId,resourceType: UsageResourceType.WORKFLOW,operationType: UsageOperationType.WORKFLOW_EXECUTION,diff --git a/packages/twenty-server/test/integration/workspace-cache/billing-entitlements-cache.integration-spec.ts b/packages/twenty-server/test/integration/workspace-cache/billing-entitlements-cache.integration-spec.tsindex 860f65cf191..2a454bf0e7a 100644--- a/packages/twenty-server/test/integration/workspace-cache/billing-entitlements-cache.integration-spec.ts+++ b/packages/twenty-server/test/integration/workspace-cache/billing-entitlements-cache.integration-spec.ts@@ -2,8 +2,8 @@ import { isDefined } from 'twenty-shared/utils';import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';import { type BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';-import { type BillingUsageLimitEntitlementProvider } from 'src/engine/core-modules/billing/services/billing-usage-limit-entitlement-provider.service';import { type EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';+import { type UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';@@ -64,7 +64,7 @@ const isBillingEnabled = process.env.IS_BILLING_ENABLED === 'true';let originalEntitlements: { value: boolean }[];let workspaceCacheService: WorkspaceCacheService;let subscriptionService: BillingSubscriptionService;- let usageLimitProvider: BillingUsageLimitEntitlementProvider;+ let usageLimitEntitlementService: UsageLimitEntitlementService;let enterprisePlanService: EnterprisePlanService;const setUsageLimitEntitlement = async (value: boolean) => {@@ -95,9 +95,9 @@ const isBillingEnabled = process.env.IS_BILLING_ENABLED === 'true';getAppProviderByClassName<BillingSubscriptionService>('BillingSubscriptionService',);- usageLimitProvider =- getAppProviderByClassName<BillingUsageLimitEntitlementProvider>(- 'BillingUsageLimitEntitlementProvider',+ usageLimitEntitlementService =+ getAppProviderByClassName<UsageLimitEntitlementService>(+ 'UsageLimitEntitlementService',);enterprisePlanService = getAppProviderByClassName<EnterprisePlanService>('EnterprisePlanService',@@ -134,17 +134,23 @@ const isBillingEnabled = process.env.IS_BILLING_ENABLED === 'true';it('reuses cached rows until invalidation, then exposes a revoked entitlement to all readers', async () => {expect(- await usageLimitProvider.hasIntraWorkspaceLimitEntitlement(workspaceId),+ await usageLimitEntitlementService.isIntraWorkspaceLimitEntitled(+ workspaceId,+ ),).toBe(true);await setUsageLimitEntitlement(false);expect(- await usageLimitProvider.hasIntraWorkspaceLimitEntitlement(workspaceId),+ await usageLimitEntitlementService.isIntraWorkspaceLimitEntitled(+ workspaceId,+ ),).toBe(true);await refreshEntitlements();expect(- await usageLimitProvider.hasIntraWorkspaceLimitEntitlement(workspaceId),+ await usageLimitEntitlementService.isIntraWorkspaceLimitEntitled(+ workspaceId,+ ),).toBe(false);expect(await subscriptionService.getWorkspaceEntitlements(workspaceId),@@ -198,11 +204,15 @@ const isBillingEnabled = process.env.IS_BILLING_ENABLED === 'true';it('evaluates license validity again while the entitlement remains cached', async () => {expect(- await usageLimitProvider.hasIntraWorkspaceLimitEntitlement(workspaceId),+ await usageLimitEntitlementService.isIntraWorkspaceLimitEntitled(+ workspaceId,+ ),).toBe(true);jest.spyOn(enterprisePlanService, 'isValid').mockReturnValue(false);expect(- await usageLimitProvider.hasIntraWorkspaceLimitEntitlement(workspaceId),+ await usageLimitEntitlementService.isIntraWorkspaceLimitEntitled(+ workspaceId,+ ),).toBe(false);});@@ -211,7 +221,7 @@ const isBillingEnabled = process.env.IS_BILLING_ENABLED === 'true';.spyOn(workspaceCacheService, 'getOrRecompute').mockRejectedValueOnce(new Error('cache unavailable'));await expect(- usageLimitProvider.hasIntraWorkspaceLimitEntitlement(workspaceId),+ usageLimitEntitlementService.isIntraWorkspaceLimitEntitled(workspaceId),).rejects.toThrow('cache unavailable');});},