Skip to content

The open alternative to Salesforce, designed for AI.

Grant credits to enrichment-qualified workspaces (#25063)

Félix Malfaitc106acf41cf5
diff --git a/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/__tests__/company-enrichment.resolver.spec.ts b/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/__tests__/company-enrichment.resolver.spec.ts
index 9ef59607e63..4029c043e37 100644
--- a/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/__tests__/company-enrichment.resolver.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/__tests__/company-enrichment.resolver.spec.ts
@@ -13,6 +13,7 @@ describe('CompanyEnrichmentResolver', () => {
let personEnrichmentService: { enrichPersonForWorkspaceCreator: jest.Mock };
let onboardingService: {
setOnboardingBookCallPendingIfQualified: jest.Mock;
+ creditEnrichmentQualificationReward: jest.Mock;
isOnboardingBookCallPending: jest.Mock;
};
@@ -30,6 +31,7 @@ describe('CompanyEnrichmentResolver', () => {
};
onboardingService = {
setOnboardingBookCallPendingIfQualified: jest.fn(),
+ creditEnrichmentQualificationReward: jest.fn(),
isOnboardingBookCallPending: jest.fn().mockResolvedValue(false),
};
@@ -78,6 +80,27 @@ describe('CompanyEnrichmentResolver', () => {
});
});
+ it('should hand the enriched employee count to the credit reward on a match', async () => {
+ companyEnrichmentService.enrichCompanyForWorkspaceCreator.mockResolvedValue(
+ {
+ outcome: 'matched',
+ enrichment: { domain: 'acme.com', employeeCount: 320 },
+ },
+ );
+
+ await resolver.enrichWorkspaceCompany(user, workspace);
+
+ expect(
+ onboardingService.creditEnrichmentQualificationReward,
+ ).toHaveBeenCalledTimes(1);
+ expect(
+ onboardingService.creditEnrichmentQualificationReward,
+ ).toHaveBeenCalledWith({
+ workspaceId: workspace.id,
+ employeeCount: 320,
+ });
+ });
+
it.each(['unavailable', 'transientError'])(
'should not qualify for the book-call step on outcome %s',
async (outcome) => {
@@ -90,6 +113,9 @@ describe('CompanyEnrichmentResolver', () => {
expect(
onboardingService.setOnboardingBookCallPendingIfQualified,
).not.toHaveBeenCalled();
+ expect(
+ onboardingService.creditEnrichmentQualificationReward,
+ ).not.toHaveBeenCalled();
},
);
diff --git a/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/company-enrichment.resolver.ts b/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/company-enrichment.resolver.ts
index 4f39000454c..7d53a78a3cb 100644
--- a/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/company-enrichment.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/company-enrichment/resolvers/company-enrichment.resolver.ts
@@ -49,11 +49,18 @@ export class CompanyEnrichmentResolver {
]);
if (enrichmentResult.outcome === 'matched') {
+ // Two independent bars on the same enrichment: a company worth a demo and
+ // a company worth credits are not necessarily the same company.
await this.onboardingService.setOnboardingBookCallPendingIfQualified({
userId: user.id,
workspaceId: workspace.id,
employeeCount: enrichmentResult.enrichment.employeeCount,
});
+
+ await this.onboardingService.creditEnrichmentQualificationReward({
+ workspaceId: workspace.id,
+ employeeCount: enrichmentResult.enrichment.employeeCount,
+ });
}
const isBookCallOnboardingStepPending =
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/__tests__/onboarding.service.spec.ts b/packages/twenty-server/src/engine/core-modules/onboarding/__tests__/onboarding.service.spec.ts
new file mode 100644
index 00000000000..d8297d1ee00
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/__tests__/onboarding.service.spec.ts
@@ -0,0 +1,235 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+import { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';
+
+import { type DataSource } from 'typeorm';
+
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.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 { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-queue-token.util';
+import { OnboardingService } from 'src/engine/core-modules/onboarding/onboarding.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { UserVarsService } from 'src/engine/core-modules/user/user-vars/services/user-vars.service';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+
+describe('OnboardingService', () => {
+ let service: OnboardingService;
+
+ const userId = 'user-id';
+ const workspaceId = 'workspace-id';
+ const creditTiers = {
+ midMarket: { minEmployeeCount: 20, amountMicro: 5_000_000 },
+ };
+
+ // The book-call step deliberately asks for a far bigger company than the
+ // credit reward, so the two bars cannot be confused for one another.
+ const bookCallMinEmployeeCount = 200;
+
+ const configValues: Record<string, unknown> = {
+ CALENDAR_BOOKING_PAGE_ID: 'team/twenty/talk-to-us',
+ ONBOARDING_BOOK_CALL_MIN_EMPLOYEE_COUNT: bookCallMinEmployeeCount,
+ ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS: creditTiers,
+ };
+
+ const grantCredits = jest.fn();
+ const captureExceptions = jest.fn();
+ const setIfNotExists = jest.fn();
+ const getConfig = jest.fn();
+
+ beforeEach(async () => {
+ grantCredits.mockResolvedValue(null);
+ setIfNotExists.mockResolvedValue(true);
+ getConfig.mockImplementation((key: string) => configValues[key]);
+
+ const dataSource = {
+ transaction: jest.fn((runInTransaction) =>
+ runInTransaction({ queryRunner: {} }),
+ ),
+ } as unknown as DataSource;
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ OnboardingService,
+ { provide: BillingService, useValue: { isBillingEnabled: jest.fn() } },
+ { provide: BillingCreditService, useValue: { grantCredits } },
+ {
+ provide: ExceptionHandlerService,
+ useValue: { captureExceptions },
+ },
+ {
+ provide: UserVarsService,
+ useValue: {
+ get: jest.fn(),
+ set: jest.fn(),
+ delete: jest.fn(),
+ setIfNotExists,
+ },
+ },
+ { provide: TwentyConfigService, useValue: { get: getConfig } },
+ { provide: getRepositoryToken(WorkspaceEntity), useValue: {} },
+ { provide: getRepositoryToken(UserWorkspaceEntity), useValue: {} },
+ {
+ provide: getQueueToken(MessageQueue.workspaceQueue),
+ useValue: { add: jest.fn() },
+ },
+ { provide: getDataSourceToken(), useValue: dataSource },
+ ],
+ }).compile();
+
+ service = module.get<OnboardingService>(OnboardingService);
+ });
+
+ afterEach(() => {
+ jest.resetAllMocks();
+ });
+
+ describe('creditEnrichmentQualificationReward', () => {
+ it('grants the amount of the tier the enriched company lands in', async () => {
+ await service.creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount: 20,
+ });
+
+ expect(grantCredits).toHaveBeenCalledTimes(1);
+ expect(grantCredits).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workspaceId,
+ amountMicro: 5_000_000,
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ idempotencyKey: `onboarding-enrichment-qualified:${workspaceId}`,
+ }),
+ );
+ });
+
+ it('grants nothing to a company below every tier', async () => {
+ await service.creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount: 19,
+ });
+
+ expect(grantCredits).not.toHaveBeenCalled();
+ });
+
+ it('grants nothing to a workspace enrichment could not match', async () => {
+ await service.creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount: null,
+ });
+
+ expect(grantCredits).not.toHaveBeenCalled();
+ });
+
+ it('grants nothing while no tier is configured', async () => {
+ getConfig.mockImplementation((key: string) =>
+ key === 'ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS'
+ ? {}
+ : configValues[key],
+ );
+
+ await service.creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount: 5000,
+ });
+
+ expect(grantCredits).not.toHaveBeenCalled();
+ });
+
+ it('swallows a billing failure so enrichment still completes', async () => {
+ grantCredits.mockRejectedValue(new Error('billing is down'));
+
+ await expect(
+ service.creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount: 5000,
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('reports malformed tiers to Sentry and pays the well-formed ones', async () => {
+ getConfig.mockImplementation((key: string) =>
+ key === 'ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS'
+ ? { broken: { minEmployeeCount: 'twenty' }, ...creditTiers }
+ : configValues[key],
+ );
+
+ await service.creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount: 20,
+ });
+
+ expect(captureExceptions).toHaveBeenCalledTimes(1);
+ expect(captureExceptions.mock.calls[0][0][0].message).toContain('broken');
+ expect(grantCredits).toHaveBeenCalledWith(
+ expect.objectContaining({ amountMicro: 5_000_000 }),
+ );
+ });
+
+ it('survives a tier config too malformed to even read, and reports it', async () => {
+ // The JSON config transformer throws rather than returning a value when
+ // the configured tiers are not a parseable object.
+ getConfig.mockImplementation((key: string) => {
+ if (key === 'ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS') {
+ throw new Error('Failed to parse JSON string');
+ }
+
+ return configValues[key];
+ });
+
+ await expect(
+ service.creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount: 20,
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(grantCredits).not.toHaveBeenCalled();
+ expect(captureExceptions).toHaveBeenCalledTimes(1);
+ });
+
+ it('grants credits even when the book-a-call step is switched off', async () => {
+ getConfig.mockImplementation((key: string) =>
+ key === 'CALENDAR_BOOKING_PAGE_ID' ||
+ key === 'ONBOARDING_BOOK_CALL_MIN_EMPLOYEE_COUNT'
+ ? undefined
+ : configValues[key],
+ );
+
+ await service.creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount: 20,
+ });
+
+ expect(grantCredits).toHaveBeenCalledWith(
+ expect.objectContaining({ amountMicro: 5_000_000 }),
+ );
+ });
+ });
+
+ describe('setOnboardingBookCallPendingIfQualified', () => {
+ it('offers the call without granting credits', async () => {
+ const hasQualified =
+ await service.setOnboardingBookCallPendingIfQualified({
+ userId,
+ workspaceId,
+ employeeCount: bookCallMinEmployeeCount,
+ });
+
+ expect(hasQualified).toBe(true);
+ expect(grantCredits).not.toHaveBeenCalled();
+ });
+
+ it('withholds the call from a company that only clears the credit tier', async () => {
+ const hasQualified =
+ await service.setOnboardingBookCallPendingIfQualified({
+ userId,
+ workspaceId,
+ employeeCount: 20,
+ });
+
+ expect(hasQualified).toBe(false);
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts b/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
index cbbd3c4cc7b..ab1ef40829a 100644
--- a/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
@@ -9,6 +9,7 @@ import { type DataSource, type QueryRunner, Repository } from 'typeorm';
import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.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';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
@@ -25,6 +26,7 @@ import {
OnboardingExceptionCode,
} from 'src/engine/core-modules/onboarding/onboarding.exception';
import { type ReversibleOnboardingStep } from 'src/engine/core-modules/onboarding/types/reversible-onboarding-step.type';
+import { getOnboardingEnrichmentCreditRewardMicro } from 'src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util';
import { readBookCallStepMinEmployeeCount } from 'src/engine/core-modules/onboarding/utils/read-book-call-step-min-employee-count.util';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { UserVarsService } from 'src/engine/core-modules/user/user-vars/services/user-vars.service';
@@ -58,6 +60,7 @@ export class OnboardingService {
constructor(
private readonly billingService: BillingService,
private readonly billingCreditService: BillingCreditService,
+ private readonly exceptionHandlerService: ExceptionHandlerService,
private readonly userVarsService: UserVarsService<OnboardingKeyValueTypeMap>,
private readonly twentyConfigService: TwentyConfigService,
@InjectRepository(WorkspaceEntity)
@@ -855,6 +858,63 @@ export class OnboardingService {
);
}
+ async creditEnrichmentQualificationReward({
+ workspaceId,
+ employeeCount,
+ }: {
+ workspaceId: string;
+ employeeCount: number | null;
+ }) {
+ // Reading the tiers throws on its own when the configured value is not a
+ // parseable JSON object, so it sits inside the guard with the grant: a
+ // reward nobody has configured correctly must not cost anyone their
+ // onboarding.
+ try {
+ const { amountMicro, malformedTierKeys } =
+ getOnboardingEnrichmentCreditRewardMicro({
+ employeeCount,
+ tiers: this.twentyConfigService.get(
+ 'ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS',
+ ),
+ });
+
+ if (malformedTierKeys.length > 0) {
+ // Dropping a malformed tier silently would under-pay every workspace
+ // that should have matched it, with nothing to notice it by.
+ this.exceptionHandlerService.captureExceptions([
+ new Error(
+ `Ignored malformed ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS entries: ${malformedTierKeys.join(', ')}`,
+ ),
+ ]);
+ }
+
+ if (!isDefined(amountMicro)) {
+ return;
+ }
+
+ await this.billingCreditService.grantCredits({
+ workspaceId,
+ amountMicro,
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ reason: 'Onboarding reward: enrichment-qualified workspace',
+ // The only gate on the reward, deliberately: it is keyed on the
+ // workspace rather than the enriching user so that a re-run of the
+ // enrichment, or a second member qualifying later, replays instead of
+ // topping up a balance the workspace already received.
+ idempotencyKey: `onboarding-enrichment-qualified:${workspaceId}`,
+ });
+ } catch (error) {
+ this.logger.error(
+ `Failed to credit onboarding enrichment qualification reward for workspace ${workspaceId}`,
+ error,
+ );
+
+ this.exceptionHandlerService.captureExceptions([error], {
+ workspace: { id: workspaceId },
+ });
+ }
+ }
+
async isOnboardingBookCallPending({
userId,
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type.ts b/packages/twenty-server/src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type.ts
new file mode 100644
index 00000000000..0364cfa4fc0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type.ts
@@ -0,0 +1,8 @@
+// A band of enriched company data and what a workspace landing in it is worth.
+// Conditions are additive over time: a qualification score will join
+// minEmployeeCount here, and a tier missing the newer field keeps matching on
+// the conditions it does carry.
+export type OnboardingEnrichmentCreditRewardTier = {
+ minEmployeeCount: number;
+ amountMicro: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/utils/__tests__/get-onboarding-enrichment-credit-reward-micro.util.spec.ts b/packages/twenty-server/src/engine/core-modules/onboarding/utils/__tests__/get-onboarding-enrichment-credit-reward-micro.util.spec.ts
new file mode 100644
index 00000000000..9a7b97bd2a9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/utils/__tests__/get-onboarding-enrichment-credit-reward-micro.util.spec.ts
@@ -0,0 +1,112 @@
+import { getOnboardingEnrichmentCreditRewardMicro } from 'src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util';
+
+describe('getOnboardingEnrichmentCreditRewardMicro', () => {
+ const tiers = {
+ midMarket: { minEmployeeCount: 20, amountMicro: 5_000_000 },
+ enterprise: { minEmployeeCount: 200, amountMicro: 10_000_000 },
+ };
+
+ it('pays the tier an enriched company lands in', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({ employeeCount: 20, tiers }),
+ ).toEqual({ amountMicro: 5_000_000, malformedTierKeys: [] });
+ });
+
+ it('pays the most generous tier a company clears', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({ employeeCount: 5000, tiers })
+ .amountMicro,
+ ).toBe(10_000_000);
+ });
+
+ it('pays nothing below every tier', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({ employeeCount: 19, tiers })
+ .amountMicro,
+ ).toBeNull();
+ });
+
+ it('pays nothing when enrichment returned no employee count', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({ employeeCount: null, tiers })
+ .amountMicro,
+ ).toBeNull();
+ });
+
+ it('pays nothing while no tier is configured', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({
+ employeeCount: 5000,
+ tiers: {},
+ }).amountMicro,
+ ).toBeNull();
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({
+ employeeCount: 5000,
+ tiers: undefined,
+ }).amountMicro,
+ ).toBeNull();
+ });
+
+ it('pays every matched company when a tier asks for no minimum', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({
+ employeeCount: 1,
+ tiers: { anyCompany: { minEmployeeCount: 0, amountMicro: 5_000_000 } },
+ }).amountMicro,
+ ).toBe(5_000_000);
+ });
+
+ describe('malformed tiers', () => {
+ const malformedTiers = {
+ wordThreshold: { minEmployeeCount: 'twenty', amountMicro: 9_000_000 },
+ zeroAmount: { minEmployeeCount: 20, amountMicro: 0 },
+ missingThreshold: { amountMicro: 8_000_000 },
+ missingAmount: { minEmployeeCount: 20 },
+ } as never;
+
+ it('drops them instead of reading them as a zero threshold', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({
+ employeeCount: 5000,
+ tiers: malformedTiers,
+ }).amountMicro,
+ ).toBeNull();
+ });
+
+ it('names every dropped tier so the caller can report it', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({
+ employeeCount: 5000,
+ tiers: malformedTiers,
+ }).malformedTierKeys,
+ ).toEqual([
+ 'wordThreshold',
+ 'zeroAmount',
+ 'missingThreshold',
+ 'missingAmount',
+ ]);
+ });
+
+ it('still pays the tiers alongside them that are well formed', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({
+ employeeCount: 5000,
+ tiers: {
+ broken: { minEmployeeCount: 'twenty' },
+ midMarket: { minEmployeeCount: 20, amountMicro: 5_000_000 },
+ } as never,
+ }),
+ ).toEqual({ amountMicro: 5_000_000, malformedTierKeys: ['broken'] });
+ });
+
+ it('names them even for a company no tier would have matched', () => {
+ expect(
+ getOnboardingEnrichmentCreditRewardMicro({
+ employeeCount: null,
+ tiers: malformedTiers,
+ }).malformedTierKeys,
+ ).toHaveLength(4);
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util.ts b/packages/twenty-server/src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util.ts
new file mode 100644
index 00000000000..b55fc003587
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/utils/get-onboarding-enrichment-credit-reward-micro.util.ts
@@ -0,0 +1,51 @@
+import { isNumber } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type OnboardingEnrichmentCreditRewardTier } from 'src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type';
+
+// Tiers are hand-authored config, so a malformed entry must drop out rather
+// than coerce into a threshold of zero and pay every matched workspace.
+const isUsableTier = (tier: OnboardingEnrichmentCreditRewardTier): boolean =>
+ isNumber(tier?.minEmployeeCount) &&
+ tier.minEmployeeCount >= 0 &&
+ isNumber(tier?.amountMicro) &&
+ tier.amountMicro > 0;
+
+export const getOnboardingEnrichmentCreditRewardMicro = ({
+ employeeCount,
+ tiers,
+}: {
+ employeeCount: number | null;
+ tiers: Record<string, OnboardingEnrichmentCreditRewardTier> | undefined;
+}): { amountMicro: number | null; malformedTierKeys: string[] } => {
+ if (!isDefined(tiers)) {
+ return { amountMicro: null, malformedTierKeys: [] };
+ }
+
+ const entries = Object.entries(tiers);
+
+ // Reported whatever the employee count, so a mistyped tier surfaces on the
+ // first enrichment after the config change rather than waiting for a
+ // workspace that would have matched it.
+ const malformedTierKeys = entries
+ .filter(([, tier]) => !isUsableTier(tier))
+ .map(([key]) => key);
+
+ if (!isNumber(employeeCount)) {
+ return { amountMicro: null, malformedTierKeys };
+ }
+
+ // Tiers are keyed for legibility, not ordered, so every one is measured and
+ // the most generous match is the one owed.
+ const matchedAmounts = entries
+ .filter(
+ ([, tier]) =>
+ isUsableTier(tier) && employeeCount >= tier.minEmployeeCount,
+ )
+ .map(([, tier]) => tier.amountMicro);
+
+ return {
+ amountMicro: matchedAmounts.length > 0 ? Math.max(...matchedAmounts) : null,
+ malformedTierKeys,
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index af384bb8944..7a84e276d6b 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -59,6 +59,7 @@ import {
ConfigVariableException,
ConfigVariableExceptionCode,
} from 'src/engine/core-modules/twenty-config/twenty-config.exception';
+import { type OnboardingEnrichmentCreditRewardTier } from 'src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type';
import { type AiProvidersConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-providers-config.type';
import {
DEFAULT_DISABLED_MODELS,
@@ -1075,6 +1076,19 @@ export class ConfigVariables {
@IsOptional()
ONBOARDING_INSTALL_APPS_CREDITS_REWARD_PER_APP = 500_000;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.BILLING_CONFIG,
+ description:
+ 'Credit reward tiers for workspaces enrichment matched to a real company, keyed by tier name, as {"midMarket":{"minEmployeeCount":20,"amountMicro":5000000}} (amounts in microCredits). The most generous matching tier wins; no tiers disables the reward. Independent of ONBOARDING_BOOK_CALL_MIN_EMPLOYEE_COUNT, so credits and the book-a-call offer can target different companies.',
+ isHiddenInAdminPanel: true,
+ type: ConfigVariableType.JSON,
+ })
+ @IsOptional()
+ ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS: Record<
+ string,
+ OnboardingEnrichmentCreditRewardTier
+ > = {};
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.SERVER_CONFIG,
description: 'Url for the frontend application',