The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(usage) - credit allowance as a quota counter and enforcement wiring (#25279)
Etienne5533cec5242e
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex d46eb8f3733..f0b883b241e 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -1741,6 +1741,50 @@ type UsageAnalytics {userDailyUsage: UsageUserDaily}+type UsageLimit {+ id: UUID!+ resourceType: UsageResourceType!+ operationType: UsageOperationType!+ spenderType: String!+ spenderId: String+ limitKind: String!+ periodCount: Int!+ periodUnit: String!+ meter: String!+ limitValue: BigInt!+ burstValue: BigInt+ createdAt: DateTime!+ updatedAt: DateTime!+}++enum UsageResourceType {+ AI+ WORKFLOW+ APP+ STORAGE+ API+ LOGIC_FUNCTION+}++enum UsageOperationType {+ ALL+ AI_CHAT_TOKEN+ AI_WORKFLOW_TOKEN+ WORKFLOW_EXECUTION+ CODE_EXECUTION+ WEB_SEARCH+ CALL_RECORDING+ EMAIL_SEND+ API_REQUEST+ SUBSCRIPTION+}++"""+The `BigInt` scalar type represents non-fractional signed whole numeric values.+"""+scalar BigInt+type ApprovedAccessDomain {id: UUID!domain: String!@@ -1819,50 +1863,6 @@ type ConnectedAccountPublicDTO {connectionParameters: PublicImapSmtpCaldavConnectionParameters}-type UsageLimit {- id: UUID!- resourceType: UsageResourceType!- operationType: UsageOperationType!- spenderType: String!- spenderId: String- limitKind: String!- periodCount: Int!- periodUnit: String!- meter: String!- limitValue: BigInt!- burstValue: BigInt- createdAt: DateTime!- updatedAt: DateTime!-}--enum UsageResourceType {- AI- WORKFLOW- APP- STORAGE- API- LOGIC_FUNCTION-}--enum UsageOperationType {- ALL- AI_CHAT_TOKEN- AI_WORKFLOW_TOKEN- WORKFLOW_EXECUTION- CODE_EXECUTION- WEB_SEARCH- CALL_RECORDING- EMAIL_SEND- API_REQUEST- SUBSCRIPTION-}--"""-The `BigInt` scalar type represents non-fractional signed whole numeric values.-"""-scalar BigInt-type FeatureFlag {key: FeatureFlagKey!value: Boolean!@@ -1881,6 +1881,7 @@ enum FeatureFlagKey {IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLEDIS_API_RATE_LIMIT_V2_ENABLEDIS_MESSAGE_CALENDAR_TARGET_READ_ENABLED+ IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED}type WorkspaceUrls {diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 15b36f77878..b68adec862e 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -1403,6 +1403,27 @@ export interface UsageAnalytics {__typename: 'UsageAnalytics'}+export interface UsageLimit {+ id: Scalars['UUID']+ resourceType: UsageResourceType+ operationType: UsageOperationType+ spenderType: Scalars['String']+ spenderId?: Scalars['String']+ limitKind: Scalars['String']+ periodCount: Scalars['Int']+ periodUnit: Scalars['String']+ meter: Scalars['String']+ limitValue: Scalars['BigInt']+ burstValue?: Scalars['BigInt']+ createdAt: Scalars['DateTime']+ updatedAt: Scalars['DateTime']+ __typename: 'UsageLimit'+}++export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL'++export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'SUBSCRIPTION'+export interface ApprovedAccessDomain {id: Scalars['UUID']domain: Scalars['String']@@ -1485,34 +1506,13 @@ export interface ConnectedAccountPublicDTO {__typename: 'ConnectedAccountPublicDTO'}-export interface UsageLimit {- id: Scalars['UUID']- resourceType: UsageResourceType- operationType: UsageOperationType- spenderType: Scalars['String']- spenderId?: Scalars['String']- limitKind: Scalars['String']- periodCount: Scalars['Int']- periodUnit: Scalars['String']- meter: Scalars['String']- limitValue: Scalars['BigInt']- burstValue?: Scalars['BigInt']- createdAt: Scalars['DateTime']- updatedAt: Scalars['DateTime']- __typename: 'UsageLimit'-}--export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL'--export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'SUBSCRIPTION'-export interface FeatureFlag {key: FeatureFlagKeyvalue: Scalars['Boolean']__typename: 'FeatureFlag'}-export type FeatureFlagKey = 'IS_APP_CLAIMING_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_EMAIL_GROUP_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_VERSION_IN_CORE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED' | 'IS_API_RATE_LIMIT_V2_ENABLED' | 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED'+export type FeatureFlagKey = 'IS_APP_CLAIMING_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_EMAIL_GROUP_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_VERSION_IN_CORE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED' | 'IS_API_RATE_LIMIT_V2_ENABLED' | 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' | 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED'export interface WorkspaceUrls {customUrl?: Scalars['String']@@ -4856,6 +4856,24 @@ export interface UsageAnalyticsGenqlSelection{__scalar?: boolean | number}+export interface UsageLimitGenqlSelection{+ id?: boolean | number+ resourceType?: boolean | number+ operationType?: boolean | number+ spenderType?: boolean | number+ spenderId?: boolean | number+ limitKind?: boolean | number+ periodCount?: boolean | number+ periodUnit?: boolean | number+ meter?: boolean | number+ limitValue?: boolean | number+ burstValue?: boolean | number+ createdAt?: boolean | number+ updatedAt?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}+export interface ApprovedAccessDomainGenqlSelection{id?: boolean | numberdomain?: boolean | number@@ -4945,24 +4963,6 @@ export interface ConnectedAccountPublicDTOGenqlSelection{__scalar?: boolean | number}-export interface UsageLimitGenqlSelection{- id?: boolean | number- resourceType?: boolean | number- operationType?: boolean | number- spenderType?: boolean | number- spenderId?: boolean | number- limitKind?: boolean | number- periodCount?: boolean | number- periodUnit?: boolean | number- meter?: boolean | number- limitValue?: boolean | number- burstValue?: boolean | number- createdAt?: boolean | number- updatedAt?: boolean | number- __typename?: boolean | number- __scalar?: boolean | number-}-export interface FeatureFlagGenqlSelection{key?: boolean | numbervalue?: boolean | number@@ -8298,6 +8298,14 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null+ const UsageLimit_possibleTypes: string[] = ['UsageLimit']+ export const isUsageLimit = (obj?: { __typename?: any } | null): obj is UsageLimit => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageLimit"')+ return UsageLimit_possibleTypes.includes(obj.__typename)+ }+++const ApprovedAccessDomain_possibleTypes: string[] = ['ApprovedAccessDomain']export const isApprovedAccessDomain = (obj?: { __typename?: any } | null): obj is ApprovedAccessDomain => {if (!obj?.__typename) throw new Error('__typename is missing in "isApprovedAccessDomain"')@@ -8370,14 +8378,6 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null- const UsageLimit_possibleTypes: string[] = ['UsageLimit']- export const isUsageLimit = (obj?: { __typename?: any } | null): obj is UsageLimit => {- if (!obj?.__typename) throw new Error('__typename is missing in "isUsageLimit"')- return UsageLimit_possibleTypes.includes(obj.__typename)- }---const FeatureFlag_possibleTypes: string[] = ['FeatureFlag']export const isFeatureFlag = (obj?: { __typename?: any } | null): obj is FeatureFlag => {if (!obj?.__typename) throw new Error('__typename is missing in "isFeatureFlag"')@@ -10145,12 +10145,6 @@ export const enumDatabaseEventAction = {UPSERTED: 'UPSERTED' as const}-export const enumEmailConnectionSecurity = {- NONE: 'NONE' as const,- STARTTLS: 'STARTTLS' as const,- SSL_TLS: 'SSL_TLS' as const-}-export const enumUsageResourceType = {AI: 'AI' as const,WORKFLOW: 'WORKFLOW' as const,@@ -10174,6 +10168,12 @@ export const enumUsageOperationType = {SUBSCRIPTION: 'SUBSCRIPTION' as const}+export const enumEmailConnectionSecurity = {+ NONE: 'NONE' as const,+ STARTTLS: 'STARTTLS' as const,+ SSL_TLS: 'SSL_TLS' as const+}+export const enumFeatureFlagKey = {IS_APP_CLAIMING_ENABLED: 'IS_APP_CLAIMING_ENABLED' as const,IS_UNIQUE_INDEXES_ENABLED: 'IS_UNIQUE_INDEXES_ENABLED' as const,@@ -10186,7 +10186,8 @@ export const enumFeatureFlagKey = {IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED: 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' as const,IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED: 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED' as const,IS_API_RATE_LIMIT_V2_ENABLED: 'IS_API_RATE_LIMIT_V2_ENABLED' as const,- IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED: 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' as const+ IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED: 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED' as const,+ IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED: 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED' as const}export const enumIdentityProviderType = {diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex dac30c73b69..bb5b0580f17 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -54,10 +54,10 @@ export default {152,155,157,- 178,+ 172,+ 173,+ 174,182,- 183,- 184,186,193,194,@@ -3388,6 +3388,53 @@ export default {1]},+ "UsageLimit": {+ "id": [+ 3+ ],+ "resourceType": [+ 172+ ],+ "operationType": [+ 173+ ],+ "spenderType": [+ 1+ ],+ "spenderId": [+ 1+ ],+ "limitKind": [+ 1+ ],+ "periodCount": [+ 26+ ],+ "periodUnit": [+ 1+ ],+ "meter": [+ 1+ ],+ "limitValue": [+ 174+ ],+ "burstValue": [+ 174+ ],+ "createdAt": [+ 4+ ],+ "updatedAt": [+ 4+ ],+ "__typename": [+ 1+ ]+ },+ "UsageResourceType": {},+ "UsageOperationType": {},+ "BigInt": {},"ApprovedAccessDomain": {"id": [3@@ -3460,7 +3507,7 @@ export default {1],"result": [- 175+ 179],"__typename": [1@@ -3477,7 +3524,7 @@ export default {1],"connectionSecurity": [- 178+ 182],"__typename": [1@@ -3486,13 +3533,13 @@ export default {"EmailConnectionSecurity": {},"PublicImapSmtpCaldavConnectionParameters": {"IMAP": [- 177+ 181],"SMTP": [- 177+ 181],"CALDAV": [- 177+ 181],"__typename": [1@@ -3548,59 +3595,12 @@ export default {4],"connectionParameters": [- 179- ],- "__typename": [- 1- ]- },- "UsageLimit": {- "id": [- 3- ],- "resourceType": [- 182- ],- "operationType": [183],- "spenderType": [- 1- ],- "spenderId": [- 1- ],- "limitKind": [- 1- ],- "periodCount": [- 26- ],- "periodUnit": [- 1- ],- "meter": [- 1- ],- "limitValue": [- 184- ],- "burstValue": [- 184- ],- "createdAt": [- 4- ],- "updatedAt": [- 4- ],"__typename": [1]},- "UsageResourceType": {},- "UsageOperationType": {},- "BigInt": {},"FeatureFlag": {"key": [186@@ -5434,7 +5434,7 @@ export default {4],"connectedAccount": [- 180+ 184],"__typename": [1@@ -5633,7 +5633,7 @@ export default {1],"connectionSecurity": [- 178+ 182],"__typename": [1@@ -6766,7 +6766,7 @@ export default {}],"usageLimits": [- 181+ 171],"getViewFilterGroups": [54,@@ -6895,7 +6895,7 @@ export default {160],"myConnectedAccounts": [- 180+ 184],"applicationConnectionProviders": [126,@@ -6924,13 +6924,13 @@ export default {162],"getInviteSuggestions": [- 172+ 176],"findWorkspaceInvitations": [- 175+ 179],"getApprovedAccessDomains": [- 171+ 175],"getPageLayoutTabs": [122,@@ -7623,7 +7623,7 @@ export default {1],"operationTypes": [- 183+ 173],"__typename": [1@@ -8024,7 +8024,7 @@ export default {}],"upsertUsageLimit": [- 181,+ 171,{"input": [405,@@ -8354,7 +8354,7 @@ export default {26],"deleteConnectedAccount": [- 180,+ 184,{"id": [3,@@ -8454,7 +8454,7 @@ export default {166],"skipSyncEmailOnboardingStep": [- 174,+ 178,{"isAutoSkipped": [8,@@ -8463,7 +8463,7 @@ export default {}],"completeBookCallOnboardingStep": [- 174,+ 178,{"hasBookedCall": [8,@@ -8476,7 +8476,7 @@ export default {}],"triggerInstallAppsOnboardingStep": [- 174,+ 178,{"universalIdentifiers": [1,@@ -8489,7 +8489,7 @@ export default {}],"goBackToPreviousOnboardingStep": [- 173+ 177],"deleteWorkspaceInvitation": [1,@@ -8501,7 +8501,7 @@ export default {}],"resendWorkspaceInvitation": [- 176,+ 180,{"appTokenId": [1,@@ -8510,7 +8510,7 @@ export default {}],"sendInvitations": [- 176,+ 180,{"emails": [1,@@ -8522,7 +8522,7 @@ export default {}],"createApprovedAccessDomain": [- 171,+ 175,{"input": [442,@@ -8540,7 +8540,7 @@ export default {}],"validateApprovedAccessDomain": [- 171,+ 175,{"input": [444,@@ -10458,10 +10458,10 @@ export default {"Upload": {},"UpsertUsageLimitInput": {"resourceType": [- 182+ 172],"operationType": [- 183+ 173],"spenderType": [1@@ -10482,10 +10482,10 @@ export default {1],"limitValue": [- 184+ 174],"burstValue": [- 184+ 174],"__typename": [1@@ -13189,7 +13189,7 @@ export default {1],"connectionSecurity": [- 178+ 182],"__typename": [1diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex 1a0bacfb36e..5512ed1dbc0 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -407,6 +407,7 @@ export enum FeatureFlagKey {IS_JUNCTION_RELATIONS_ENABLED = 'IS_JUNCTION_RELATIONS_ENABLED',IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED = 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED',IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED = 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED',+ IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED = 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED',IS_REST_METADATA_API_NEW_FORMAT_DIRECT = 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT',IS_UNIQUE_INDEXES_ENABLED = 'IS_UNIQUE_INDEXES_ENABLED',IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED = 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED',diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 49071c8e35c..0956162cd05 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -1902,6 +1902,7 @@ export enum FeatureFlagKey {IS_JUNCTION_RELATIONS_ENABLED = 'IS_JUNCTION_RELATIONS_ENABLED',IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED = 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED',IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED = 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED',+ IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED = 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED',IS_REST_METADATA_API_NEW_FORMAT_DIRECT = 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT',IS_UNIQUE_INDEXES_ENABLED = 'IS_UNIQUE_INDEXES_ENABLED',IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED = 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED',diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.module.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.module.tsindex ab08ad88c58..3691b8f5c79 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.module.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/billing-webhook.module.ts@@ -11,6 +11,7 @@ import { BillingWebhookProductService } from 'src/engine/core-modules/billing-weimport { BillingWebhookSubscriptionScheduleService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-subscription-schedule.service';import { BillingWebhookSubscriptionService } from 'src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service';import { BillingModule } from 'src/engine/core-modules/billing/billing.module';+import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { BillingEntitlementEntity } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';import { BillingMeterEntity } from 'src/engine/core-modules/billing/entities/billing-meter.entity';@@ -39,6 +40,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cachePermissionsModule,WorkspaceModule,BillingModule,+ UsageLimitModule,WorkspaceCacheModule,TypeOrmModule.forFeature([BillingSubscriptionEntity,diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.tsindex ed6f6f525ef..a5403dc2ef1 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts@@ -25,6 +25,7 @@ import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entitimport { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';import { BillingWebhookEvent } from 'src/engine/core-modules/billing/enums/billing-webhook-events.enum';import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';import { type SubscriptionWithSchedule } from 'src/engine/core-modules/billing/types/billing-subscription-with-schedule.type';@@ -65,6 +66,7 @@ export class BillingWebhookSubscriptionService {private readonly workspaceService: WorkspaceService,private readonly stripeSubscriptionScheduleService: StripeSubscriptionScheduleService,private readonly billingUsageCacheService: BillingUsageCacheService,+ private readonly usageLimitQuotaService: UsageLimitQuotaService,private readonly workspaceCacheService: WorkspaceCacheService,) {}@@ -189,6 +191,8 @@ export class BillingWebhookSubscriptionService {'currentBillingSubscription',]);+ await this.usageLimitQuotaService.dropAllowanceCounter(workspace.id);+const shouldSuspendWorkspace = allLiveSubscriptions.every((customerSubscription) =>this.shouldSuspendWorkspace(customerSubscription),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 db315e7f6c4..f8fb166ecf3 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@@ -16,13 +16,17 @@ import {} from '@nestjs/common';import { Request } from 'express';-import { type CreditAvailability } from 'twenty-shared/application';+import {+ type CreditAvailability,+ type CreditUnavailableReason,+} from 'twenty-shared/application';import { ApiPath } from 'twenty-shared/types';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 { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';@@ -34,6 +38,15 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';const APP_BILLING_CHARGE_THROTTLE_LIMIT = 1000;const APP_BILLING_CHARGE_THROTTLE_TTL_MS = 60_000;+const CREDIT_UNAVAILABLE_REASON_BY_SERVER_REASON: Record<+ SubscriptionInactiveReason | 'NO_CREDITS',+ CreditUnavailableReason+> = {+ WORKSPACE_SUSPENDED: 'workspace-suspended',+ NO_SUBSCRIPTION: 'no-subscription',+ NO_CREDITS: 'no-credits',+};+@Controller(`${ApiPath.App}/billing`)@UseGuards(JwtAuthGuard, WorkspaceAuthGuard, NoPermissionGuard)export class AppBillingController {@@ -63,9 +76,20 @@ export class AppBillingController {APP_BILLING_CHARGE_THROTTLE_TTL_MS,);- return this.billingUsageService.getCreditAvailability({- workspaceId: request.workspace.id,- });+ const creditAvailability =+ await this.billingUsageService.getCreditAvailability(+ request.workspace.id,+ );++ return creditAvailability.hasAvailableCredits+ ? { hasAvailableCredits: true }+ : {+ hasAvailableCredits: false,+ reason:+ CREDIT_UNAVAILABLE_REASON_BY_SERVER_REASON[+ creditAvailability.reason+ ],+ };}@Post('charge')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 c45b46977ab..14e90eb3b67 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@@ -62,13 +62,13 @@ export class BillingSubscriptionItemResolver {}const creditAvailability =- await this.billingUsageService.getCreditAvailability({- workspaceId: billingSubscription.workspaceId,- });+ await this.billingUsageService.getCreditAvailability(+ billingSubscription.workspaceId,+ );return (!creditAvailability.hasAvailableCredits &&- creditAvailability.reason === 'no-credits'+ creditAvailability.reason === 'NO_CREDITS');} catch (error) {this.logger.warn(diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.exception.tsindex faa13a5b609..cd7a51e65d4 100644--- a/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts@@ -34,6 +34,7 @@ export enum BillingExceptionCode {BILLING_SUBSCRIPTION_PHASE_NOT_FOUND = 'BILLING_SUBSCRIPTION_PHASE_NOT_FOUND',BILLING_TOO_MUCH_SUBSCRIPTIONS_FOUND = 'BILLING_TOO_MUCH_SUBSCRIPTIONS_FOUND',BILLING_CREDITS_EXHAUSTED = 'BILLING_CREDITS_EXHAUSTED',+ BILLING_SUBSCRIPTION_INACTIVE = 'BILLING_SUBSCRIPTION_INACTIVE',BILLING_SUBSCRIPTION_NOT_CANCELED = 'BILLING_SUBSCRIPTION_NOT_CANCELED',BILLING_CREDIT_AMOUNT_INVALID = 'BILLING_CREDIT_AMOUNT_INVALID',BILLING_CREDIT_GRANT_NOT_FOUND = 'BILLING_CREDIT_GRANT_NOT_FOUND',@@ -98,6 +99,8 @@ const getBillingExceptionUserFriendlyMessage = (code: BillingExceptionCode) => {return msg`Multiple subscriptions found where one was expected.`;case BillingExceptionCode.BILLING_CREDITS_EXHAUSTED:return msg`You have exhausted your credits. Please upgrade your plan to continue.`;+ case BillingExceptionCode.BILLING_SUBSCRIPTION_INACTIVE:+ return msg`This workspace has no active subscription.`;case BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_CANCELED:return msg`Workspace cannot be deleted: subscription is not yet canceled.`;case BillingExceptionCode.BILLING_CREDIT_AMOUNT_INVALID: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 334748874f1..670e1eacbfb 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@@ -31,6 +31,7 @@ import { BillingPriceService } from 'src/engine/core-modules/billing/services/biimport { BillingProductService } from 'src/engine/core-modules/billing/services/billing-product.service';import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';import { BillingSubscriptionPhaseService } from 'src/engine/core-modules/billing/services/billing-subscription-phase.service';+import { BillingCreditAllowanceProvider } from 'src/engine/core-modules/billing/services/billing-credit-allowance-provider.service';import { 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 { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';@@ -50,6 +51,7 @@ 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 { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';@Module({@@ -78,6 +80,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache]),MetricsModule,EnterpriseModule,+ UsageLimitModule,WorkspaceIteratorModule,],providers: [@@ -98,6 +101,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheBillingSyncPlansDataCommand,BillingUsageService,BillingUsageCacheService,+ BillingCreditAllowanceProvider,BillingPriceService,BillingCreditRolloverService,BillingCreditGrantService,diff --git a/packages/twenty-server/src/engine/core-modules/billing/constants/subscription-inactive-reason-user-friendly-message.constant.ts b/packages/twenty-server/src/engine/core-modules/billing/constants/subscription-inactive-reason-user-friendly-message.constant.tsnew file mode 100644index 00000000000..62f1d2b1017--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/constants/subscription-inactive-reason-user-friendly-message.constant.ts@@ -0,0 +1,12 @@+import { msg } from '@lingui/core/macro';+import { type MessageDescriptor } from '@lingui/core';++import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';++export const SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE: Record<+ SubscriptionInactiveReason,+ MessageDescriptor+> = {+ WORKSPACE_SUSPENDED: msg`This workspace is suspended.`,+ NO_SUBSCRIPTION: msg`This workspace has no active subscription.`,+};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.tsnew file mode 100644index 00000000000..38617f5592a--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-allowance-provider.service.ts@@ -0,0 +1,92 @@+/* @license Enterprise */++import { Injectable, Logger } from '@nestjs/common';++import { isDefined } from 'twenty-shared/utils';++import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.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';+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 {+ private readonly logger = new Logger(BillingCreditAllowanceProvider.name);++ constructor(+ private readonly twentyConfigService: TwentyConfigService,+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly billingSubscriptionService: BillingSubscriptionService,+ private readonly billingCreditGrantService: BillingCreditGrantService,+ private readonly billingUsageService: BillingUsageService,+ ) {+ super();+ }++ async isCreditAllowanceEnabled(workspaceId: string): Promise<boolean> {+ return this.billingUsageService.isAllowanceCounterEnabled(workspaceId);+ }++ async getCreditAllowancePeriod(+ workspaceId: string,+ ): Promise<UsagePeriod | null> {+ if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {+ return null;+ }++ const { currentBillingSubscription } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'currentBillingSubscription',+ ]);++ if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {+ return null;+ }++ return {+ periodStart: new Date(currentBillingSubscription.currentPeriodStart),+ periodEnd: new Date(currentBillingSubscription.currentPeriodEnd),+ };+ }++ async getCreditAllowance(+ workspaceId: string,+ ): Promise<CreditAllowance | null> {+ if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {+ return null;+ }++ try {+ const subscription =+ await this.billingSubscriptionService.getCurrentBillingSubscription({+ workspaceId,+ });++ if (!isDefined(subscription)) {+ return null;+ }++ const creditBalanceMicro =+ await this.billingCreditGrantService.getActiveCreditsMicro(workspaceId);++ return {+ periodStart: subscription.currentPeriodStart,+ periodEnd: subscription.currentPeriodEnd,+ allowanceMicro:+ this.billingUsageService.getResourceUsageCap(subscription) ++ creditBalanceMicro,+ };+ } catch (error) {+ this.logger.error(+ `Could not compute allowance for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,+ );++ return null;+ }+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.tsindex d8e3b5f7c85..6a3deeae76a 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts@@ -16,7 +16,7 @@ import { computeCarryForwardGrants } from 'src/engine/core-modules/billing/utilsimport { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';-export type ProcessRolloverParams = {+type ProcessRolloverParams = {workspaceId: string;closingPeriodStart: Date;closingPeriodEnd: Date;@@ -119,9 +119,6 @@ export class BillingCreditRolloverService {let carriedForwardMicro = 0;let hasReplayedGrant = false;- // Writes the grants directly rather than through grantCredits: the cache,- // cap flag and workspace cache only need refreshing once for the whole- // transition, and this runs inside a Stripe webhook.for (const carryForwardGrant of carryForwardGrants) {const grant = await this.billingCreditGrantService.createGrant({workspaceId,@@ -146,16 +143,6 @@ export class BillingCreditRolloverService {}}- // A replay only tells us the rows already exist, not whether the delivery- // that wrote them got as far as the counter. Stripe also redelivers events- // it already handled successfully, and rebuilding then would throw away a- // correct warm counter and recompute it from ClickHouse, crediting back- // whatever usage has not been ingested yet. So the transition records under- // adjustmentKey that it moved the counter, and the refresh rebuilds only- // when that record is absent.- //- // Runs unconditionally: closing the old grants moves the balance on its- // own, so a period where everything was spent still needs the refresh.await this.billingCreditService.refreshWorkspaceCreditState({workspaceId,availableDeltaMicro: carriedForwardMicro,@@ -165,8 +152,6 @@ export class BillingCreditRolloverService {}}-// Scopes the completion marker to one period transition, so only a redelivery-// of that transition can see it.const buildRolloverAdjustmentKey = (nextPeriodStart: Date): string =>`rollover:${nextPeriodStart.toISOString()}`;diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.tsindex 82c1319dfc6..aee5e100469 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts@@ -11,10 +11,12 @@ import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enuimport { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';+import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';import { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';// Used when a workspace has no subscription yet, which happens for rewards@@ -22,7 +24,7 @@ import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/works// aligned on the real billing period.const PROVISIONAL_GRANT_VALIDITY_IN_DAYS = 31;-export type GrantCreditsParams = {+type GrantCreditsParams = {workspaceId: string;amountMicro: number;type: BillingCreditGrantType;@@ -43,8 +45,10 @@ export class BillingCreditService {private readonly billingCreditGrantService: BillingCreditGrantService,private readonly billingSubscriptionService: BillingSubscriptionService,private readonly billingUsageCacheService: BillingUsageCacheService,+ private readonly billingUsageService: BillingUsageService,private readonly cacheLockService: CacheLockService,private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly usageLimitQuotaService: UsageLimitQuotaService,) {}async grantCredits(@@ -56,10 +60,6 @@ export class BillingCreditService {const { workspaceId } = params;- // Writing the row and moving the counter are two steps, and a reader that- // computes availability between them counts the grant from the ledger and- // then has it added a second time. Locking keeps the pair indivisible for- // anything else touching this workspace's credit state.return this.cacheLockService.withLock(() => this.writeGrantAndRefreshState(params),buildBillingCreditStateLockKey(workspaceId),@@ -71,18 +71,12 @@ export class BillingCreditService {): Promise<BillingCreditGrantEntity | null> {const { workspaceId, amountMicro } = params;- // Read once for the whole write: the validity window and the state refresh- // both need it, and both run inside the lock. Reading it here rather than- // before the lock is what keeps a grant that waited behind a period- // transition from carrying the period the wait started in, which would- // land it already expired while its amount still went onto the counter for- // the period that had meanwhile opened.const subscription =await this.billingSubscriptionService.getCurrentBillingSubscription({workspaceId,});- const { effectiveAt, expiresAt } = resolveGrantValidity(+ const { effectiveAt, expiresAt } = computeGrantValidity(params,subscription,);@@ -93,21 +87,11 @@ export class BillingCreditService {expiresAt,});- // A replay only means the ledger row exists, not that the projections- // built from it do: the first attempt can have inserted the row and then- // failed on the refresh, and onboarding callers swallow that error. Repair- // rather than return, with no counter delta since the original attempt may- // already have applied it.if (!isDefined(grant)) {this.logger.log(`Replayed credit grant for workspace ${workspaceId} (idempotency key ${params.idempotencyKey}), repairing derived state`,);- // Rebuilding from the ledger can overstate the balance by whatever- // usage ClickHouse has not ingested yet, and that value then stands for- // the period. Accepted here because the alternative is a grant that- // stays invisible for the whole period, and erring high is the direction- // the grant intended.await this.refreshWorkspaceCreditState({workspaceId,availableDeltaMicro: 0,@@ -165,15 +149,6 @@ export class BillingCreditService {const adjustmentKey = buildRevocationAdjustmentKey(grantId);- // A retried revocation must not take the same credits off the usage- // counter twice, which would block a workspace that still has credits.- // Whether the attempt that did revoke got as far as the counter is- // recorded under adjustmentKey, so the refresh can tell the two apart:- // already applied means repair the rest and leave the counter alone, never- // applied means rebuild from the ledger. Guessing either way is wrong,- // since always rebuilding freezes ClickHouse lag in as extra credit on- // every double click and never rebuilding leaves revoked credits spendable- // until the period ends.if (!wasRevokedNow) {await this.refreshWorkspaceCreditState({workspaceId,@@ -185,11 +160,6 @@ export class BillingCreditService {return grant;}- // Only credits the counter actually holds may come off it. The mutation- // accepts any grant id, and a grant can expire between the admin panel- // rendering and the revoke landing, so subtracting unconditionally would- // take away credits that were never counted and block usage until the- // period ends.const revokedAtMs = (grant.revokedAt ?? new Date()).getTime();const wasActiveWhenRevoked =grant.effectiveAt.getTime() <= revokedAtMs &&@@ -204,12 +174,6 @@ export class BillingCreditService {return grant;}- // Keeps everything that reads a credit balance consistent with the ledger:- // the Redis counter that gates usage and the cached subscription the front- // reads. Public so a caller writing several grants at once pays for this- // once; such a caller must hold buildBillingCreditStateLockKey for its own- // ledger writes and this refresh together, which is why this does not take- // the lock itself.async refreshWorkspaceCreditState({workspaceId,availableDeltaMicro,@@ -219,12 +183,8 @@ export class BillingCreditService {}: {workspaceId: string;availableDeltaMicro: number;- // A replay cannot know how far the original attempt got, so the counter is- // recomputed from the ledger unless adjustmentKey says it already moved.isReplay?: boolean;- // Names a one-off adjustment so a retry can see it already landed.adjustmentKey?: string;- // Saves a re-read for a caller that already has it in hand.subscription?: BillingSubscriptionEntity;}): Promise<void> {const subscription =@@ -237,12 +197,51 @@ export class BillingCreditService {return;}- // Deliberately not getBillingSubscriptionPeriod, which reports the trial- // window while trialing: every usage path keys this counter off- // currentPeriodStart, so taking the period from anywhere else would move a- // key the gate never reads.+ // Not getBillingSubscriptionPeriod: while trialing it reports the trial window, and the counter is keyed off currentPeriodStart.const periodStart = subscription.currentPeriodStart;+ if (await this.billingUsageService.isAllowanceCounterEnabled(workspaceId)) {+ await this.billingUsageCacheService.invalidateAvailableCredits(+ workspaceId,+ periodStart,+ );+ } else {+ await this.adjustAvailableCreditsCounter({+ workspaceId,+ periodStart,+ periodEnd: subscription.currentPeriodEnd,+ availableDeltaMicro,+ isReplay,+ adjustmentKey,+ });+ }++ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [+ 'currentBillingSubscription',+ ]);++ const isPureReplay = isReplay && availableDeltaMicro === 0;++ if (!isPureReplay) {+ await this.usageLimitQuotaService.dropAllowanceCounter(workspaceId);+ }+ }++ private async adjustAvailableCreditsCounter({+ workspaceId,+ periodStart,+ periodEnd,+ availableDeltaMicro,+ isReplay,+ adjustmentKey,+ }: {+ workspaceId: string;+ periodStart: Date;+ periodEnd: Date;+ availableDeltaMicro: number;+ isReplay: boolean;+ adjustmentKey?: string;+ }): Promise<void> {const rebuildCounter =isReplay &&(!isDefined(adjustmentKey) ||@@ -262,17 +261,11 @@ export class BillingCreditService {await this.billingUsageCacheService.markCounterAdjustmentApplied(workspaceId,adjustmentKey,- subscription.currentPeriodEnd,+ periodEnd,);}-- await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [- 'currentBillingSubscription',- ]);}- // Returns what the counter holds afterwards, or null when there is no warm- // counter to speak for the workspace.private async applyCounterWrite({workspaceId,periodStart,@@ -297,18 +290,12 @@ export class BillingCreditService {return null;}- // Adjusting the warm counter instead of flushing it avoids recomputing- // from ClickHouse while its async inserts for recent usage are still- // landing, which would credit the workspace for usage it already spent.const cachedAvailableCredits =await this.billingUsageCacheService.getAvailableCredits(workspaceId,periodStart,);- // Nothing to do when the counter is cold. A reader can only warm it while- // holding this same lock, so it cannot be mid-computation now, and the- // next one to take the lock reads a ledger that already has this write.if (!isDefined(cachedAvailableCredits)) {return null;}@@ -323,12 +310,10 @@ export class BillingCreditService {}}-// Scopes the completion marker to one revocation, so retrying it is the only-// thing that can see it.const buildRevocationAdjustmentKey = (grantId: string): string =>`revoke:${grantId}`;-const resolveGrantValidity = (+const computeGrantValidity = (params: GrantCreditsParams,subscription: BillingSubscriptionEntity | undefined,): { effectiveAt: Date; expiresAt: Date } => {diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.tsindex a7c1cfd315f..6e6cce0df26 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts@@ -32,6 +32,7 @@ import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billinimport { BillingPlanService } from 'src/engine/core-modules/billing/services/billing-plan.service';import { BillingPriceService } from 'src/engine/core-modules/billing/services/billing-price.service';import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';@@ -74,6 +75,7 @@ export class BillingSubscriptionService {private readonly enterprisePlanService: EnterprisePlanService,private readonly workspaceCacheService: WorkspaceCacheService,private readonly billingUsageCacheService: BillingUsageCacheService,+ private readonly usageLimitQuotaService: UsageLimitQuotaService,) {}async getBillingSubscriptions(workspaceId: string) {@@ -94,6 +96,7 @@ export class BillingSubscriptionService {relations: ['billingSubscriptionItems','billingSubscriptionItems.billingProduct',+ 'billingSubscriptionItems.billingProduct.billingPrices',],};@@ -300,6 +303,8 @@ export class BillingSubscriptionService {'currentBillingSubscription',]);+ await this.usageLimitQuotaService.dropAllowanceCounter(workspace.id);+return {status: getSubscriptionStatus(updatedSubscription.status),hasPaymentMethod: true,diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.tsindex a99c7b118be..dd6e5ba14d3 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts@@ -26,8 +26,6 @@ export class BillingUsageCacheService {);}- // Callers must hold buildBillingCreditStateLockKey: that is what stops a- // value computed before a grant landed from being installed after it.async warmAvailableCredits(workspaceId: string,periodStart: Date | string,@@ -64,7 +62,6 @@ export class BillingUsageCacheService {);}- // Signed: usage moves it down, a grant moves it up.async adjustAvailableCredits(workspaceId: string,periodStart: Date | string,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 5e85d47db2a..541fbe541cc 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@@ -2,6 +2,7 @@import { Injectable, Logger } from '@nestjs/common';+import { FeatureFlagKey } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { WorkspaceActivationStatus } from 'twenty-shared/workspace';@@ -13,6 +14,7 @@ import {BillingExceptionCode,} from 'src/engine/core-modules/billing/billing.exception';import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';+import { SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE } from 'src/engine/core-modules/billing/constants/subscription-inactive-reason-user-friendly-message.constant';import { type BillingResourceCreditUsageDTO } from 'src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto';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';@@ -21,16 +23,24 @@ import { BillingCreditGrantService } from 'src/engine/core-modules/billing/serviimport { 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 { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';-import { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';-import { isValidCreditAmountMicro } from 'src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util';+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 { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';+import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';import {CacheLockException,CacheLockExceptionCode,} from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';+import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.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 { 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';import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';@@ -40,27 +50,24 @@ type UsageSumRow = {total: string | number | null;};+type UsageQuotaScope = {+ workspaceId: string;+ resourceType: UsageResourceType;+ operationType: UsageOperationType;+ spenders: UsageSpenders;+};+type AvailableCreditsParams = {workspaceId: string;currentPeriodStart: Date;currentPeriodEnd: Date;};-type ResolvedAvailableCredits = {+type AvailableCreditsRead = {availableCredits: number;isCounterWarm: boolean;};-export type CreditAvailability =- | { hasAvailableCredits: true }- | {- hasAvailableCredits: false;- reason: 'workspace-suspended' | 'no-subscription' | 'no-credits';- };--// This gate runs before every credit-consuming execution, so it waits far less-// than a writer does and falls back to computing unlocked rather than failing-// the execution outright.const AVAILABLE_CREDITS_WARM_UP_LOCK_OPTIONS = {ms: 50,maxRetries: 20,@@ -82,22 +89,156 @@ export class BillingUsageService {private readonly clickHouseService: ClickHouseService,private readonly cacheLockService: CacheLockService,private readonly coreEntityCacheService: CoreEntityCacheService,+ private readonly featureFlagService: FeatureFlagService,+ private readonly usageLimitQuotaService: UsageLimitQuotaService,) {}- async canFeatureBeUsed(workspaceId: string): Promise<boolean> {- if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {- return true;+ async isAllowanceCounterEnabled(workspaceId: string): Promise<boolean> {+ return this.featureFlagService.isFeatureEnabled(+ FeatureFlagKey.IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED,+ workspaceId,+ );+ }++ private async isAvailableCreditsCounterEnabled(+ workspaceId: string,+ ): Promise<boolean> {+ return (+ this.twentyConfigService.get('IS_BILLING_ENABLED') &&+ !(await this.isAllowanceCounterEnabled(workspaceId))+ );+ }++ async assertUsageAllowed({+ workspaceId,+ resourceType,+ operationType,+ spenders,+ }: UsageQuotaScope): Promise<void> {+ await this.assertSubscriptionActive(workspaceId);++ if (await this.isAvailableCreditsCounterEnabled(workspaceId)) {+ await this.assertAvailableCreditsNotExhausted(workspaceId);}- const { currentBillingSubscription } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'currentBillingSubscription',- ]);+ await this.usageLimitQuotaService.assertQuotaNotExhausted({+ workspaceId,+ resourceType,+ operationType,+ spenders,+ });+ }- return (- currentBillingSubscription !== NO_BILLING_SUBSCRIPTION &&- currentBillingSubscription.status !== SubscriptionStatus.Canceled+ async consumeUsageQuota({+ workspaceId,+ resourceType,+ operationType,+ spenders,+ cost,+ }: UsageQuotaScope & { cost: QuotaCost }): Promise<{+ hasNoMoreAvailableCredits: boolean;+ }> {+ const { exhausted } = await this.usageLimitQuotaService.consumeQuota({+ workspaceId,+ resourceType,+ operationType,+ spenders,+ cost,+ });++ const isAllowanceExhausted = exhausted.some(+ (scope) => scope.exhaustedKind === 'allowance',);++ if (!(await this.isAvailableCreditsCounterEnabled(workspaceId))) {+ return { hasNoMoreAvailableCredits: isAllowanceExhausted };+ }++ const availableCredits = await this.decrementAvailableCreditsInCache({+ workspaceId,+ usedCredits: cost.creditsUsedMicro,+ });++ return {+ hasNoMoreAvailableCredits: isAllowanceExhausted || availableCredits <= 0,+ };+ }++ async getSubscriptionInactiveReason(+ workspaceId: string,+ ): Promise<SubscriptionInactiveReason | null> {+ if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {+ return null;+ }++ const workspace = await this.coreEntityCacheService.get(+ 'workspaceEntity',+ workspaceId,+ );++ if (+ isDefined(workspace) &&+ workspace.activationStatus === WorkspaceActivationStatus.SUSPENDED+ ) {+ return 'WORKSPACE_SUSPENDED';+ }++ const currentBillingSubscription =+ await this.getCachedCurrentBillingSubscription(workspaceId);++ if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {+ return 'NO_SUBSCRIPTION';+ }++ return null;+ }++ async assertSubscriptionActive(workspaceId: string): Promise<void> {+ const subscriptionInactiveReason =+ await this.getSubscriptionInactiveReason(workspaceId);++ if (isDefined(subscriptionInactiveReason)) {+ throw new BillingException(+ `Workspace ${workspaceId} has no active subscription: ${subscriptionInactiveReason}`,+ BillingExceptionCode.BILLING_SUBSCRIPTION_INACTIVE,+ {+ userFriendlyMessage:+ SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE[+ subscriptionInactiveReason+ ],+ },+ );+ }+ }++ async getCreditAvailability(+ workspaceId: string,+ ): Promise<CreditAvailability> {+ const subscriptionInactiveReason =+ await this.getSubscriptionInactiveReason(workspaceId);++ if (isDefined(subscriptionInactiveReason)) {+ return { hasAvailableCredits: false, reason: subscriptionInactiveReason };+ }++ const remainingMicro = (await this.isAllowanceCounterEnabled(workspaceId))+ ? await this.usageLimitQuotaService.getAllowanceRemainingMicro(+ workspaceId,+ )+ : await this.getAvailableCreditsOrNull(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(@@ -242,17 +383,49 @@ export class BillingUsageService {return Number(resourceCreditPrice.metadata?.credit_amount ?? 0);}- async decrementAvailableCreditsInCache({+ private async assertAvailableCreditsNotExhausted(+ workspaceId: string,+ ): Promise<void> {+ const availableCredits = await this.getAvailableCreditsOrNull(workspaceId);++ if (isDefined(availableCredits) && availableCredits <= 0) {+ throw new BillingException(+ 'Credits exhausted',+ BillingExceptionCode.BILLING_CREDITS_EXHAUSTED,+ );+ }+ }++ private async getAvailableCreditsOrNull(+ workspaceId: string,+ ): Promise<number | null> {+ if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {+ return null;+ }++ const currentBillingSubscription =+ await this.getCachedCurrentBillingSubscription(workspaceId);++ if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {+ return null;+ }++ const { availableCredits } = await this.getOrWarmAvailableCredits({+ workspaceId: currentBillingSubscription.workspaceId,+ currentPeriodStart: currentBillingSubscription.currentPeriodStart,+ currentPeriodEnd: currentBillingSubscription.currentPeriodEnd,+ });++ return availableCredits;+ }++ private async decrementAvailableCreditsInCache({workspaceId,usedCredits,- currentBillingSubscription: providedCurrentBillingSubscription,}: {workspaceId: string;usedCredits: number;- currentBillingSubscription?: CurrentBillingSubscription;}): Promise<number> {- // Callers derive this from durations and token counts, so clamp at the one- // place that writes the counter rather than trusting each of them.const creditsToDecrement = isValidCreditAmountMicro(usedCredits)? usedCredits: 0;@@ -264,10 +437,7 @@ export class BillingUsageService {}const currentBillingSubscription =- await this.resolveCurrentBillingSubscription({- workspaceId,- providedCurrentBillingSubscription,- });+ await this.getCachedCurrentBillingSubscription(workspaceId);if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {return 0;@@ -276,16 +446,12 @@ export class BillingUsageService {const { currentPeriodStart, currentPeriodEnd } = currentBillingSubscription;const { availableCredits, isCounterWarm } =- await this.resolveAvailableCredits({+ await this.getOrWarmAvailableCredits({workspaceId,currentPeriodStart,currentPeriodEnd,});- // A counter held stale by a recent grant must not be created from a value- // that may predate it: incrementing an absent key would install- // -usedCredits as the whole balance. Compute this turn locally instead and- // let the next read rebuild once the marker lapses.return isCounterWarm? await this.billingUsageCacheService.adjustAvailableCredits(workspaceId,@@ -295,15 +461,9 @@ export class BillingUsageService {: availableCredits - creditsToDecrement;}- // Warming is a read of the ledger followed by a write of what it implies, so- // a grant landing in between would be counted from the ledger here and then- // added to the counter again by the grant itself. Taking the writers' lock on- // the cold path closes that; a hit returns before the lock, keeping the warm- // path, which is the overwhelming majority of calls, free of Redis round- // trips.private async readWarmAvailableCredits(params: AvailableCreditsParams,- ): Promise<ResolvedAvailableCredits | undefined> {+ ): Promise<AvailableCreditsRead | undefined> {const availableCredits =await this.billingUsageCacheService.getAvailableCredits(params.workspaceId,@@ -315,9 +475,9 @@ export class BillingUsageService {: undefined;}- private async resolveAvailableCredits(+ private async getOrWarmAvailableCredits(params: AvailableCreditsParams,- ): Promise<ResolvedAvailableCredits> {+ ): Promise<AvailableCreditsRead> {const warmAvailableCredits = await this.readWarmAvailableCredits(params);if (isDefined(warmAvailableCredits)) {@@ -327,8 +487,6 @@ export class BillingUsageService {try {return await this.cacheLockService.withLock(async () =>- // Another reader may have warmed it while this one waited, so a burst- // of cold reads pays for ClickHouse once rather than once each.(await this.readWarmAvailableCredits(params)) ??(await this.computeAndWarmAvailableCredits(params)),buildBillingCreditStateLockKey(params.workspaceId),@@ -342,10 +500,6 @@ export class BillingUsageService {throw error;}- // Failing the execution because a grant is being written would be worse- // than answering from a value this call computed itself. Deliberately- // does not warm: holding the lock is what makes installing a computed- // value safe, so the counter stays cold until an uncontended read.this.logger.warn(`Computing available credits for workspace ${params.workspaceId} without the credit state lock: ${error.message}`,);@@ -359,7 +513,7 @@ export class BillingUsageService {private async computeAndWarmAvailableCredits(params: AvailableCreditsParams,- ): Promise<ResolvedAvailableCredits> {+ ): Promise<AvailableCreditsRead> {const availableCredits =await this.getAvailableCreditsFromClickHouse(params);@@ -373,71 +527,6 @@ export class BillingUsageService {return { availableCredits, isCounterWarm: true };}- async getCreditAvailability({- workspaceId,- currentBillingSubscription: providedCurrentBillingSubscription,- }: {- workspaceId: string;- currentBillingSubscription?: CurrentBillingSubscription;- }): Promise<CreditAvailability> {- if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {- return { hasAvailableCredits: true };- }-- const workspace = await this.coreEntityCacheService.get(- 'workspaceEntity',- workspaceId,- );-- if (- isDefined(workspace) &&- workspace.activationStatus === WorkspaceActivationStatus.SUSPENDED- ) {- return { hasAvailableCredits: false, reason: 'workspace-suspended' };- }-- const currentBillingSubscription =- await this.resolveCurrentBillingSubscription({- workspaceId,- providedCurrentBillingSubscription,- });-- if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {- return { hasAvailableCredits: false, reason: 'no-subscription' };- }-- const subscription = currentBillingSubscription;-- const { availableCredits } = await this.resolveAvailableCredits({- workspaceId: subscription.workspaceId,- currentPeriodStart: subscription.currentPeriodStart,- currentPeriodEnd: subscription.currentPeriodEnd,- });-- return availableCredits > 0- ? { hasAvailableCredits: true }- : { hasAvailableCredits: false, reason: 'no-credits' };- }-- async hasAvailableCredits(workspaceId: string): Promise<boolean> {- const { hasAvailableCredits } = await this.getCreditAvailability({- workspaceId,- });-- return hasAvailableCredits;- }-- async hasAvailableCreditsOrThrow(workspaceId: string): Promise<void> {- const hasCredits = await this.hasAvailableCredits(workspaceId);-- if (!hasCredits) {- throw new BillingException(- 'Credits exhausted',- BillingExceptionCode.BILLING_CREDITS_EXHAUSTED,- );- }- }-// Returns null when usage could not be read. ClickHouseService.select// swallows query errors and returns [], but a bare sum() aggregate always// yields exactly one row, so an empty result means the read failed rather@@ -504,20 +593,14 @@ export class BillingUsageService {return usedMicro ?? 0;}- async resolveCurrentBillingSubscription({- workspaceId,- providedCurrentBillingSubscription,- }: {- workspaceId: string;- providedCurrentBillingSubscription?: CurrentBillingSubscription;- }): Promise<CurrentBillingSubscription> {- return (- providedCurrentBillingSubscription ??- (- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'currentBillingSubscription',- ])- ).currentBillingSubscription- );+ async getCachedCurrentBillingSubscription(+ workspaceId: string,+ ): Promise<CurrentBillingSubscription> {+ const { currentBillingSubscription } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'currentBillingSubscription',+ ]);++ return currentBillingSubscription;}}diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/credit-availability.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/credit-availability.type.tsnew file mode 100644index 00000000000..fc9f5b44d82--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/types/credit-availability.type.ts@@ -0,0 +1,8 @@+import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';++export type CreditAvailability =+ | { hasAvailableCredits: true }+ | {+ hasAvailableCredits: false;+ reason: SubscriptionInactiveReason | 'NO_CREDITS';+ };diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/subscription-inactive-reason.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/subscription-inactive-reason.type.tsnew file mode 100644index 00000000000..f047a82c4ff--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/types/subscription-inactive-reason.type.ts@@ -0,0 +1,3 @@+export type SubscriptionInactiveReason =+ | 'WORKSPACE_SUSPENDED'+ | 'NO_SUBSCRIPTION';diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.tsindex 63202b6b01c..504db8119ef 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts@@ -1,6 +1,3 @@-// Records that a one-off adjustment (a revocation, a period transition) already-// moved the counter, so a retry can tell "already applied" from "never got that-// far".export const buildBillingUsageCounterAdjustmentKey = (workspaceId: string,adjustmentKey: string,diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.tsindex 71024bb96bf..a3bb7e7636b 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts@@ -31,6 +31,7 @@ export const getBillingExceptionStatusCode = (case BillingExceptionCode.BILLING_SUBSCRIPTION_ALREADY_EXISTS:return 400;case BillingExceptionCode.BILLING_CREDITS_EXHAUSTED:+ case BillingExceptionCode.BILLING_SUBSCRIPTION_INACTIVE:case BillingExceptionCode.BILLING_UPGRADE_INVOICE_PAYMENT_FAILED:return 402;case BillingExceptionCode.BILLING_CUSTOMER_EVENT_WORKSPACE_NOT_FOUND: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 aa9ea9dc0c4..58293abdbbc 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@@ -31,9 +31,7 @@ import { type ApplicationVariableCacheMaps } from 'src/engine/core-modules/appliimport { 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 { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';-import { BillingService } from 'src/engine/core-modules/billing/services/billing.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';@@ -95,7 +93,6 @@ export class LogicFunctionExecutorService {private readonly eventLogLiveService: EventLogLiveService,private readonly eventLogEmitterService: EventLogEmitterService,private readonly usageRecorderService: UsageRecorderService,- private readonly billingService: BillingService,private readonly billingUsageService: BillingUsageService,private readonly featureFlagService: FeatureFlagService,private readonly workspaceDomainsService: WorkspaceDomainsService,@@ -631,28 +628,21 @@ export class LogicFunctionExecutorService {const totalCreditsMicro = invocationCreditsMicro + durationCreditsMicro;- if (this.billingService.isBillingEnabled()) {- const { currentBillingSubscription } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'currentBillingSubscription',- ]);-- if (- currentBillingSubscription !== NO_BILLING_SUBSCRIPTION &&- totalCreditsMicro > 0- ) {- await this.billingUsageService.decrementAvailableCreditsInCache({- workspaceId,- usedCredits: totalCreditsMicro,- });- }- }-const spenders = {logicFunctionId: flatLogicFunction.id,applicationId: flatApplication.id,};+ if (totalCreditsMicro > 0) {+ await this.billingUsageService.consumeUsageQuota({+ workspaceId,+ resourceType: UsageResourceType.LOGIC_FUNCTION,+ operationType: UsageOperationType.CODE_EXECUTION,+ spenders,+ cost: { creditsUsedMicro: totalCreditsMicro, quantity: 1 },+ });+ }+await this.usageRecorderService.record(workspaceId, [{resourceType: UsageResourceType.LOGIC_FUNCTION,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.tsindex 3d5af75882f..964874b072a 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@@ -5,6 +5,8 @@ import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usag@Injectable()export abstract class CreditAllowanceProvider {+ abstract isCreditAllowanceEnabled(workspaceId: string): Promise<boolean>;+abstract getCreditAllowancePeriod(workspaceId: string,): Promise<UsagePeriod | null>;diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.tsindex 270df7178a9..98cfd1bd254 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts@@ -40,6 +40,7 @@ const ALLOWANCE_PERIOD = {};class TestCreditAllowanceProvider extends CreditAllowanceProvider {+ isCreditAllowanceEnabled = jest.fn().mockResolvedValue(true);getCreditAllowancePeriod = jest.fn().mockResolvedValue(null);getCreditAllowance = jest.fn().mockResolvedValue(null);}@@ -250,14 +251,31 @@ describe('UsageLimitQuotaService', () => {});});- it('reports an exhausted limit over the exhausted allowance', async () => {+ it('reports the exhausted allowance over an exhausted limit', async () => {setLimits([buildLimit({})]);setAllowance(2_000_000);cacheStorage.mget.mockResolvedValue([0, 0]);+ await expect(assertQuotaNotExhausted()).rejects.toMatchObject({+ exhaustedScope: expect.objectContaining({ exhaustedKind: 'allowance' }),+ });+ });++ it('builds no allowance counter when the provider reports it disabled', async () => {+ setLimits([buildLimit({})]);+ setAllowance(2_000_000);+ creditAllowanceProvider.isCreditAllowanceEnabled.mockResolvedValue(false);+ cacheStorage.mget.mockResolvedValue([0]);+await expect(assertQuotaNotExhausted()).rejects.toMatchObject({exhaustedScope: expect.objectContaining({ exhaustedKind: 'limit' }),});+ expect(cacheStorage.mget).toHaveBeenCalledWith([+ expect.not.stringContaining(':allowance:'),+ ]);+ expect(+ creditAllowanceProvider.getCreditAllowancePeriod,+ ).not.toHaveBeenCalled();});it('skips warming an allowance whose period rolled over since the read', async () => {@@ -305,7 +323,18 @@ describe('UsageLimitQuotaService', () => {expect(cacheStorage.runScript).toHaveBeenCalledWith(expect.objectContaining({ args: ['[50,7]'] }),);- expect(exhausted).toBeNull();+ expect(exhausted).toEqual([]);+ });++ it('consumes an invalid cost as zero instead of crediting the counter', async () => {+ setLimits([buildLimit({})]);+ cacheStorage.runScript.mockResolvedValue([1, 950]);++ await consumeQuota(-50, Number.NaN);++ expect(cacheStorage.runScript).toHaveBeenCalledWith(+ expect.objectContaining({ args: ['[0]'] }),+ );});it('debits the allowance counter with the credit cost on consume', async () => {@@ -318,7 +347,20 @@ describe('UsageLimitQuotaService', () => {expect(cacheStorage.runScript).toHaveBeenCalledWith(expect.objectContaining({ args: ['[7,50]'] }),);- expect(exhausted).toMatchObject({ exhaustedKind: 'allowance' });+ expect(exhausted).toMatchObject([{ exhaustedKind: 'allowance' }]);+ });++ it('reports every exhausted counter on consume', async () => {+ setLimits([buildLimit({})]);+ setAllowance(2_000_000);+ cacheStorage.runScript.mockResolvedValue([1, 0, 1, -5]);++ const { exhausted } = await consumeQuota(50);++ expect(exhausted).toMatchObject([+ { exhaustedKind: 'limit' },+ { exhaustedKind: 'allowance' },+ ]);});it('warms a cold counter before consuming it', async () => {@@ -334,7 +376,7 @@ describe('UsageLimitQuotaService', () => {expect(cacheStorage.runScript).toHaveBeenCalledWith(expect.objectContaining({ args: ['[50]'] }),);- expect(exhausted).toBeNull();+ expect(exhausted).toEqual([]);});describe('dropAllowanceCounter', () => {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 38c153caaff..6166eab4fe9 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@@ -37,8 +37,9 @@ import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/import { buildQuotaCounters } from 'src/engine/core-modules/usage-limit/utils/build-quota-counters.util';import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util';import { buildQuotaWarmLockKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util';+import { clampQuotaCost } from 'src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util';import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util';-import { findExhaustedCounter } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util';+import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';import { fromConsumeResultsToRemainings } from 'src/engine/core-modules/usage-limit/utils/from-consume-results-to-remainings.util';import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';@@ -85,8 +86,12 @@ export class UsageLimitQuotaService implements OnModuleInit {}async assertQuotaNotExhausted(args: QuotaConsumeArgs): Promise<void> {+ const exhaustedScopes =+ await this.findExhaustedScopesAdmittingOnFailure(args);+const exhaustedScope =- await this.findExhaustedScopeAdmittingOnFailure(args);+ exhaustedScopes.find((scope) => scope.exhaustedKind === 'allowance') ??+ exhaustedScopes[0];if (isDefined(exhaustedScope)) {this.throwQuotaExhausted(exhaustedScope);@@ -97,12 +102,23 @@ export class UsageLimitQuotaService implements OnModuleInit {cost,...args}: QuotaConsumeArgs & { cost: QuotaCost }): Promise<{- exhausted: ExhaustedScope | null;+ exhausted: ExhaustedScope[];}> {+ const clampedCost = clampQuotaCost(cost);++ if (+ clampedCost.creditsUsedMicro !== cost.creditsUsedMicro ||+ clampedCost.quantity !== cost.quantity+ ) {+ this.logger.error(+ `Refusing to consume invalid quota cost ${JSON.stringify(cost)} for workspace ${args.workspaceId}; treating it as 0`,+ );+ }+return {exhausted: await this.consumeCountersAdmittingOnFailure({...args,- cost,+ cost: clampedCost,}),};}@@ -168,7 +184,7 @@ export class UsageLimitQuotaService implements OnModuleInit {return remaining;} catch (error) {- return this.admitOnFailure({ error, workspaceId });+ return this.admitOnFailure({ error, workspaceId, admitted: null });}}@@ -201,14 +217,14 @@ export class UsageLimitQuotaService implements OnModuleInit {}}- private async findExhaustedScopeAdmittingOnFailure(+ private async findExhaustedScopesAdmittingOnFailure(args: QuotaConsumeArgs,- ): Promise<ExhaustedScope | null> {+ ): Promise<ExhaustedScope[]> {try {const counters = await this.buildCounters(args);if (counters.length === 0) {- return null;+ return [];}const remainings = await this.readRemainings({@@ -216,25 +232,29 @@ export class UsageLimitQuotaService implements OnModuleInit {counters,});- return await this.buildExhaustedScope({+ return await this.buildExhaustedScopes({args,counters,remainings,});} catch (error) {- return this.admitOnFailure({ error, workspaceId: args.workspaceId });+ return this.admitOnFailure({+ error,+ workspaceId: args.workspaceId,+ admitted: [],+ });}}private async consumeCountersAdmittingOnFailure({cost,...args- }: QuotaConsumeArgs & { cost: QuotaCost }): Promise<ExhaustedScope | null> {+ }: QuotaConsumeArgs & { cost: QuotaCost }): Promise<ExhaustedScope[]> {try {const counters = await this.buildCounters(args);if (counters.length === 0) {- return null;+ return [];}// The consume script only debits keys that exist: warm cold counters@@ -250,17 +270,21 @@ export class UsageLimitQuotaService implements OnModuleInit {const remainings = fromConsumeResultsToRemainings(consumeResults);- return await this.buildExhaustedScope({+ return await this.buildExhaustedScopes({args,counters,remainings,});} catch (error) {- return this.admitOnFailure({ error, workspaceId: args.workspaceId });+ return this.admitOnFailure({+ error,+ workspaceId: args.workspaceId,+ admitted: [],+ });}}- private async buildExhaustedScope({+ private async buildExhaustedScopes({args,counters,remainings,@@ -268,25 +292,28 @@ export class UsageLimitQuotaService implements OnModuleInit {args: QuotaConsumeArgs;counters: QuotaCounter[];remainings: (number | null)[];- }): Promise<ExhaustedScope | null> {- const exhaustedCounter = findExhaustedCounter({ counters, remainings });+ }): Promise<ExhaustedScope[]> {+ const exhaustedCounters = findExhaustedCounters({ counters, remainings });- if (!isDefined(exhaustedCounter)) {- return null;+ if (exhaustedCounters.length === 0) {+ return [];}- const allowance =- exhaustedCounter.kind === 'allowance'- ? ((await this.creditAllowanceProvider?.getCreditAllowance(- args.workspaceId,- )) ?? null)- : null;-- return buildQuotaExhaustedScope({- resourceType: args.resourceType,- counter: exhaustedCounter,- allowance,- });+ const allowance = exhaustedCounters.some(+ (counter) => counter.kind === 'allowance',+ )+ ? ((await this.creditAllowanceProvider?.getCreditAllowance(+ args.workspaceId,+ )) ?? null)+ : null;++ return exhaustedCounters.map((counter) =>+ buildQuotaExhaustedScope({+ resourceType: args.resourceType,+ counter,+ allowance,+ }),+ );}private throwQuotaExhausted(exhaustedScope: ExhaustedScope): never {@@ -308,13 +335,15 @@ export class UsageLimitQuotaService implements OnModuleInit {);}- private admitOnFailure({+ private admitOnFailure<TAdmitted>({error,workspaceId,+ admitted,}: {error: unknown;workspaceId: string;- }): null {+ admitted: TAdmitted;+ }): TAdmitted {if (error instanceof WorkspaceCacheException ||error instanceof UsageLimitException@@ -326,7 +355,7 @@ export class UsageLimitQuotaService implements OnModuleInit {`Usage quota enforcement degraded for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,);- return null;+ return admitted;}private async buildCounters(args: QuotaConsumeArgs): Promise<QuotaCounter[]> {@@ -377,8 +406,17 @@ export class UsageLimitQuotaService implements OnModuleInit {private async buildAllowanceCounter(workspaceId: string,): Promise<AllowanceQuotaCounter | null> {+ const creditAllowanceProvider = this.creditAllowanceProvider;++ if (+ !isDefined(creditAllowanceProvider) ||+ !(await creditAllowanceProvider.isCreditAllowanceEnabled(workspaceId))+ ) {+ return null;+ }+const period =- await this.creditAllowanceProvider?.getCreditAllowancePeriod(workspaceId);+ await creditAllowanceProvider.getCreditAllowancePeriod(workspaceId);if (!isDefined(period)) {return null;diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counter.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.tssimilarity index 52%rename from packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counter.util.spec.tsrename to packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.tsindex cb645000eaa..b45c1fff588 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counter.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts@@ -1,5 +1,5 @@import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';-import { findExhaustedCounter } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util';+import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';const buildCounter = (key: string): AllowanceQuotaCounter => ({kind: 'allowance',@@ -9,49 +9,53 @@ const buildCounter = (key: string): AllowanceQuotaCounter => ({periodEnd: new Date('2026-09-01T00:00:00.000Z'),});-describe('findExhaustedCounter', () => {- it('answers null when every counter has budget left', () => {+describe('findExhaustedCounters', () => {+ it('answers empty when every counter has budget left', () => {expect(- findExhaustedCounter({+ findExhaustedCounters({counters: [buildCounter('first'), buildCounter('second')],remainings: [250, 1],}),- ).toBeNull();+ ).toEqual([]);});- it('picks the first counter whose budget is gone', () => {+ it('picks every counter whose budget is gone', () => {expect(- findExhaustedCounter({- counters: [buildCounter('first'), buildCounter('second')],- remainings: [100, 0],+ findExhaustedCounters({+ counters: [+ buildCounter('first'),+ buildCounter('second'),+ buildCounter('third'),+ ],+ remainings: [0, 100, 0],}),- ).toMatchObject({ key: 'second' });+ ).toMatchObject([{ key: 'first' }, { key: 'third' }]);});it('counts an overdrawn counter as exhausted', () => {expect(- findExhaustedCounter({+ findExhaustedCounters({counters: [buildCounter('first')],remainings: [-10],}),- ).toMatchObject({ key: 'first' });+ ).toMatchObject([{ key: 'first' }]);});it('skips cold counters', () => {expect(- findExhaustedCounter({+ findExhaustedCounters({counters: [buildCounter('first'), buildCounter('second')],remainings: [null, 0],}),- ).toMatchObject({ key: 'second' });+ ).toMatchObject([{ key: 'second' }]);});- it('answers null when every counter is cold', () => {+ it('answers empty when every counter is cold', () => {expect(- findExhaustedCounter({+ findExhaustedCounters({counters: [buildCounter('first')],remainings: [null],}),- ).toBeNull();+ ).toEqual([]);});});diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.tsnew file mode 100644index 00000000000..42ab1c42046--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts@@ -0,0 +1,9 @@+import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';+import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';++export const clampQuotaCost = (cost: QuotaCost): QuotaCost => ({+ creditsUsedMicro: isValidCreditAmountMicro(cost.creditsUsedMicro)+ ? cost.creditsUsedMicro+ : 0,+ quantity: isValidCreditAmountMicro(cost.quantity) ? cost.quantity : 0,+});diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util.tsdeleted file mode 100644index dc9f320acfd..00000000000--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util.ts+++ /dev/null@@ -1,17 +0,0 @@-import { isDefined } from 'twenty-shared/utils';--import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';--export const findExhaustedCounter = ({- counters,- remainings,-}: {- counters: QuotaCounter[];- remainings: (number | null)[];-}): QuotaCounter | null => {- const exhaustedIndex = remainings.findIndex(- (remaining) => isDefined(remaining) && remaining <= 0,- );-- return exhaustedIndex === -1 ? null : counters[exhaustedIndex];-};diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util.tsnew file mode 100644index 00000000000..07622c5ae0b--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util.ts@@ -0,0 +1,16 @@+import { isDefined } from 'twenty-shared/utils';++import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';++export const findExhaustedCounters = ({+ counters,+ remainings,+}: {+ counters: QuotaCounter[];+ remainings: (number | null)[];+}): QuotaCounter[] =>+ counters.filter((_, index) => {+ const remaining = remainings[index];++ return isDefined(remaining) && remaining <= 0;+ });diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/normalize-spender-id.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/normalize-spender-id.util.tsindex 03f4f981957..2162fcc7536 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/normalize-spender-id.util.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/normalize-spender-id.util.ts@@ -1,4 +1,6 @@-// The entity stores '' for "every spender" so the unique index can match it;-// outward shapes carry null instead.+// The entity stores '' for a limit with no spenderId so the unique index can+// match it; outward shapes carry null instead. Such a limit is one pool shared+// by every spender of its type, not a per-spender default: the counter key+// carries no spender id and the warm sums every spender's consumption.export const normalizeSpenderId = (spenderId: string): string | null =>spenderId === '' ? null : spenderId;diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.tsindex 3b79f5d568f..b7ceb76edc7 100644--- a/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts@@ -1,4 +1,5 @@import { Logger } from '@nestjs/common';+import { DiscoveryService } from '@nestjs/core';import { Test, type TestingModule } from '@nestjs/testing';import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';@@ -12,7 +13,6 @@ import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resimport { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';const API_REQUEST: RecordUsageInput = {@@ -48,14 +48,14 @@ describe('UsageRecorderService', () => {provide: WorkspaceEventEmitter,useValue: { emitCustomBatchEvent: jest.fn() },},- {- provide: WorkspaceCacheService,- useValue: { getOrRecompute: jest.fn() },- },{provide: TwentyConfigService,useValue: { get: jest.fn().mockReturnValue(false) },},+ {+ provide: DiscoveryService,+ useValue: { getProviders: () => [] },+ },],}).compile();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 3f4d15a291f..a9cbcfae8c3 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,19 +6,20 @@ import {type OnModuleDestroy,type OnModuleInit,} from '@nestjs/common';+import { DiscoveryService } from '@nestjs/core';import { isDefined } from 'twenty-shared/utils';-import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';-import { isValidCreditAmountMicro } from 'src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util';+import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';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 { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';const MAX_BUFFERED_ROLLUPS = 10_000;@@ -29,15 +30,20 @@ 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 | null = null;constructor(private readonly workspaceEventEmitter: WorkspaceEventEmitter,private readonly eventLogEmitterService: EventLogEmitterService,- private readonly workspaceCacheService: WorkspaceCacheService,private readonly twentyConfigService: TwentyConfigService,+ private readonly discoveryService: DiscoveryService,) {}onModuleInit() {+ this.creditAllowanceProvider = findCreditAllowanceProvider(+ this.discoveryService,+ );+this.flushTimer = setInterval(() => void this.flush(),this.twentyConfigService.get('USAGE_ROLLUP_FLUSH_INTERVAL_MS'),@@ -64,7 +70,7 @@ export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {return;}- const periodStart = await this.resolvePeriodStart(workspaceId);+ const periodStart = await this.getBillingPeriodStart(workspaceId);this.workspaceEventEmitter.emitCustomBatchEvent<UsageEvent>(USAGE_RECORDED,@@ -134,7 +140,7 @@ export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {workspaceId: string,usageEvents: UsageEvent[],): Promise<void> {- const periodStart = await this.resolvePeriodStart(workspaceId);+ const periodStart = await this.getBillingPeriodStart(workspaceId);return this.eventLogEmitterService.dispatch(buildUsageEventEnvelopes(@@ -165,20 +171,12 @@ export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {return { ...input, creditsUsedMicro };}- private async resolvePeriodStart(+ private async getBillingPeriodStart(workspaceId: string,): Promise<Date | undefined> {- if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {- return undefined;- }-- const { currentBillingSubscription } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'currentBillingSubscription',- ]);+ const period =+ await this.creditAllowanceProvider?.getCreditAllowancePeriod(workspaceId);- return currentBillingSubscription === NO_BILLING_SUBSCRIPTION- ? undefined- : currentBillingSubscription.currentPeriodStart;+ 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 b8d95179fb9..121ef264e02 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,6 +1,7 @@/* @license Enterprise */import { Module } from '@nestjs/common';+import { DiscoveryModule } from '@nestjs/core';import { TypeOrmModule } from '@nestjs/typeorm';import { ClickHouseModule } from 'src/database/clickhouse/clickhouse.module';@@ -17,6 +18,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache@Module({imports: [ClickHouseModule,+ DiscoveryModule,EventLogEmitterModule,FeatureFlagModule,PermissionsModule,diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-valid-credit-amount-micro.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/is-valid-credit-amount-micro.util.spec.tssimilarity index 93%rename from packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-valid-credit-amount-micro.util.spec.tsrename to packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/is-valid-credit-amount-micro.util.spec.tsindex 2f825dbc84b..94b0d2d14db 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-valid-credit-amount-micro.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/is-valid-credit-amount-micro.util.spec.ts@@ -1,4 +1,4 @@-import { isValidCreditAmountMicro } from 'src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util';+import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';describe('isValidCreditAmountMicro', () => {it.each([diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util.tssimilarity index 100%rename from packages/twenty-server/src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util.tsrename to packages/twenty-server/src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util.tsdiff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.tsindex 4a9059e9b6d..c5c06d250d3 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/resolvers/agent-run.resolver.ts@@ -1,10 +1,12 @@-import { UseGuards, UseInterceptors } from '@nestjs/common';+import { UseFilters, UseGuards, UseInterceptors } from '@nestjs/common';import { Args, Mutation } from '@nestjs/graphql';import { PermissionFlagType } from 'twenty-shared/constants';import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';+import { BillingGraphqlApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-graphql-api-exception.filter';+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';@@ -19,6 +21,10 @@ import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai@UseGuards(WorkspaceAuthGuard, SettingsPermissionGuard(PermissionFlagType.AI))@UseInterceptors(AiGraphqlApiExceptionInterceptor)+@UseFilters(+ UsageLimitGraphqlApiExceptionFilter,+ BillingGraphqlApiExceptionFilter,+)@MetadataResolver()export class AgentRunResolver {constructor(private readonly agentRunService: AgentRunService) {}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.tsindex 714cbeadc5e..d0ed89708d6 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts@@ -23,7 +23,6 @@ import { type Repository } from 'typeorm';import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { TOOL_EXECUTION_DURATION_MS_BUCKET_BOUNDARIES } from 'src/engine/core-modules/metrics/constants/tool-execution-duration-ms-bucket-boundaries.constant';import { TOOL_OUTPUT_TOKENS_BUCKET_BOUNDARIES } from 'src/engine/core-modules/metrics/constants/tool-output-tokens-bucket-boundaries.constant';import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';@@ -104,7 +103,6 @@ export class AgentAsyncExecutorService {private readonly toolRegistry: ToolRegistryService,private readonly nativeToolBinder: NativeToolBinderService,private readonly aiBillingService: AiBillingService,- private readonly billingUsageService: BillingUsageService,private readonly metricsService: MetricsService,@InjectWorkspaceScopedRepository(RoleTargetEntity)private readonly roleTargetRepository: WorkspaceScopedRepository<RoleTargetEntity>,@@ -279,7 +277,11 @@ export class AgentAsyncExecutorService {);}- await this.billingUsageService.hasAvailableCreditsOrThrow(workspaceId);+ await this.aiBillingService.assertAiExecutionAllowed({+ workspaceId,+ operationType,+ spenders: { userWorkspaceId, agentId: agent?.id },+ });let accumulatedUsage: LanguageModelUsage = EMPTY_USAGE;let cacheCreationTokens = 0;@@ -408,16 +410,18 @@ export class AgentAsyncExecutorService {},onStepFinish: async (step) => {const { hasNoMoreAvailableCredits: stepHasNoMoreAvailableCredits } =- await this.aiBillingService.decrementAndCheckAvailableCredits(- registeredModel.modelId,- {+ await this.aiBillingService.decrementAndCheckAvailableCredits({+ modelId: registeredModel.modelId,+ billingInput: {usage: step.usage,cacheCreationTokens: extractCacheCreationTokens(step.providerMetadata,),},workspaceId,- );+ operationType,+ spenders: { userWorkspaceId, agentId: agent?.id },+ });if (stepHasNoMoreAvailableCredits) {hasNoMoreAvailableCredits = true;@@ -511,16 +515,18 @@ export class AgentAsyncExecutorService {}),onStepFinish: async (step) => {const { hasNoMoreAvailableCredits: stepHasNoMoreAvailableCredits } =- await this.aiBillingService.decrementAndCheckAvailableCredits(- registeredModel.modelId,- {+ await this.aiBillingService.decrementAndCheckAvailableCredits({+ modelId: registeredModel.modelId,+ billingInput: {usage: step.usage,cacheCreationTokens: extractCacheCreationTokens(step.providerMetadata,),},workspaceId,- );+ operationType,+ spenders: { userWorkspaceId, agentId: agent?.id },+ });if (stepHasNoMoreAvailableCredits) {hasNoMoreAvailableCredits = true;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/ai-billing.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/ai-billing.module.tsindex 41beccd1863..69c75fbf3f6 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/ai-billing.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/ai-billing.module.ts@@ -4,10 +4,9 @@ import { BillingModule } from 'src/engine/core-modules/billing/billing.module';import { UsageModule } from 'src/engine/core-modules/usage/usage.module';import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';import { AiModelsModule } from 'src/engine/metadata-modules/ai/ai-models/ai-models.module';-import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';@Module({- imports: [AiModelsModule, BillingModule, UsageModule, WorkspaceCacheModule],+ imports: [AiModelsModule, BillingModule, UsageModule],providers: [AiBillingService],exports: [AiBillingService],})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 6052a773a9e..8f2f91010c6 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,20 +1,19 @@import { Injectable, Logger } from '@nestjs/common';import { type LanguageModelUsage } from 'ai';-import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';-import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';+import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';+import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';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';import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';import { NATIVE_WEB_SEARCH_COST_PER_CALL_DOLLARS } from 'src/engine/metadata-modules/ai/ai-billing/constants/native-web-search-cost-per-call-dollars';import { computeCostBreakdown } from 'src/engine/metadata-modules/ai/ai-billing/utils/compute-cost-breakdown.util';import { convertDollarsToCreditsMicro } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-credits-micro.util';import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';import { type ModelId } from 'src/engine/metadata-modules/ai/ai-models/types/model-id.type';-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';export type BillingUsageInput = {usage: LanguageModelUsage;@@ -28,11 +27,46 @@ export class AiBillingService {constructor(private readonly usageRecorderService: UsageRecorderService,private readonly aiModelRegistryService: AiModelRegistryService,- private readonly billingService: BillingService,private readonly billingUsageService: BillingUsageService,- private readonly workspaceCacheService: WorkspaceCacheService,) {}+ async assertAiExecutionAllowed({+ workspaceId,+ operationType,+ spenders,+ }: {+ workspaceId: string;+ operationType: UsageOperationType;+ spenders: UsageSpenders;+ }): Promise<void> {+ await this.billingUsageService.assertUsageAllowed({+ workspaceId,+ resourceType: UsageResourceType.AI,+ operationType,+ spenders,+ });+ }++ private async consumeQuota({+ workspaceId,+ operationType,+ spenders,+ cost,+ }: {+ workspaceId: string;+ operationType: UsageOperationType;+ spenders: UsageSpenders;+ cost: QuotaCost;+ }): Promise<{ hasNoMoreAvailableCredits: boolean }> {+ return this.billingUsageService.consumeUsageQuota({+ workspaceId,+ resourceType: UsageResourceType.AI,+ operationType,+ spenders,+ cost,+ });+ }+calculateCost(modelId: ModelId, billingInput: BillingUsageInput): number {const model = this.aiModelRegistryService.getEffectiveModelConfig(modelId);const { usage, cacheCreationTokens = 0 } = billingInput;@@ -72,12 +106,12 @@ export class AiBillingService {(billingInput.usage.inputTokens ?? 0) +(billingInput.usage.outputTokens ?? 0);- if (this.billingService.isBillingEnabled()) {- await this.billingUsageService.decrementAvailableCreditsInCache({- workspaceId,- usedCredits: creditsUsedMicro,- });- }+ await this.consumeQuota({+ workspaceId,+ operationType,+ spenders: { userWorkspaceId, agentId },+ cost: { creditsUsedMicro, quantity: totalTokens },+ });await this.emitAiTokenUsageEvent(workspaceId,@@ -90,25 +124,32 @@ export class AiBillingService {);}- async decrementAndCheckAvailableCredits(- modelId: ModelId,- billingInput: BillingUsageInput,- workspaceId: string,- ): Promise<{ hasNoMoreAvailableCredits: boolean }> {- if (!this.billingService.isBillingEnabled()) {- return { hasNoMoreAvailableCredits: false };- }-+ async decrementAndCheckAvailableCredits({+ modelId,+ billingInput,+ workspaceId,+ operationType,+ spenders,+ }: {+ modelId: ModelId;+ billingInput: BillingUsageInput;+ workspaceId: string;+ operationType: UsageOperationType;+ spenders: UsageSpenders;+ }): Promise<{ hasNoMoreAvailableCredits: boolean }> {const costInDollars = this.calculateCost(modelId, billingInput);const creditsUsedMicro = convertDollarsToCreditsMicro(costInDollars);- const remainingCredits =- await this.billingUsageService.decrementAvailableCreditsInCache({- workspaceId,- usedCredits: creditsUsedMicro,- });+ const totalTokens =+ (billingInput.usage.inputTokens ?? 0) ++ (billingInput.usage.outputTokens ?? 0);- return { hasNoMoreAvailableCredits: remainingCredits <= 0 };+ return this.consumeQuota({+ workspaceId,+ operationType,+ spenders,+ cost: { creditsUsedMicro, quantity: totalTokens },+ });}async billNativeWebSearchUsage(@@ -128,19 +169,12 @@ export class AiBillingService {`Native web search billing: ${nativeWebSearchCallCount} calls, $${costInDollars.toFixed(4)}`,);- if (this.billingService.isBillingEnabled()) {- const { currentBillingSubscription } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'currentBillingSubscription',- ]);-- if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {- await this.billingUsageService.decrementAvailableCreditsInCache({- workspaceId,- usedCredits: creditsUsedMicro,- });- }- }+ await this.consumeQuota({+ workspaceId,+ operationType: UsageOperationType.WEB_SEARCH,+ spenders: { userWorkspaceId },+ cost: { creditsUsedMicro, quantity: nativeWebSearchCallCount },+ });await this.usageRecorderService.record(workspaceId, [{diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.tsindex ece8f3b2d0d..a45daca3543 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts@@ -1,4 +1,4 @@-import { UseGuards, UseInterceptors } from '@nestjs/common';+import { UseFilters, UseGuards, UseInterceptors } from '@nestjs/common';import {Args,Float,@@ -14,7 +14,6 @@ import { isDefined } from 'twenty-shared/utils';import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { RedisClientService } from 'src/engine/core-modules/redis-client/redis-client.service';import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';@@ -37,17 +36,25 @@ import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/serviceimport { SystemPromptBuilderService } from 'src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service';import { getCancelChannel } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-cancel-channel.util';import { tagAiChatStreamScope } from 'src/engine/metadata-modules/ai/ai-chat/utils/tag-ai-chat-stream-scope.util';+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';+import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';import {AiException,AiExceptionCode,} from 'src/engine/metadata-modules/ai/ai.exception';+import { BillingGraphqlApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-graphql-api-exception.filter';+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';@UseGuards(WorkspaceAuthGuard, SettingsPermissionGuard(PermissionFlagType.AI))@UseInterceptors(AiGraphqlApiExceptionInterceptor)+@UseFilters(+ UsageLimitGraphqlApiExceptionFilter,+ BillingGraphqlApiExceptionFilter,+)@MetadataResolver(() => AgentChatThreadDTO)export class AgentChatResolver {constructor(@@ -55,7 +62,7 @@ export class AgentChatResolver {private readonly agentChatStreamingService: AgentChatStreamingService,private readonly eventPublisherService: AgentChatEventPublisherService,private readonly systemPromptBuilderService: SystemPromptBuilderService,- private readonly billingUsageService: BillingUsageService,+ private readonly aiBillingService: AiBillingService,private readonly aiModelRegistryService: AiModelRegistryService,private readonly redisClientService: RedisClientService,@InjectWorkspaceScopedRepository(AgentChatThreadEntity)@@ -179,7 +186,11 @@ export class AgentChatResolver {workspace,);- await this.billingUsageService.hasAvailableCreditsOrThrow(workspace.id);+ await this.aiBillingService.assertAiExecutionAllowed({+ workspaceId: workspace.id,+ operationType: UsageOperationType.AI_CHAT_TOKEN,+ spenders: { userWorkspaceId },+ });const thread = await this.threadRepository.findOne(workspace.id, {where: { id: threadId, userWorkspaceId },@@ -290,7 +301,11 @@ export class AgentChatResolver {workspace,);- await this.billingUsageService.hasAvailableCreditsOrThrow(workspace.id);+ await this.aiBillingService.assertAiExecutionAllowed({+ workspaceId: workspace.id,+ operationType: UsageOperationType.AI_CHAT_TOKEN,+ spenders: { userWorkspaceId },+ });const result = await this.agentChatStreamingService.retryLastFailedTurn({threadId,@@ -343,7 +358,11 @@ export class AgentChatResolver {workspace,);- await this.billingUsageService.hasAvailableCreditsOrThrow(workspace.id);+ await this.aiBillingService.assertAiExecutionAllowed({+ workspaceId: workspace.id,+ operationType: UsageOperationType.AI_CHAT_TOKEN,+ spenders: { userWorkspaceId },+ });const thread = await this.threadRepository.findOne(workspace.id, {where: { id: threadId, userWorkspaceId },diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service.tsindex 3a6bbad6d42..9b19d20916a 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-title-generation.service.ts@@ -7,7 +7,6 @@ import {generateText,} from 'ai';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';import { extractCacheCreationTokensFromSteps } from 'src/engine/metadata-modules/ai/ai-billing/utils/extract-cache-creation-tokens.util';@@ -21,7 +20,6 @@ export class AgentTitleGenerationService {constructor(private readonly aiModelRegistryService: AiModelRegistryService,private readonly aiBillingService: AiBillingService,- private readonly billingUsageService: BillingUsageService,) {}async generateThreadTitle(@@ -29,7 +27,11 @@ export class AgentTitleGenerationService {workspaceId: string,userWorkspaceId: string | null,): Promise<string> {- await this.billingUsageService.hasAvailableCreditsOrThrow(workspaceId);+ await this.aiBillingService.assertAiExecutionAllowed({+ workspaceId,+ operationType: UsageOperationType.AI_CHAT_TOKEN,+ spenders: { userWorkspaceId },+ });const defaultModel = this.aiModelRegistryService.getDefaultSpeedModel();diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.tsindex 142e86108e2..fdffe11644e 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts@@ -552,16 +552,18 @@ export class ChatExecutionService {});const { hasNoMoreAvailableCredits: stepHasNoMoreAvailableCredits } =- await this.aiBillingService.decrementAndCheckAvailableCredits(- registeredModel.modelId,- {+ await this.aiBillingService.decrementAndCheckAvailableCredits({+ modelId: registeredModel.modelId,+ billingInput: {usage: step.usage,cacheCreationTokens: extractCacheCreationTokens(step.providerMetadata,),},- workspace.id,- );+ workspaceId: workspace.id,+ operationType: UsageOperationType.AI_CHAT_TOKEN,+ spenders: { userWorkspaceId },+ });if (stepHasNoMoreAvailableCredits) {hasNoMoreAvailableCredits = true;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-generate-text/controllers/ai-generate-text.controller.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-generate-text/controllers/ai-generate-text.controller.tsindex 36efb5284fc..c395c9a8649 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-generate-text/controllers/ai-generate-text.controller.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-generate-text/controllers/ai-generate-text.controller.ts@@ -5,7 +5,7 @@ import { PermissionFlagType } from 'twenty-shared/constants';import { ApiPath } from 'twenty-shared/types';import { RestApiExceptionFilter } from 'src/engine/api/rest/rest-api-exception.filter';-import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';+import { UsageLimitRestApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-rest-api-exception.filter';import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';import type { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';@@ -19,6 +19,7 @@ import {} from 'src/engine/metadata-modules/ai/ai.exception';import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';import { AiRestApiExceptionFilter } from 'src/engine/metadata-modules/ai/filters/ai-api-exception.filter';+import { BillingRestApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-api-exception.filter';import { GenerateTextInput } from 'src/engine/metadata-modules/ai/ai-generate-text/dtos/generate-text.input';import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';import { buildAiTelemetry } from 'src/engine/metadata-modules/ai/ai-models/utils/build-ai-telemetry.util';@@ -28,15 +29,16 @@ import { PermissionsRestApiExceptionFilter } from 'src/engine/metadata-modules/p@Controller(`${ApiPath.Rest}/ai`)@UseGuards(JwtAuthGuard, WorkspaceAuthGuard)@UseFilters(+ RestApiExceptionFilter,PermissionsRestApiExceptionFilter,AiRestApiExceptionFilter,- RestApiExceptionFilter,+ UsageLimitRestApiExceptionFilter,+ BillingRestApiExceptionFilter,)export class AiGenerateTextController {constructor(private readonly aiModelRegistryService: AiModelRegistryService,private readonly aiBillingService: AiBillingService,- private readonly billingUsageService: BillingUsageService,) {}@Post('generate-text')@@ -53,7 +55,11 @@ export class AiGenerateTextController {);}- await this.billingUsageService.hasAvailableCreditsOrThrow(workspace.id);+ await this.aiBillingService.assertAiExecutionAllowed({+ workspaceId: workspace.id,+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,+ spenders: { userWorkspaceId },+ });const resolvedModelId = body.modelId ?? workspace.fastModel;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/utils/__tests__/ai-graphql-api-exception-handler.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/utils/__tests__/ai-graphql-api-exception-handler.util.spec.tsindex f9c61493c0c..7498e89e770 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/utils/__tests__/ai-graphql-api-exception-handler.util.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/utils/__tests__/ai-graphql-api-exception-handler.util.spec.ts@@ -2,6 +2,10 @@ import {AiException,AiExceptionCode,} from 'src/engine/metadata-modules/ai/ai.exception';+import {+ BillingException,+ BillingExceptionCode,+} from 'src/engine/core-modules/billing/billing.exception';import { aiGraphqlApiExceptionHandler } from 'src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util';import {ErrorCode,@@ -33,6 +37,15 @@ describe('aiGraphqlApiExceptionHandler', () => {expect(graphqlError.extensions.userFriendlyMessage).toBeDefined();});+ it('leaves billing exceptions to the billing filter', () => {+ const exception = new BillingException(+ 'Credits exhausted',+ BillingExceptionCode.BILLING_CREDITS_EXHAUSTED,+ );++ expect(() => aiGraphqlApiExceptionHandler(exception)).toThrow(exception);+ });+it('maps THREAD_NOT_FOUND to NOT_FOUND', () => {const error = new AiException('Thread not found',diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.tsindex be5eea6beb0..e2bd0f26d25 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts@@ -1,7 +1,5 @@import { assertUnreachable } from 'twenty-shared/utils';-import { BillingException } from 'src/engine/core-modules/billing/billing.exception';-import { billingGraphqlApiExceptionHandler } from 'src/engine/core-modules/billing/utils/billing-graphql-api-exception-handler.util';import {ConflictError,ForbiddenError,@@ -15,10 +13,6 @@ import {} from 'src/engine/metadata-modules/ai/ai.exception';export const aiGraphqlApiExceptionHandler = (error: Error) => {- if (error instanceof BillingException) {- return billingGraphqlApiExceptionHandler(error);- }-if (error instanceof AiException) {switch (error.code) {case AiExceptionCode.AGENT_NOT_FOUND:diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.tsindex 396f74dab38..c29e06e5d15 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts@@ -9,6 +9,7 @@ const DEFAULT_SEEDED_FEATURE_FLAGS: Partial<Record<FeatureFlagKey, boolean>> = {[FeatureFlagKey.IS_EMAIL_GROUP_ENABLED]: true,[FeatureFlagKey.IS_JUNCTION_RELATIONS_ENABLED]: true,[FeatureFlagKey.IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED]: true,+ [FeatureFlagKey.IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED]: false,};type SeedFeatureFlagsArgs = {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 af0f04ac3ed..67f6becc7c3 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,17 +1,12 @@import { Injectable } from '@nestjs/common';-import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';-import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';-import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';-import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';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';import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';import { convertDollarsToCreditsMicro } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-credits-micro.util';import { type EmailCreditContext } from 'src/modules/emailing/types/email-credit-context.type';-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';import { EMAIL_MARGIN_MULTIPLIER } from 'src/modules/emailing/constants/email-margin-multiplier';import { SES_EMAIL_COST_PER_THOUSAND_DOLLARS } from 'src/modules/emailing/constants/ses-email-cost-per-thousand-dollars';@@ -19,49 +14,35 @@ import { SES_EMAIL_COST_PER_THOUSAND_DOLLARS } from 'src/modules/emailing/constaexport class EmailBillingService {constructor(private readonly usageRecorderService: UsageRecorderService,- private readonly billingService: BillingService,private readonly billingUsageService: BillingUsageService,- private readonly workspaceCacheService: WorkspaceCacheService,) {}async validateEmailCreditsOrThrow(workspaceId: string): Promise<void> {- await this.billingUsageService.hasAvailableCreditsOrThrow(workspaceId);+ await this.billingUsageService.assertUsageAllowed({+ workspaceId,+ resourceType: UsageResourceType.EMAIL,+ operationType: UsageOperationType.EMAIL_SEND,+ spenders: {},+ });}- async resolveEmailCreditContext(+ async getEmailCreditContext(workspaceId: string,): Promise<EmailCreditContext> {- if (!this.billingService.isBillingEnabled()) {- return {- hasCredits: true,- currentBillingSubscription: NO_BILLING_SUBSCRIPTION,- };- }-- const { currentBillingSubscription } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'currentBillingSubscription',- ]);-const { hasAvailableCredits } =- await this.billingUsageService.getCreditAvailability({- workspaceId,- currentBillingSubscription,- });+ await this.billingUsageService.getCreditAvailability(workspaceId);- return { hasCredits: hasAvailableCredits, currentBillingSubscription };+ return { hasCredits: hasAvailableCredits };}async billSentEmails({workspaceId,sentEmailCount,userWorkspaceId,- currentBillingSubscription: providedCurrentBillingSubscription,}: {workspaceId: string;sentEmailCount: number;userWorkspaceId?: string | null;- currentBillingSubscription?: CurrentBillingSubscription;}): Promise<void> {if (sentEmailCount <= 0) {return;@@ -72,21 +53,13 @@ export class EmailBillingService {const chargedInDollars = providerCostInDollars * EMAIL_MARGIN_MULTIPLIER;const creditsUsedMicro = convertDollarsToCreditsMicro(chargedInDollars);- if (this.billingService.isBillingEnabled()) {- const currentBillingSubscription =- await this.billingUsageService.resolveCurrentBillingSubscription({- workspaceId,- providedCurrentBillingSubscription,- });-- if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {- await this.billingUsageService.decrementAvailableCreditsInCache({- workspaceId,- usedCredits: creditsUsedMicro,- currentBillingSubscription,- });- }- }+ await this.billingUsageService.consumeUsageQuota({+ workspaceId,+ resourceType: UsageResourceType.EMAIL,+ operationType: UsageOperationType.EMAIL_SEND,+ spenders: { userWorkspaceId },+ cost: { creditsUsedMicro, quantity: sentEmailCount },+ });await this.usageRecorderService.record(workspaceId, [{diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.tsindex f4530076c7c..67f2ed105fa 100644--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-delivery.service.ts@@ -104,7 +104,7 @@ export class MessageCampaignDeliveryService {}const creditContext =- await this.emailBillingService.resolveEmailCreditContext(workspaceId);+ await this.emailBillingService.getEmailCreditContext(workspaceId);if (creditContext.hasCredits) {const refusal = await this.findSendSlotRefusal(workspaceId);@@ -331,7 +331,7 @@ export class MessageCampaignDeliveryService {data,messageRepository,sendContext: { campaign, person, claimToken },- creditContext: { hasCredits, currentBillingSubscription },+ creditContext: { hasCredits },}: {data: SendCampaignEmailJobData;messageRepository: WorkspaceRepository<MessageWorkspaceEntity>;@@ -425,7 +425,6 @@ export class MessageCampaignDeliveryService {workspaceId,sentEmailCount: 1,userWorkspaceId,- currentBillingSubscription,}).catch((error) => {this.logger.error(diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.tsindex 2740811e1a8..2f30e8b18d7 100644--- a/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign.service.ts@@ -110,7 +110,7 @@ export class MessageCampaignService {});const { hasCredits } =- await this.emailBillingService.resolveEmailCreditContext(workspaceId);+ await this.emailBillingService.getEmailCreditContext(workspaceId);if (sendableRecipients.length > 0 && !hasCredits) {throw new EmailingDomainException(diff --git a/packages/twenty-server/src/modules/emailing/types/email-credit-context.type.ts b/packages/twenty-server/src/modules/emailing/types/email-credit-context.type.tsindex fc44a88e1d1..1f8ea57b9cc 100644--- a/packages/twenty-server/src/modules/emailing/types/email-credit-context.type.ts+++ b/packages/twenty-server/src/modules/emailing/types/email-credit-context.type.ts@@ -1,6 +1,3 @@-import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';-export type EmailCreditContext = {hasCredits: boolean;- currentBillingSubscription: CurrentBillingSubscription;};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 6e81bf5c44c..2e973948376 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@@ -8,9 +8,7 @@ import {WorkflowRunStepInfos,} from 'twenty-shared/workflow';-import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';-import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';@@ -21,7 +19,6 @@ import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-opimport { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';-import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';import { workflowHasRunningSteps } from 'src/modules/workflow/common/utils/workflow-has-running-steps.util';import {@@ -62,9 +59,7 @@ export class WorkflowExecutorWorkspaceService {private readonly workflowActionFactory: WorkflowActionFactory,private readonly usageRecorderService: UsageRecorderService,private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,- private readonly billingService: BillingService,private readonly billingUsageService: BillingUsageService,- private readonly workspaceCacheService: WorkspaceCacheService,private readonly exceptionHandlerService: ExceptionHandlerService,private readonly metricsService: MetricsService,@InjectMessageQueue(MessageQueue.workflowQueue)@@ -349,19 +344,13 @@ export class WorkflowExecutorWorkspaceService {workspaceId: string,workflowId: string,) {- if (this.billingService.isBillingEnabled()) {- const { currentBillingSubscription } =- await this.workspaceCacheService.getOrRecompute(workspaceId, [- 'currentBillingSubscription',- ]);-- if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {- await this.billingUsageService.decrementAvailableCreditsInCache({- workspaceId,- usedCredits: 100,- });- }- }+ await this.billingUsageService.consumeUsageQuota({+ workspaceId,+ resourceType: UsageResourceType.WORKFLOW,+ operationType: UsageOperationType.WORKFLOW_EXECUTION,+ spenders: { workflowId },+ cost: { creditsUsedMicro: 100, quantity: 1 },+ });await this.usageRecorderService.record(workspaceId, [{diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.tsindex 5681e78f2b5..0971d238bcf 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts@@ -65,12 +65,12 @@ export class WorkflowRunnerWorkspaceService {source: ActorMetadata;workflowRunId?: string;}) {- const canFeatureBeUsed =- await this.billingUsageService.canFeatureBeUsed(workspaceId);+ const subscriptionInactiveReason =+ await this.billingUsageService.getSubscriptionInactiveReason(workspaceId);- if (!canFeatureBeUsed) {+ if (isDefined(subscriptionInactiveReason)) {this.logger.log(- 'Cannot execute billed function, there is no subscription for this workspace',+ `Cannot execute billed function for this workspace: ${subscriptionInactiveReason}`,);}diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.tsindex 2563291aeba..80a116d6629 100644--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts@@ -6,8 +6,11 @@ import {getBillingUsageCacheService,getSeededBillingWorkspaceId,listCreditGrants,+ quitBillingFixtureRedis,+ readAllowanceCounter,resetBillingCreditState,setupResourceCreditSubscription,+ warmAllowanceCounter,} from 'test/integration/billing/utils/billing-credit-fixtures.util';import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';@@ -89,6 +92,10 @@ describe('Admin credit grant and revoke (integration)', () => {await resetBillingCreditState(workspaceId);});+ afterAll(async () => {+ await quitBillingFixtureRedis();+ });+it('records a granted amount on the ledger and mirrors it', async () => {const response = await grantCredits({workspaceId,@@ -110,7 +117,7 @@ describe('Admin credit grant and revoke (integration)', () => {});});- it('adds the granted amount to a warm usage counter', async () => {+ it('adds the granted amount to a warm available-credits counter', async () => {const cache = getBillingUsageCacheService();await cache.warmAvailableCredits(@@ -132,7 +139,7 @@ describe('Admin credit grant and revoke (integration)', () => {);});- it('takes a revoked grant back off the ledger and the counter', async () => {+ it('takes a revoked grant back off the ledger and the available-credits counter', async () => {const cache = getBillingUsageCacheService();await cache.warmAvailableCredits(@@ -168,6 +175,63 @@ describe('Admin credit grant and revoke (integration)', () => {);});+ it.each([+ BillingCreditGrantType.ROLLOVER,+ BillingCreditGrantType.ONBOARDING_REWARD,+ ])('refuses to grant a %s by hand', async (type) => {+ const response = await grantCredits({+ workspaceId,+ amount: 1,+ type,+ reason: null,+ });++ expect(response.body.errors?.[0]?.extensions?.subCode).toBe(+ 'BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE',+ );+ expect(await listCreditGrants(workspaceId)).toHaveLength(0);+ });++ it('drops the warm allowance counter when a grant lands', async () => {+ await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);++ await grantCredits({+ workspaceId,+ amount: 2,+ type: BillingCreditGrantType.COMPENSATION,+ reason: null,+ });++ expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();+ });++ it('takes a revoked grant off the ledger and drops the counter', async () => {+ const granted = await grantCredits({+ workspaceId,+ amount: 2,+ type: BillingCreditGrantType.COMPENSATION,+ reason: null,+ });+ const creditGrantId = granted.body.data.grantWorkspaceCredits.id;++ await warmAllowanceCounter(workspaceId, PERIOD_START, 500_000);++ const revoked = await callAdminGraphql(REVOKE_MUTATION, {+ workspaceId,+ creditGrantId,+ });++ expect(revoked.body.errors).toBeUndefined();+ expect(+ revoked.body.data.revokeWorkspaceCreditGrant.revokedAt,+ ).not.toBeNull();++ const grants = await listCreditGrants(workspaceId);++ expect(grants[0].revokedAt).not.toBeNull();+ expect(await readAllowanceCounter(workspaceId, PERIOD_START)).toBeNull();+ });+// The panel only offers the three operator types, but the mutation is// reachable directly and these two are written by the period transition and// the onboarding jobs.diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.tsindex d24058f3f90..f3305537e77 100644--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts@@ -6,9 +6,12 @@ import {getSeededBillingWorkspaceId,insertCreditGrant,listCreditGrants,+ quitBillingFixtureRedis,+ readAllowanceCounter,resetBillingCreditState,setupResourceCreditSubscription,TEST_STRIPE_CUSTOMER_ID,+ warmAllowanceCounter,} from 'test/integration/billing/utils/billing-credit-fixtures.util';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';@@ -79,6 +82,10 @@ describe('Billing credit rollover (integration)', () => {await resetBillingCreditState(workspaceId);});+ afterAll(async () => {+ await quitBillingFixtureRedis();+ });+it('carries the unspent allowance into the next period', async () => {usageSpy.mockResolvedValue(300_000);@@ -200,13 +207,10 @@ describe('Billing credit rollover (integration)', () => {expect(await listCreditGrants(workspaceId)).toHaveLength(0);});- it('adds the carried balance to a warm usage counter', async () => {+ it('adds the carried balance to a warm available-credits counter', async () => {usageSpy.mockResolvedValue(300_000);const cache = getBillingUsageCacheService();- // The counter is keyed by the period the subscription is currently in,- // which is the one the invoice is closing: Stripe moves the subscription- // forward in a separate event.await cache.warmAvailableCredits(workspaceId,CLOSING_PERIOD_START,@@ -221,10 +225,7 @@ describe('Billing credit rollover (integration)', () => {).toBe(120_000 + 700_000);});- // Stripe redelivers events it already handled. Rebuilding on that redelivery- // would drop a counter that is already correct and recompute it from- // ClickHouse, handing back every credit whose usage has not been ingested yet.- it('leaves a warm counter alone when a successful delivery is repeated', async () => {+ it('leaves a warm available-credits counter alone when a successful delivery is repeated', async () => {usageSpy.mockResolvedValue(300_000);const cache = getBillingUsageCacheService();@@ -249,6 +250,21 @@ describe('Billing credit rollover (integration)', () => {).toBe(afterFirst);});+ it('drops the allowance counter on the period transition', async () => {+ usageSpy.mockResolvedValue(300_000);++ // The counter is keyed by the period the subscription is currently in,+ // which is the one the invoice is closing: Stripe moves the subscription+ // forward in a separate event.+ await warmAllowanceCounter(workspaceId, CLOSING_PERIOD_START, 120_000);++ await postInvoiceFinalized().expect(200);++ expect(+ await readAllowanceCounter(workspaceId, CLOSING_PERIOD_START),+ ).toBeNull();+ });+// A subscription anchored on the 31st runs January 31 to February 28. Once// the subscription.updated webhook has moved the subscription on, calendar// arithmetic clamps February 28 back to January 28 and the closing perioddiff --git a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.tsindex cd26c9cd5a2..c0398d4c7b8 100644--- a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts+++ b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts@@ -1,5 +1,10 @@+import { createClient, type RedisClientType } from 'redis';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';import { type BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';+import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';@@ -166,6 +171,55 @@ export const listCreditGrants = async ([workspaceId],);+let redisClient: RedisClientType | null = null;++const getRedisClient = async (): Promise<RedisClientType> => {+ if (!isDefined(redisClient)) {+ redisClient = createClient({ url: process.env.REDIS_URL });+ await redisClient.connect();+ }++ return redisClient;+};++export const quitBillingFixtureRedis = async (): Promise<void> => {+ if (isDefined(redisClient)) {+ await redisClient.quit();+ redisClient = null;+ }+};++const buildTestAllowanceCounterKey = (+ workspaceId: string,+ periodStart: Date,+): string =>+ `${CacheStorageNamespace.IntegrationTests}:${CacheStorageNamespace.EngineUsageLimit}:${buildAllowanceCounterKey({ workspaceId, periodStart })}`;++export const warmAllowanceCounter = async (+ workspaceId: string,+ periodStart: Date,+ valueMicro: number,+): Promise<void> => {+ const redis = await getRedisClient();++ await redis.set(+ buildTestAllowanceCounterKey(workspaceId, periodStart),+ String(valueMicro),+ );+};++export const readAllowanceCounter = async (+ workspaceId: string,+ periodStart: Date,+): Promise<number | null> => {+ const redis = await getRedisClient();+ const value = await redis.get(+ buildTestAllowanceCounterKey(workspaceId, periodStart),+ );++ return isDefined(value) ? Number(value) : null;+};+export const resetBillingCreditState = async (workspaceId: string,): Promise<void> => {@@ -173,13 +227,21 @@ export const resetBillingCreditState = async (`DELETE FROM core."billingCreditGrant" WHERE "workspaceId" = $1`,[workspaceId],);+const cache = getBillingUsageCacheService();await cache.flushAvailableCredits(workspaceId);- // Adjustment markers outlive a counter flush by design, so a transition in- // one test would otherwise make the next one read its first delivery as a- // replay that had already moved the counter.await cache.flushCounterAdjustmentMarkers(workspaceId);++ const redis = await getRedisClient();+ const staleKeys = [+ ...(await redis.keys(`*{${workspaceId}}:quota:allowance:*`)),+ ...(await redis.keys(`*currentBillingSubscription:${workspaceId}*`)),+ ];++ if (isNonEmptyArray(staleKeys)) {+ await redis.del(staleKeys);+ }};export const getBillingUsageCacheService = (): BillingUsageCacheService =>diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.tsindex c801e8c618b..859e6c84f9d 100644--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts@@ -11,4 +11,5 @@ export enum FeatureFlagKey {IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED = 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED',IS_API_RATE_LIMIT_V2_ENABLED = 'IS_API_RATE_LIMIT_V2_ENABLED',IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED = 'IS_MESSAGE_CALENDAR_TARGET_READ_ENABLED',+ IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED = 'IS_QUOTA_ENGINE_CREDIT_BOUND_ENABLED',}