The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(usage-limit): cap email sends with a quota limit (#26378)
Etienne1b1444e495b4
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitQuantityUnitLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitQuantityUnitLabels.tsindex a10841b8ab6..02677ed52ae 100644--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitQuantityUnitLabels.ts+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitQuantityUnitLabels.ts@@ -6,6 +6,7 @@ import { UsageOperationType } from '~/generated-metadata/graphql';export const USAGE_LIMIT_QUANTITY_UNIT_LABELS: Partial<Record<UsageOperationType, MessageDescriptor>> = {+ [UsageOperationType.EMAIL_SEND]: msg`emails`,[UsageOperationType.WEB_SEARCH]: msg`searches`,[UsageOperationType.WORKFLOW_EXECUTION]: msg`runs`,[UsageOperationType.CODE_EXECUTION]: msg`runs`,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 7d8c4e9194b..54801008219 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@@ -13,7 +13,6 @@ 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';@@ -24,6 +23,8 @@ import { BillingSubscriptionService } from 'src/engine/core-modules/billing/servimport { type CreditAvailability } from 'src/engine/core-modules/billing/types/credit-availability.type';import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';+import { buildUsageRefusalException } from 'src/engine/core-modules/billing/utils/build-usage-refusal-exception.util';import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';@@ -59,20 +60,40 @@ export class BillingUsageService {private readonly usageLimitQuotaService: UsageLimitQuotaService,) {}- async assertUsageAllowed({+ async assertUsageAllowed(scope: UsageQuotaScope): Promise<void> {+ const usageRefusal = await this.findUsageRefusal(scope);++ if (isDefined(usageRefusal)) {+ throw buildUsageRefusalException({+ usageRefusal,+ workspaceId: scope.workspaceId,+ });+ }+ }++ async findUsageRefusal({workspaceId,resourceType,operationType,spenders,- }: UsageQuotaScope): Promise<void> {- await this.assertSubscriptionActive(workspaceId);+ }: UsageQuotaScope): Promise<UsageRefusal | null> {+ const subscriptionInactiveReason =+ await this.getSubscriptionInactiveReason(workspaceId);- await this.usageLimitQuotaService.assertQuotaNotExhausted({- workspaceId,- resourceType,- operationType,- spenders,- });+ if (isDefined(subscriptionInactiveReason)) {+ return {+ kind: 'subscriptionInactive',+ reason: subscriptionInactiveReason,+ };+ }++ const exhaustedScope = await this.usageLimitQuotaService.findExhaustedScope(+ { workspaceId, resourceType, operationType, spenders },+ );++ return isDefined(exhaustedScope)+ ? { kind: 'quotaExhausted', exhaustedScope }+ : null;}async consumeUsageQuota({@@ -128,24 +149,6 @@ export class BillingUsageService {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> {diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/usage-refusal.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/usage-refusal.type.tsnew file mode 100644index 00000000000..9e01e88df4c--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/types/usage-refusal.type.ts@@ -0,0 +1,6 @@+import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';++export type UsageRefusal =+ | { kind: 'subscriptionInactive'; reason: SubscriptionInactiveReason }+ | { kind: 'quotaExhausted'; exhaustedScope: ExhaustedScope };diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-usage-refusal-exception.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-usage-refusal-exception.util.spec.tsnew file mode 100644index 00000000000..04bbd3e94fe--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/build-usage-refusal-exception.util.spec.ts@@ -0,0 +1,83 @@+import { BillingExceptionCode } from 'src/engine/core-modules/billing/billing.exception';+import { SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE } from 'src/engine/core-modules/billing/constants/subscription-inactive-reason-user-friendly-message.constant';+import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';+import { buildUsageRefusalException } from 'src/engine/core-modules/billing/utils/build-usage-refusal-exception.util';+import { isUsageRefusedError } from 'src/engine/core-modules/billing/utils/is-usage-refused-error.util';+import { UsageLimitExceptionCode } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';+import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.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';++const WORKSPACE_ID = 'workspace-1';++const buildException = (usageRefusal: UsageRefusal) =>+ buildUsageRefusalException({ usageRefusal, workspaceId: WORKSPACE_ID });++const buildExhaustedScope = (+ overrides: Partial<ExhaustedScope> = {},+): ExhaustedScope => ({+ resourceType: UsageResourceType.EMAIL,+ limitKind: 'quota',+ exhaustedKind: 'limit',+ spenderType: 'workspace',+ spenderId: '',+ operationType: UsageOperationType.EMAIL_SEND,+ limitValue: 1000,+ remaining: 0,+ periodCount: 1,+ periodUnit: 'month',+ retryAfterMs: 0,+ ...overrides,+});++const EXHAUSTED_SCOPE_BY_EXHAUSTED_KIND: Record<ExhaustedKind, ExhaustedScope> =+ {+ limit: buildExhaustedScope({ exhaustedKind: 'limit' }),+ allowance: buildExhaustedScope({ exhaustedKind: 'allowance' }),+ };++const USAGE_REFUSALS_BY_KIND: Record<UsageRefusal['kind'], UsageRefusal[]> = {+ subscriptionInactive: (+ Object.keys(+ SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE,+ ) as SubscriptionInactiveReason[]+ ).map((reason) => ({ kind: 'subscriptionInactive', reason })),+ quotaExhausted: Object.values(EXHAUSTED_SCOPE_BY_EXHAUSTED_KIND).map(+ (exhaustedScope) => ({ kind: 'quotaExhausted', exhaustedScope }),+ ),+};++describe('buildUsageRefusalException', () => {+ it('names the workspace and the reason when the subscription is inactive', () => {+ const exception = buildException({+ kind: 'subscriptionInactive',+ reason: 'NO_SUBSCRIPTION',+ });++ expect(exception.message).toBe(+ `Workspace ${WORKSPACE_ID} has no active subscription: NO_SUBSCRIPTION`,+ );+ expect(exception.code).toBe(+ BillingExceptionCode.BILLING_SUBSCRIPTION_INACTIVE,+ );+ expect(exception.userFriendlyMessage).toBeDefined();+ });++ it('delegates an exhausted quota to the usage limit exception', () => {+ const exception = buildException({+ kind: 'quotaExhausted',+ exhaustedScope: buildExhaustedScope(),+ });++ expect(exception.code).toBe(UsageLimitExceptionCode.QUOTA_EXHAUSTED);+ });++ it.each(Object.values(USAGE_REFUSALS_BY_KIND).flat())(+ 'builds a $kind refusal that isUsageRefusedError still recognizes',+ (usageRefusal) => {+ expect(isUsageRefusedError(buildException(usageRefusal))).toBe(true);+ },+ );+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-usage-refusal-exception.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-usage-refusal-exception.util.tsnew file mode 100644index 00000000000..2741d2afed1--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-usage-refusal-exception.util.ts@@ -0,0 +1,31 @@+import {+ BillingException,+ BillingExceptionCode,+} from 'src/engine/core-modules/billing/billing.exception';+import { SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE } from 'src/engine/core-modules/billing/constants/subscription-inactive-reason-user-friendly-message.constant';+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';+import { type UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';+import { buildQuotaExhaustedException } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util';++export const buildUsageRefusalException = ({+ usageRefusal,+ workspaceId,+}: {+ usageRefusal: UsageRefusal;+ workspaceId: string;+}): BillingException | UsageLimitException => {+ if (usageRefusal.kind === 'subscriptionInactive') {+ return new BillingException(+ `Workspace ${workspaceId} has no active subscription: ${usageRefusal.reason}`,+ BillingExceptionCode.BILLING_SUBSCRIPTION_INACTIVE,+ {+ userFriendlyMessage:+ SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE[+ usageRefusal.reason+ ],+ },+ );+ }++ return buildQuotaExhaustedException(usageRefusal.exhaustedScope);+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception.tsindex c4a09e98e71..0940676ab3b 100644--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception.ts+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception.ts@@ -13,6 +13,8 @@ export enum EmailingDomainExceptionCode {MESSAGE_CAMPAIGN_NOT_FOUND = 'MESSAGE_CAMPAIGN_NOT_FOUND',MESSAGE_CAMPAIGN_NOT_SENDABLE = 'MESSAGE_CAMPAIGN_NOT_SENDABLE',MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS = 'MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS',+ MESSAGE_CAMPAIGN_SUBSCRIPTION_INACTIVE = 'MESSAGE_CAMPAIGN_SUBSCRIPTION_INACTIVE',+ MESSAGE_CAMPAIGN_USAGE_LIMIT_REACHED = 'MESSAGE_CAMPAIGN_USAGE_LIMIT_REACHED',MESSAGE_CAMPAIGN_NOT_CANCELABLE = 'MESSAGE_CAMPAIGN_NOT_CANCELABLE',MESSAGE_CAMPAIGN_SCHEDULE_NOT_IN_FUTURE = 'MESSAGE_CAMPAIGN_SCHEDULE_NOT_IN_FUTURE',}@@ -35,6 +37,10 @@ const getEmailingDomainExceptionUserFriendlyMessage = (return msg`This campaign no longer exists.`;case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS:return msg`This campaign needs more email credits than your workspace has left. Top up your credits or send to a smaller list.`;+ case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SUBSCRIPTION_INACTIVE:+ return msg`This campaign cannot be sent while the workspace subscription is inactive.`;+ case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_USAGE_LIMIT_REACHED:+ return msg`This campaign is stopped by an email usage limit set on this workspace. Raise the limit or send to a smaller list.`;case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE:return msg`This campaign cannot be sent. It may be missing a sender, subject or recipient list, or it was already sent.`;case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_CANCELABLE:diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter.tsindex 0df7841b77e..c66f2ceada0 100644--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter.ts+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/filters/emailing-domain-graphql-api-exception.filter.ts@@ -26,6 +26,8 @@ export class EmailingDomainGraphqlApiExceptionFilter implements ExceptionFiltercase EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_FOUND:throw new NotFoundError(exception);case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS:+ case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SUBSCRIPTION_INACTIVE:+ case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_USAGE_LIMIT_REACHED:case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE:case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_CANCELABLE:case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SCHEDULE_NOT_IN_FUTURE:diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.tsindex 1eb1dc984ec..bc947288754 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts@@ -108,6 +108,11 @@ export const USAGE_LIMIT_DEFINITIONS = {},],},+ quota: {+ allowedOperationTypes: [UsageOperationType.EMAIL_SEND],+ allowedSpenderTypes: ['workspace', 'userWorkspace'],+ allowedMeters: ['creditsUsedMicro', 'quantity'],+ },},[UsageResourceType.WEBHOOK]: {speed: {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 e6c0a700922..96f6ff2637e 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@@ -9,10 +9,6 @@ import {import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';-import {- UsageLimitException,- UsageLimitExceptionCode,-} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';import { UsageLimitEntitlementProvider } from 'src/engine/core-modules/usage-limit/interfaces/usage-limit-entitlement-provider.service';import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';@@ -147,8 +143,8 @@ describe('UsageLimitQuotaService', () => {);};- const assertQuotaNotExhausted = () =>- service.assertQuotaNotExhausted({+ const findExhaustedScope = () =>+ service.findExhaustedScope({workspaceId: 'workspace-1',resourceType: UsageResourceType.AI,operationType: UsageOperationType.AI_CHAT_TOKEN,@@ -223,7 +219,7 @@ describe('UsageLimitQuotaService', () => {setLimits([buildLimit({})]);cacheStorage.mget.mockResolvedValue([250]);- await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();+ await expect(findExhaustedScope()).resolves.toBeNull();expect(usageAnalyticsService.getConsumptionRowsForAllScopes,).not.toHaveBeenCalled();@@ -233,13 +229,10 @@ describe('UsageLimitQuotaService', () => {setLimits([buildLimit({})]);cacheStorage.mget.mockResolvedValue([0]);- await expect(assertQuotaNotExhausted()).rejects.toMatchObject({- code: UsageLimitExceptionCode.QUOTA_EXHAUSTED,- exhaustedScope: expect.objectContaining({- spenderType: 'workspace',- limitKind: 'quota',- exhaustedKind: 'limit',- }),+ await expect(findExhaustedScope()).resolves.toMatchObject({+ spenderType: 'workspace',+ limitKind: 'quota',+ exhaustedKind: 'limit',});});@@ -247,7 +240,7 @@ describe('UsageLimitQuotaService', () => {setLimits([buildLimit({})]);cacheStorage.mget.mockResolvedValue([undefined]);- await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();+ await expect(findExhaustedScope()).resolves.toBeNull();expect(usageAnalyticsService.getConsumptionRowsForAllScopes,).toHaveBeenCalledWith(@@ -265,7 +258,7 @@ describe('UsageLimitQuotaService', () => {]);cacheStorage.mget.mockResolvedValue([undefined, undefined]);- await assertQuotaNotExhausted();+ await findExhaustedScope();expect(usageAnalyticsService.getConsumptionRowsForAllScopes,@@ -279,9 +272,7 @@ describe('UsageLimitQuotaService', () => {150,);- await expect(assertQuotaNotExhausted()).rejects.toThrow(- UsageLimitException,- );+ await expect(findExhaustedScope()).resolves.not.toBeNull();expect(usageAnalyticsService.getCreditsUsedMicroForBillingPeriod,).toHaveBeenCalledWith({@@ -304,7 +295,7 @@ describe('UsageLimitQuotaService', () => {});cacheStorage.mget.mockResolvedValue([undefined]);- await assertQuotaNotExhausted();+ await findExhaustedScope();const [[entries]] = cacheStorage.mset.mock.calls;@@ -316,11 +307,9 @@ describe('UsageLimitQuotaService', () => {setAllowance(2_000_000);cacheStorage.mget.mockResolvedValue([0]);- await expect(assertQuotaNotExhausted()).rejects.toMatchObject({- exhaustedScope: expect.objectContaining({- exhaustedKind: 'allowance',- limitValue: 2_000_000,- }),+ await expect(findExhaustedScope()).resolves.toMatchObject({+ exhaustedKind: 'allowance',+ limitValue: 2_000_000,});});@@ -329,8 +318,8 @@ describe('UsageLimitQuotaService', () => {setAllowance(2_000_000);cacheStorage.mget.mockResolvedValue([0, 0]);- await expect(assertQuotaNotExhausted()).rejects.toMatchObject({- exhaustedScope: expect.objectContaining({ exhaustedKind: 'allowance' }),+ await expect(findExhaustedScope()).resolves.toMatchObject({+ exhaustedKind: 'allowance',});});@@ -340,8 +329,8 @@ describe('UsageLimitQuotaService', () => {creditAllowanceProvider.isCreditAllowanceEnabled.mockResolvedValue(false);cacheStorage.mget.mockResolvedValue([0]);- await expect(assertQuotaNotExhausted()).rejects.toMatchObject({- exhaustedScope: expect.objectContaining({ exhaustedKind: 'limit' }),+ await expect(findExhaustedScope()).resolves.toMatchObject({+ exhaustedKind: 'limit',});expect(cacheStorage.mget).toHaveBeenCalledWith([expect.not.stringContaining(':allowance:'),@@ -361,7 +350,7 @@ describe('UsageLimitQuotaService', () => {});cacheStorage.mget.mockResolvedValue([undefined]);- await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();+ await expect(findExhaustedScope()).resolves.toBeNull();expect(cacheStorage.mset).toHaveBeenCalledWith([]);});@@ -391,7 +380,7 @@ describe('UsageLimitQuotaService', () => {},]);- await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();+ await expect(findExhaustedScope()).resolves.toBeNull();expect(usageAnalyticsService.getConsumptionRowsForAllScopes,@@ -412,7 +401,7 @@ describe('UsageLimitQuotaService', () => {setLimits([buildLimit({})]);cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));- await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();+ await expect(findExhaustedScope()).resolves.toBeNull();expect(metricsService.incrementCounterBy).toHaveBeenCalledTimes(1);expect(metricsService.incrementCounterBy).toHaveBeenCalledWith({key: MetricsKeys.UsageLimitQuotaAdmittedOnFailure,@@ -453,7 +442,7 @@ describe('UsageLimitQuotaService', () => {new Error('clickhouse unreachable'),);- await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();+ await expect(findExhaustedScope()).resolves.toBeNull();expect(cacheStorage.mset).not.toHaveBeenCalled();});@@ -530,7 +519,7 @@ describe('UsageLimitQuotaService', () => {setLimits([buildLimit({})]);cacheStorage.mget.mockResolvedValue([250]);- await assertQuotaNotExhausted();+ await findExhaustedScope();expect(entitlementProvider.hasIntraWorkspaceLimitEntitlement,@@ -547,7 +536,7 @@ describe('UsageLimitQuotaService', () => {]);cacheStorage.mget.mockResolvedValue([250]);- await assertQuotaNotExhausted();+ await findExhaustedScope();expect(cacheStorage.mget.mock.calls[0][0]).toHaveLength(1);});@@ -559,7 +548,7 @@ describe('UsageLimitQuotaService', () => {]);cacheStorage.mget.mockResolvedValue([250, 250]);- await assertQuotaNotExhausted();+ await findExhaustedScope();expect(cacheStorage.mget.mock.calls[0][0]).toHaveLength(2);});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 292f7642fe9..edce34b72b7 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts@@ -1,7 +1,6 @@import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';import { DiscoveryService } from '@nestjs/core';-import { msg } from '@lingui/core/macro';import { isDefined } from 'twenty-shared/utils';import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';@@ -15,10 +14,7 @@ import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/typimport { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';import { CONSUME_QUOTA_COUNTERS_SCRIPT } from 'src/engine/core-modules/usage-limit/constants/consume-quota-counters-script.constant';-import {- UsageLimitException,- UsageLimitExceptionCode,-} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';+import { UsageLimitException } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';@@ -96,17 +92,17 @@ export class UsageLimitQuotaService implements OnModuleInit {);}- async assertQuotaNotExhausted(args: QuotaConsumeArgs): Promise<void> {+ async findExhaustedScope(+ args: QuotaConsumeArgs,+ ): Promise<ExhaustedScope | null> {const exhaustedScopes =await this.findExhaustedScopesAdmittingOnFailure(args);- const exhaustedScope =+ return (exhaustedScopes.find((scope) => scope.exhaustedKind === 'allowance') ??- exhaustedScopes[0];-- if (isDefined(exhaustedScope)) {- this.throwQuotaExhausted(exhaustedScope);- }+ exhaustedScopes[0] ??+ null+ );}async consumeQuota({@@ -476,25 +472,6 @@ export class UsageLimitQuotaService implements OnModuleInit {);}- private throwQuotaExhausted(exhaustedScope: ExhaustedScope): never {- if (exhaustedScope.exhaustedKind === 'allowance') {- throw new UsageLimitException(- 'Credit allowance exhausted for this billing period',- UsageLimitExceptionCode.QUOTA_EXHAUSTED,- {- userFriendlyMessage: msg`Credit allowance exhausted for this billing period.`,- exhaustedScope,- },- );- }-- throw new UsageLimitException(- `Usage limit reached for ${exhaustedScope.spenderType}`,- UsageLimitExceptionCode.QUOTA_EXHAUSTED,- { exhaustedScope },- );- }-private admitOnFailure<TAdmitted>({error,workspaceId,diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.tsindex 94586644739..b9db3050122 100644--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts@@ -12,6 +12,7 @@ describe('buildQuotaDefinitions', () => {[UsageResourceType.AI, 'quota'],[UsageResourceType.WORKFLOW, 'quota'],[UsageResourceType.LOGIC_FUNCTION, 'quota'],+ [UsageResourceType.EMAIL, 'quota'],]);});diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-exception.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-exception.util.spec.tsnew file mode 100644index 00000000000..73617063f80--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-exception.util.spec.ts@@ -0,0 +1,52 @@+import { UsageLimitExceptionCode } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';+import { buildQuotaExhaustedException } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util';+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';++const buildExhaustedScope = (+ overrides: Partial<ExhaustedScope> = {},+): ExhaustedScope => ({+ resourceType: UsageResourceType.EMAIL,+ limitKind: 'quota',+ exhaustedKind: 'limit',+ spenderType: 'userWorkspace',+ spenderId: 'user-workspace-1',+ operationType: UsageOperationType.EMAIL_SEND,+ limitValue: 1000,+ remaining: 0,+ periodCount: 1,+ periodUnit: 'month',+ retryAfterMs: 0,+ ...overrides,+});++describe('buildQuotaExhaustedException', () => {+ it('names the spender type when a configured limit is exhausted', () => {+ const exception = buildQuotaExhaustedException(buildExhaustedScope());++ expect(exception.message).toBe('Usage limit reached for userWorkspace');+ expect(exception.code).toBe(UsageLimitExceptionCode.QUOTA_EXHAUSTED);+ });++ it('overrides the generic user friendly message when the credit allowance is exhausted', () => {+ const allowanceException = buildQuotaExhaustedException(+ buildExhaustedScope({ exhaustedKind: 'allowance' }),+ );++ expect(allowanceException.message).toBe(+ 'Credit allowance exhausted for this billing period',+ );+ expect(allowanceException.userFriendlyMessage).not.toEqual(+ buildQuotaExhaustedException(buildExhaustedScope()).userFriendlyMessage,+ );+ });++ it('carries the exhausted scope so the api filters can build a response', () => {+ const exhaustedScope = buildExhaustedScope();++ expect(buildQuotaExhaustedException(exhaustedScope).exhaustedScope).toBe(+ exhaustedScope,+ );+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util.tsnew file mode 100644index 00000000000..154ac4f2963--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-exception.util.ts@@ -0,0 +1,28 @@+import { msg } from '@lingui/core/macro';++import {+ UsageLimitException,+ UsageLimitExceptionCode,+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';++export const buildQuotaExhaustedException = (+ exhaustedScope: ExhaustedScope,+): UsageLimitException => {+ if (exhaustedScope.exhaustedKind === 'allowance') {+ return new UsageLimitException(+ 'Credit allowance exhausted for this billing period',+ UsageLimitExceptionCode.QUOTA_EXHAUSTED,+ {+ userFriendlyMessage: msg`Credit allowance exhausted for this billing period.`,+ exhaustedScope,+ },+ );+ }++ return new UsageLimitException(+ `Usage limit reached for ${exhaustedScope.spenderType}`,+ UsageLimitExceptionCode.QUOTA_EXHAUSTED,+ { exhaustedScope },+ );+};diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/message-channel-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/message-channel-graphql-api-exception-handler.util.tsindex 69dc4892bee..66b5d6231ea 100644--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/message-channel-graphql-api-exception-handler.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/message-channel-graphql-api-exception-handler.util.ts@@ -49,6 +49,8 @@ export const messageChannelGraphqlApiExceptionHandler = (error: Error) => {case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_FOUND:throw new NotFoundError(error);case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS:+ case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SUBSCRIPTION_INACTIVE:+ case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_USAGE_LIMIT_REACHED:case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_SENDABLE:case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_NOT_CANCELABLE:case EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SCHEDULE_NOT_IN_FUTURE:diff --git a/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts b/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.tsindex 86096685608..8ff2894f412 100644--- a/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts+++ b/packages/twenty-server/src/modules/emailing/resolvers/emailing-send.resolver.ts@@ -19,6 +19,8 @@ import { SendMessageCampaignTestInput } from 'src/engine/core-modules/emailing-dimport { SendMessageCampaignOutputDTO } from 'src/engine/core-modules/emailing-domain/dtos/send-message-campaign-output.dto';import { EmailGroupAccessService } from 'src/engine/core-modules/emailing-domain/services/email-group-access.service';import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';@@ -49,6 +51,7 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filtEmailingDomainGraphqlApiExceptionFilter,ThrottlerGraphqlApiExceptionFilter,AuthGraphqlApiExceptionFilter,+ UsageLimitGraphqlApiExceptionFilter,)@UsePipes(ResolverValidationPipe)@MetadataResolver()@@ -72,10 +75,13 @@ export class EmailingSendResolver {@AuthUserWorkspaceId({ allowUndefined: true })userWorkspaceId: string | undefined,): Promise<SendEmailViaDomainOutputDTO> {+ const spenders = { userWorkspaceId };+this.emailGroupAccessService.validateEmailGroupAccessOrThrow();- await this.emailBillingService.validateEmailCreditsOrThrow(- currentWorkspace.id,- );+ await this.emailBillingService.validateEmailSendOrThrow({+ workspaceId: currentWorkspace.id,+ spenders,+ });const { emailingDomainId, ...content } = input;const result = await this.emailingDomainSenderService.sendEmail(@@ -86,7 +92,7 @@ export class EmailingSendResolver {await this.billAcceptedSend({workspaceId: currentWorkspace.id,- userWorkspaceId,+ spenders,result,});@@ -101,9 +107,10 @@ export class EmailingSendResolver {@AuthUserWorkspaceId() userWorkspaceId: string,): Promise<SendMessageCampaignOutputDTO> {this.emailGroupAccessService.validateEmailGroupAccessOrThrow();- await this.emailBillingService.validateEmailCreditsOrThrow(- currentWorkspace.id,- );+ await this.emailBillingService.validateEmailSendOrThrow({+ workspaceId: currentWorkspace.id,+ spenders: { userWorkspaceId },+ });if (isDefined(input.scheduledAt)) {return this.messageCampaignScheduleService.schedule({@@ -142,11 +149,14 @@ export class EmailingSendResolver {async sendMessageCampaignTest(@Args('input') input: SendMessageCampaignTestInput,@AuthWorkspace() currentWorkspace: WorkspaceEntity,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,): Promise<SendEmailViaDomainOutputDTO> {this.emailGroupAccessService.validateEmailGroupAccessOrThrow();- await this.emailBillingService.validateEmailCreditsOrThrow(- currentWorkspace.id,- );+ await this.emailBillingService.validateEmailSendOrThrow({+ workspaceId: currentWorkspace.id,+ spenders: { userWorkspaceId },+ });const result = await this.messageCampaignService.sendTest({workspaceId: currentWorkspace.id,@@ -157,7 +167,11 @@ export class EmailingSendResolver {fromAddress: input.fromAddress,});- await this.billAcceptedSend({ workspaceId: currentWorkspace.id, result });+ await this.billAcceptedSend({+ workspaceId: currentWorkspace.id,+ spenders: { userWorkspaceId },+ result,+ });return { messageId: result.messageId };}@@ -183,17 +197,17 @@ export class EmailingSendResolver {// would invite a retry that sends it a second time.private async billAcceptedSend({workspaceId,- userWorkspaceId,+ spenders,result,}: {workspaceId: string;- userWorkspaceId?: string;+ spenders: UsageSpenders;result: EmailingDomainSendEmailResult;}): Promise<void> {await this.emailBillingService.billSentEmails({workspaceId,- userWorkspaceId,+ spenders,sentEmailCount: countDeliveredRecipients(result.deliveredRecipients),}).catch((error) => {diff --git a/packages/twenty-server/src/modules/emailing/services/__tests__/message-campaign-batch-delivery.service.spec.ts b/packages/twenty-server/src/modules/emailing/services/__tests__/message-campaign-batch-delivery.service.spec.tsindex f47df7c4a35..b814ec21877 100644--- a/packages/twenty-server/src/modules/emailing/services/__tests__/message-campaign-batch-delivery.service.spec.ts+++ b/packages/twenty-server/src/modules/emailing/services/__tests__/message-campaign-batch-delivery.service.spec.ts@@ -119,7 +119,7 @@ const buildHarness = () => {findBlockedRecipientAddresses: jest.fn(async () => new Set<string>()),};const emailBillingService = {- getEmailCreditContext: jest.fn(async () => ({ hasCredits: true })),+ findEmailSendRefusal: jest.fn(async () => null),billSentEmails: jest.fn(async () => undefined),};const campaignVariableService = {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 16f8468348d..4fef30095e5 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,13 +1,18 @@import { Injectable } from '@nestjs/common';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';import { 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 { EMAIL_PRICE_PER_THOUSAND_DOLLARS } from 'src/modules/emailing/constants/email-price-per-thousand-dollars';+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';+import { computeEmailCreditsUsedMicro } from 'src/modules/emailing/utils/compute-email-credits-used-micro.util';++type EmailUsageScope = {+ workspaceId: string;+ spenders: UsageSpenders;+};@Injectable()export class EmailBillingService {@@ -16,46 +21,46 @@ export class EmailBillingService {private readonly billingUsageService: BillingUsageService,) {}- async validateEmailCreditsOrThrow(workspaceId: string): Promise<void> {+ async validateEmailSendOrThrow({+ workspaceId,+ spenders,+ }: EmailUsageScope): Promise<void> {await this.billingUsageService.assertUsageAllowed({workspaceId,resourceType: UsageResourceType.EMAIL,operationType: UsageOperationType.EMAIL_SEND,- spenders: {},+ spenders,});}- async getEmailCreditContext(- workspaceId: string,- ): Promise<EmailCreditContext> {- const { hasAvailableCredits } =- await this.billingUsageService.getCreditAvailability(workspaceId);-- return { hasCredits: hasAvailableCredits };+ async findEmailSendRefusal({+ workspaceId,+ spenders,+ }: EmailUsageScope): Promise<UsageRefusal | null> {+ return this.billingUsageService.findUsageRefusal({+ workspaceId,+ resourceType: UsageResourceType.EMAIL,+ operationType: UsageOperationType.EMAIL_SEND,+ spenders,+ });}async billSentEmails({workspaceId,sentEmailCount,- userWorkspaceId,- }: {- workspaceId: string;- sentEmailCount: number;- userWorkspaceId?: string | null;- }): Promise<void> {+ spenders,+ }: EmailUsageScope & { sentEmailCount: number }): Promise<void> {if (sentEmailCount <= 0) {return;}- const chargedInDollars =- (sentEmailCount / 1000) * EMAIL_PRICE_PER_THOUSAND_DOLLARS;- const creditsUsedMicro = convertDollarsToCreditsMicro(chargedInDollars);+ const creditsUsedMicro = computeEmailCreditsUsedMicro(sentEmailCount);await this.billingUsageService.consumeUsageQuota({workspaceId,resourceType: UsageResourceType.EMAIL,operationType: UsageOperationType.EMAIL_SEND,- spenders: { userWorkspaceId },+ spenders,cost: { creditsUsedMicro, quantity: sentEmailCount },});@@ -66,7 +71,7 @@ export class EmailBillingService {creditsUsedMicro,quantity: sentEmailCount,unit: UsageUnit.INVOCATION,- spenders: { userWorkspaceId },+ spenders,},]);}diff --git a/packages/twenty-server/src/modules/emailing/services/message-campaign-batch-delivery.service.ts b/packages/twenty-server/src/modules/emailing/services/message-campaign-batch-delivery.service.tsindex 7529326d638..8c725a02be2 100644--- a/packages/twenty-server/src/modules/emailing/services/message-campaign-batch-delivery.service.ts+++ b/packages/twenty-server/src/modules/emailing/services/message-campaign-batch-delivery.service.ts@@ -35,7 +35,7 @@ import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/import { MessageCampaignWorkspaceEntity } from 'src/modules/emailing/standard-objects/message-campaign.workspace-entity';import { type EmailingDomainEmailTemplate } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-email-template.type';import { type CampaignDeliverySettlement } from 'src/modules/emailing/types/campaign-delivery-settlement.type';-import { type EmailCreditContext } from 'src/modules/emailing/types/email-credit-context.type';+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';import { buildCampaignBatchReplacements } from 'src/modules/emailing/utils/build-campaign-batch-replacements.util';import { buildCampaignThreadExternalId } from 'src/modules/emailing/utils/build-campaign-thread-external-id.util';import { buildCampaignDeliverySettleQuery } from 'src/modules/emailing/utils/build-campaign-delivery-settle-query.util';@@ -83,8 +83,10 @@ export class MessageCampaignBatchDeliveryService {await this.messageCampaignLifecycleService.findRunningCampaign(campaignId,);- const creditContext =- await this.emailBillingService.getEmailCreditContext(workspaceId);+ const sendRefusal = await this.emailBillingService.findEmailSendRefusal({+ workspaceId,+ spenders: { userWorkspaceId: data.userWorkspaceId },+ });const claimToken = v4();const claimedDeliveryIds = await this.claimBatch({@@ -106,7 +108,7 @@ export class MessageCampaignBatchDeliveryService {await this.processClaimedBatch({data,campaign,- creditContext,+ sendRefusal,claimToken,claimedRecipients,});@@ -137,13 +139,13 @@ export class MessageCampaignBatchDeliveryService {private async processClaimedBatch({data,campaign,- creditContext,+ sendRefusal,claimToken,claimedRecipients,}: {data: SendCampaignEmailBatchJobData;campaign: MessageCampaignWorkspaceEntity | null;- creditContext: EmailCreditContext;+ sendRefusal: UsageRefusal | null;claimToken: string;claimedRecipients: BatchRecipient[];}): Promise<void> {@@ -161,7 +163,7 @@ export class MessageCampaignBatchDeliveryService {return;}- if (!creditContext.hasCredits) {+ if (isDefined(sendRefusal)) {await this.settleWholeBatchAs({workspaceId,claimToken,@@ -481,7 +483,7 @@ export class MessageCampaignBatchDeliveryService {.billSentEmails({workspaceId,sentEmailCount: sentDeliveryIds.length,- userWorkspaceId,+ spenders: { userWorkspaceId },}).catch((error) => {this.logger.error(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 8e81923dadb..e04ef84f259 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@@ -30,7 +30,7 @@ import { SKIP_EVENT_EMISSION } from 'src/modules/emailing/constants/skip-event-eimport { CampaignSendSlotService } from 'src/modules/emailing/services/campaign-send-slot.service';import { CampaignVariableService } from 'src/modules/emailing/services/campaign-variable.service';import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';-import { type EmailCreditContext } from 'src/modules/emailing/types/email-credit-context.type';+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';import { EmailingDomainSenderService } from 'src/modules/emailing/services/emailing-domain-sender.service';import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';import { MessageCampaignStatisticsService } from 'src/modules/emailing/services/message-campaign-statistics.service';@@ -85,10 +85,12 @@ export class MessageCampaignDeliveryService {return;}- const creditContext =- await this.emailBillingService.getEmailCreditContext(workspaceId);+ const sendRefusal = await this.emailBillingService.findEmailSendRefusal({+ workspaceId,+ spenders: { userWorkspaceId: data.userWorkspaceId },+ });- if (creditContext.hasCredits) {+ if (!isDefined(sendRefusal)) {const refusal = await this.campaignSendSlotService.findSendSlotRefusal({workspaceId,});@@ -125,7 +127,7 @@ export class MessageCampaignDeliveryService {data,messageRepository,sendContext,- creditContext,+ sendRefusal,});await this.messageCampaignStatisticsService@@ -270,12 +272,12 @@ export class MessageCampaignDeliveryService {data,messageRepository,sendContext: { campaign, person, claimToken },- creditContext: { hasCredits },+ sendRefusal,}: {data: SendCampaignEmailJobData;messageRepository: WorkspaceRepository<MessageWorkspaceEntity>;sendContext: SendContext;- creditContext: EmailCreditContext;+ sendRefusal: UsageRefusal | null;}): Promise<void> {const {workspaceId,@@ -286,7 +288,7 @@ export class MessageCampaignDeliveryService {userWorkspaceId,} = data;- if (!hasCredits) {+ if (isDefined(sendRefusal)) {await this.settleClaimedDelivery({workspaceId,messageId,@@ -370,7 +372,7 @@ export class MessageCampaignDeliveryService {.billSentEmails({workspaceId,sentEmailCount: 1,- userWorkspaceId,+ spenders: { userWorkspaceId },}).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 8d38f97c8ae..55e4790239e 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@@ -28,6 +28,7 @@ import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspaceimport { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';import { CampaignVariableService } from 'src/modules/emailing/services/campaign-variable.service';import { EmailBillingService } from 'src/modules/emailing/services/email-billing.service';+import { buildCampaignSendRefusalException } from 'src/modules/emailing/utils/build-campaign-send-refusal-exception.util';import { EmailingDomainSenderService } from 'src/modules/emailing/services/emailing-domain-sender.service';import { MessageCampaignAudienceService } from 'src/modules/emailing/services/message-campaign-audience.service';import { MessageCampaignLifecycleService } from 'src/modules/emailing/services/message-campaign-lifecycle.service';@@ -131,14 +132,17 @@ export class MessageCampaignService {unsubscribeTopicId: unsubscribeTopicId ?? undefined,});- const { hasCredits } =- await this.emailBillingService.getEmailCreditContext(workspaceId);+ const sendRefusal = await this.emailBillingService.findEmailSendRefusal({+ workspaceId,+ spenders: { userWorkspaceId },+ });- if (sendableRecipients.length > 0 && !hasCredits) {- throw new EmailingDomainException(- `Campaign ${campaignId} cannot be sent to ${sendableRecipients.length} recipient(s) because the workspace has no email credits left`,- EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS,- );+ if (sendableRecipients.length > 0 && isDefined(sendRefusal)) {+ throw buildCampaignSendRefusalException({+ campaignId,+ recipientCount: sendableRecipients.length,+ sendRefusal,+ });}const messageChannel =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.tsdeleted file mode 100644index 1f8ea57b9cc..00000000000--- a/packages/twenty-server/src/modules/emailing/types/email-credit-context.type.ts+++ /dev/null@@ -1,3 +0,0 @@-export type EmailCreditContext = {- hasCredits: boolean;-};diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-send-refusal-exception.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-send-refusal-exception.util.spec.tsnew file mode 100644index 00000000000..f70387f7859--- /dev/null+++ b/packages/twenty-server/src/modules/emailing/utils/__tests__/build-campaign-send-refusal-exception.util.spec.ts@@ -0,0 +1,95 @@+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';+import { EmailingDomainExceptionCode } from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';+import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.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 { buildCampaignSendRefusalException } from 'src/modules/emailing/utils/build-campaign-send-refusal-exception.util';++const buildException = (sendRefusal: UsageRefusal) =>+ buildCampaignSendRefusalException({+ campaignId: 'campaign-1',+ recipientCount: 12,+ sendRefusal,+ });++const buildQuotaRefusal = (exhaustedKind: ExhaustedKind): UsageRefusal => ({+ kind: 'quotaExhausted',+ exhaustedScope: {+ resourceType: UsageResourceType.EMAIL,+ limitKind: 'quota',+ exhaustedKind,+ spenderType: 'userWorkspace',+ spenderId: 'user-workspace-1',+ operationType: UsageOperationType.EMAIL_SEND,+ limitValue: 1000,+ remaining: 0,+ periodCount: 1,+ periodUnit: 'month',+ retryAfterMs: 0,+ } satisfies ExhaustedScope,+});++describe('buildCampaignSendRefusalException', () => {+ it('advises topping up credits only when the allowance is what ran out', () => {+ const exception = buildException(buildQuotaRefusal('allowance'));++ expect(exception.code).toBe(+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS,+ );+ expect(exception.message).toBe(+ 'Campaign campaign-1 cannot be sent to 12 recipient(s): the workspace credit allowance is exhausted',+ );+ });++ it('names the limit rather than the credits when a configured cap is reached', () => {+ const exception = buildException(buildQuotaRefusal('limit'));++ expect(exception.code).toBe(+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_USAGE_LIMIT_REACHED,+ );+ expect(exception.message).toBe(+ 'Campaign campaign-1 cannot be sent to 12 recipient(s): an email usage limit of 1000 for userWorkspace is reached',+ );+ });++ it.each(['NO_SUBSCRIPTION', 'WORKSPACE_SUSPENDED'] as const)(+ 'reports %s as a subscription problem rather than missing credits',+ (reason) => {+ const exception = buildException({+ kind: 'subscriptionInactive',+ reason,+ });++ expect(exception.code).toBe(+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SUBSCRIPTION_INACTIVE,+ );+ expect(exception.message).toContain(reason);+ },+ );++ it('gives each refusal its own user facing advice', () => {+ const userFriendlyMessages = [+ buildException(buildQuotaRefusal('allowance')),+ buildException(buildQuotaRefusal('limit')),+ buildException({+ kind: 'subscriptionInactive',+ reason: 'NO_SUBSCRIPTION',+ }),+ ].map((exception) => exception.userFriendlyMessage);++ expect(new Set(userFriendlyMessages).size).toBe(3);+ });++ it('never leaks the refusal discriminator', () => {+ expect(buildException(buildQuotaRefusal('limit')).message).not.toContain(+ 'quotaExhausted',+ );+ expect(+ buildException({+ kind: 'subscriptionInactive',+ reason: 'NO_SUBSCRIPTION',+ }).message,+ ).not.toContain('subscriptionInactive');+ });+});diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/compute-email-credits-used-micro.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/compute-email-credits-used-micro.util.spec.tsnew file mode 100644index 00000000000..9c05770431e--- /dev/null+++ b/packages/twenty-server/src/modules/emailing/utils/__tests__/compute-email-credits-used-micro.util.spec.ts@@ -0,0 +1,16 @@+import { computeEmailCreditsUsedMicro } from 'src/modules/emailing/utils/compute-email-credits-used-micro.util';++describe('computeEmailCreditsUsedMicro', () => {+ it.each([+ [0, 0],+ [1, 900],+ [7, 6300],+ [1000, 900_000],+ ])('charges %i email(s) as %i micro-credits', (sentEmailCount, expected) => {+ expect(computeEmailCreditsUsedMicro(sentEmailCount)).toBe(expected);+ });++ it('rounds to a whole micro-credit', () => {+ expect(Number.isInteger(computeEmailCreditsUsedMicro(3))).toBe(true);+ });+});diff --git a/packages/twenty-server/src/modules/emailing/utils/build-campaign-send-refusal-exception.util.ts b/packages/twenty-server/src/modules/emailing/utils/build-campaign-send-refusal-exception.util.tsnew file mode 100644index 00000000000..b50c0fb156e--- /dev/null+++ b/packages/twenty-server/src/modules/emailing/utils/build-campaign-send-refusal-exception.util.ts@@ -0,0 +1,43 @@+import { SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE } from 'src/engine/core-modules/billing/constants/subscription-inactive-reason-user-friendly-message.constant';+import { type UsageRefusal } from 'src/engine/core-modules/billing/types/usage-refusal.type';+import {+ EmailingDomainException,+ EmailingDomainExceptionCode,+} from 'src/engine/core-modules/emailing-domain/exceptions/emailing-domain.exception';++export const buildCampaignSendRefusalException = ({+ campaignId,+ recipientCount,+ sendRefusal,+}: {+ campaignId: string;+ recipientCount: number;+ sendRefusal: UsageRefusal;+}): EmailingDomainException => {+ if (sendRefusal.kind === 'subscriptionInactive') {+ return new EmailingDomainException(+ `Campaign ${campaignId} cannot be sent to ${recipientCount} recipient(s) without an active subscription: ${sendRefusal.reason}`,+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_SUBSCRIPTION_INACTIVE,+ {+ userFriendlyMessage:+ SUBSCRIPTION_INACTIVE_REASON_USER_FRIENDLY_MESSAGE[+ sendRefusal.reason+ ],+ },+ );+ }++ const { exhaustedKind, spenderType, limitValue } = sendRefusal.exhaustedScope;++ if (exhaustedKind === 'allowance') {+ return new EmailingDomainException(+ `Campaign ${campaignId} cannot be sent to ${recipientCount} recipient(s): the workspace credit allowance is exhausted`,+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_INSUFFICIENT_CREDITS,+ );+ }++ return new EmailingDomainException(+ `Campaign ${campaignId} cannot be sent to ${recipientCount} recipient(s): an email usage limit of ${limitValue} for ${spenderType} is reached`,+ EmailingDomainExceptionCode.MESSAGE_CAMPAIGN_USAGE_LIMIT_REACHED,+ );+};diff --git a/packages/twenty-server/src/modules/emailing/utils/compute-email-credits-used-micro.util.ts b/packages/twenty-server/src/modules/emailing/utils/compute-email-credits-used-micro.util.tsnew file mode 100644index 00000000000..cf37501f118--- /dev/null+++ b/packages/twenty-server/src/modules/emailing/utils/compute-email-credits-used-micro.util.ts@@ -0,0 +1,7 @@+import { convertDollarsToCreditsMicro } from 'src/engine/metadata-modules/ai/ai-billing/utils/convert-dollars-to-credits-micro.util';+import { EMAIL_PRICE_PER_THOUSAND_DOLLARS } from 'src/modules/emailing/constants/email-price-per-thousand-dollars';++export const computeEmailCreditsUsedMicro = (sentEmailCount: number): number =>+ convertDollarsToCreditsMicro(+ (sentEmailCount / 1000) * EMAIL_PRICE_PER_THOUSAND_DOLLARS,+ );