feat: Add attribute sync logic from Salesforce (#26517)

* Add db schema

* Add `CredentialRepository.findByTeamIdAndSlugs`

* Add enabled app slugs for attribute syncing

* Create repository for `IntegrationAttributeSync`

* Create zod schemas

* Create `AttributeSyncUserRuleOutputMapper`

* Create `IntegrationAttributeSyncService`

* Create DI contianer

* Create trpc endpoints

* Create page

* Include team name in `CredentialRepository.findByTeamIdAndSlugs`

* Update schema and relations

* Update types and schemas

* Add more methods to IntegrationAttributeSyncRepository

* Add more services to `IntegrationAttributeSyncService`
- getById
- Init updateIncludeRulesAndMappings

* Refactor `getTeams.handler` to use repository

* Create `createAttributeSync` trpc endpoint

* Create `updateAttributeSync` trpc endpoint

* Add router to trpc

* Create attribute sync child components

* Pass custom actions to `FormCard`

* Create `IntegrationAttributeSyncCard`

* Pass inital props via server side

* Fix prop

* Only refetch on mutation

* Fixes

* Add form error when duplicate field and attribute combo

* Add `updateTransactionWithRUleAndMappings` logic

* Adjust zod schemas

* Service add `updateIncludeRulesAndMappings`

* Pass orgId from server to component

* Rename types

* Add deleteById method to repository

* Add name to integrationAttributeSync

* Add deleteById method to service

* Rename method

* Add deleteAttributeSync trpc endpoint

* Make the IntegrationAttributeSyncCard a dummy component

* test: add tests for IntegrationAttributeSync feature

Co-Authored-By: [email protected] <[email protected]>

* Move creating a attribute sync record to the service

* Add i18n strings

* Safe select credential in find by id and team

* Fix default credentialId value in form

* Update repository return types

* Add i18n string

* Make credentialId optional for form schema

* Fix label

* Add cascade deletes

* Add verification that syncs belong to org

* Create mapper for repository output

* Type fixes

* Remove old test file

* Pass `attributeOptions` from parent to children

* Infer types from zod schema

* Type fixes

* Type fix

* Clean up

* Add i18n strings

* Remove unused file

* Address feedback

* Add migration file

* Address feedback

* Add validation for new integration values

* Remove unused router

* Move away from z.infer to z.ZodType

* Clean up comments

* Type fix

* Type fixes

* Type fix

* fix: add passthrough to syncFormDataSchema to preserve extra fields

Co-Authored-By: [email protected] <[email protected]>

* fix: remove incorrect test that expected extra fields to pass through syncFormDataSchema

Co-Authored-By: [email protected] <[email protected]>

* Add endpoint for SF to call

* Create scratch org config

* Create sf cli scripts

* Create package logic

* Update README

* Remove unused file

* Add indexes

* Add aria label

* Address feedback - consistent validation

* Fix import paths for attribute types

* Add `CredentialRepository.findByAppIdAndKeyValue`

* Get credential by instance URL

* Verify incoming sfdc orgId matches credential sfdc orgId

* Rename method

* Get user name integration syncs

* refactor: change attributeSyncRules array to singular attributeSyncRule

The database schema enforces a one-to-one relationship between
IntegrationAttributeSync and AttributeSyncRule (via @unique constraint),
and the UI only supports a single rule. This change makes the TypeScript
type match the database schema and UI behavior.

Changes:
- Update IntegrationAttributeSync interface to use attributeSyncRule: AttributeSyncRule | null
- Update mapper to return singular rule instead of wrapping in array
- Update UI component to access sync.attributeSyncRule directly
- Update IIntegrationAttributeSyncUpdateParams Omit type
- Update tests to use attributeSyncRule: null instead of attributeSyncRules: []

Co-Authored-By: [email protected] <[email protected]>

* Convert `membershipRepository.findAllByUserId` to a normal method

* Add temp files to git ignore

* Init  and process team conditions

* Biome formatting

* Add `AttributeService` to get user attributes

* Add DI container for AttributeService

* AttributeSyncService evaluate attribute conditions

* Create DI container for attributeSyncService

* Return result for full condition

* Evaluate if attribute sync should apply to user

* Add  method

* Change PrismaAttributeOptionRepository to instance methods

* Init AttributeSyncFieldMappingsService and process attribute syncs

* Add AttributeSyncFieldMappingService DI container

* Refactor orgId to organizationId

* Add membership validation to sync field service

* AttributeSYncFieldMappingService use repository methods

* AttributeSyncFieldMappingService.processMappings add mapping logic

* Add DI tokens

* user-sync endpoint to implement attribute syncing

* Validate team belongs to org for rule

* test: add tests for AttributeSyncRuleService, AttributeSyncFieldMappingService, and AttributeService

Co-Authored-By: [email protected] <[email protected]>

* Remove duplicate migration file

* Fix merge conflict

* fix: resolve type errors in attribute sync feature (#26814)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Rename  variable

* Fix log typo

* Fix file name

* Add error logging

* Use credential teamId

* fix: add missing mockTeamRepository and team validation to tests

Co-Authored-By: [email protected] <[email protected]>

* Fix naming

* Fix file import

* Type fix

* Pass MembershipRepository as a dep in AttributeSyncFieldMappingService

* Type fix

* fix: add mockMembershipRepository to AttributeSyncFieldMappingService tests

Co-Authored-By: [email protected] <[email protected]>

* Update packages/app-store/salesforce/api/user-sync.ts

Add error handling when getting orgId from stored salesforce id

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix: address Cubic code review comments

- PrismaAttributeRepository: use nested select instead of include: true for options
- CredentialRepository: use this.primaClient instead of global prisma, use select instead of include for relations
- AttributeSyncFieldMappingService: optimize O(n*m) complexity with Map lookup for O(1) access

Co-Authored-By: [email protected] <[email protected]>

* Fix typo in CredentialRepository

* Update README

* Update sfdx-project

* Add SFDC package tests

* fix: improve Salesforce Apex test assertions to verify actual behavior

- Enhanced CalComHttpMock to track HTTP callout invocations and capture requests
- Updated UserUpdateHandlerTest to verify HTTP callouts are made with correct data
- Updated CalComCalloutQueueableTest to verify HTTP callouts are made correctly
- Replaced System.assert(true, ...) with meaningful assertions that verify:
  - Correct number of HTTP callouts
  - Request body contains expected fields
  - Request method is POST

Addresses Cubic AI review feedback (confidence 9/10 issues only)

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-01-15 09:19:57 -05:00
1 parent 8c8a5b4ae9
commit 6501743e5e
43 files changed
+3438 -105

No files matched your search

@@ -0,0 +1,23 @@
import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import { PrismaAttributeOptionRepository } from "@calcom/features/attributes/repositories/PrismaAttributeOptionRepository";
import { INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS } from "./tokens";
export const attributeOptionRepositoryModule = createModule();
const token = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_OPTION_REPOSITORY;
const moduleToken = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_OPTION_REPOSITORY_MODULE;
const loadModule = bindModuleToClassOnToken({
module: attributeOptionRepositoryModule,
moduleToken,
token,
classs: PrismaAttributeOptionRepository,
dep: prismaModuleLoader,
});
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { PrismaAttributeOptionRepository };
@@ -0,0 +1,23 @@
import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import { INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS } from "./tokens";
export const attributeRepositoryModule = createModule();
const token = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_REPOSITORY;
const moduleToken = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_REPOSITORY_MODULE;
const loadModule = bindModuleToClassOnToken({
module: attributeRepositoryModule,
moduleToken,
token,
classs: PrismaAttributeRepository,
dep: prismaModuleLoader,
});
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { PrismaAttributeRepository };
@@ -0,0 +1,16 @@
import { createContainer } from "@calcom/features/di/di";
import {
type AttributeSyncFieldMappingService,
moduleLoader as attributeSyncFieldMappingServiceModule,
} from "./AttributeSyncFieldMappingService.module";
const attributeSyncFieldMappingServiceContainer = createContainer();
export function getAttributeSyncFieldMappingService(): AttributeSyncFieldMappingService {
attributeSyncFieldMappingServiceModule.loadModule(attributeSyncFieldMappingServiceContainer);
return attributeSyncFieldMappingServiceContainer.get<AttributeSyncFieldMappingService>(
attributeSyncFieldMappingServiceModule.token
);
}
@@ -0,0 +1,31 @@
import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as membershipRepositoryModuleLoader } from "@calcom/features/users/di/MembershipRepository.module";
import { AttributeSyncFieldMappingService } from "../services/AttributeSyncFieldMappingService";
import { moduleLoader as attributeToUserRepositoryModuleLoader } from "./AttributeToUserRepository.module";
import { moduleLoader as attributeRepositoryModuleLoader } from "./AttributeRepository.module";
import { moduleLoader as attributeOptionRepositoryModuleLoader } from "./AttributeOptionRepository.module";
import { INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS } from "./tokens";
export const attributeSyncFieldMappingServiceModule = createModule();
const token = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_SYNC_FIELD_MAPPING_SERVICE;
const moduleToken = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_SYNC_FIELD_MAPPING_SERVICE_MODULE;
const loadModule = bindModuleToClassOnToken({
module: attributeSyncFieldMappingServiceModule,
moduleToken,
token,
classs: AttributeSyncFieldMappingService,
depsMap: {
attributeToUserRepository: attributeToUserRepositoryModuleLoader,
attributeRepository: attributeRepositoryModuleLoader,
attributeOptionRepository: attributeOptionRepositoryModuleLoader,
membershipRepository: membershipRepositoryModuleLoader,
},
});
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { AttributeSyncFieldMappingService };
@@ -0,0 +1,14 @@
import { createContainer } from "@calcom/features/di/di";
import {
type AttributeSyncRuleService,
moduleLoader as attributeSyncRuleServiceModule,
} from "./AttributeSyncRuleService.module";
const attributeSyncRuleServiceContainer = createContainer();
export function getAttributeSyncRuleService(): AttributeSyncRuleService {
attributeSyncRuleServiceModule.loadModule(attributeSyncRuleServiceContainer);
return attributeSyncRuleServiceContainer.get<AttributeSyncRuleService>(attributeSyncRuleServiceModule.token);
}
@@ -0,0 +1,27 @@
import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as membershipRepositoryModuleLoader } from "@calcom/features/users/di/MembershipRepository.module";
import { AttributeSyncRuleService } from "../services/AttributeSyncRuleService";
import { moduleLoader as attributeToUserRepositoryModuleLoader } from "./AttributeToUserRepository.module";
import { INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS } from "./tokens";
export const attributeSyncRuleServiceModule = createModule();
const token = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_SYNC_RULE_SERVICE;
const moduleToken = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_SYNC_RULE_SERVICE_MODULE;
const loadModule = bindModuleToClassOnToken({
module: attributeSyncRuleServiceModule,
moduleToken,
token,
classs: AttributeSyncRuleService,
depsMap: {
membershipRepository: membershipRepositoryModuleLoader,
attributeToUserRepository: attributeToUserRepositoryModuleLoader,
},
});
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { AttributeSyncRuleService };
@@ -0,0 +1,23 @@
import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as prismaModuleLoader } from "@calcom/features/di/modules/Prisma";
import { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import { INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS } from "./tokens";
export const attributeToUserRepositoryModule = createModule();
const token = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_TO_USER_REPOSITORY;
const moduleToken = INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS.ATTRIBUTE_TO_USER_REPOSITORY_MODULE;
const loadModule = bindModuleToClassOnToken({
module: attributeToUserRepositoryModule,
moduleToken,
token,
classs: PrismaAttributeToUserRepository,
dep: prismaModuleLoader,
});
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { PrismaAttributeToUserRepository };
@@ -1,6 +1,7 @@
import { bindModuleToClassOnToken, createModule, type ModuleLoader } from "@calcom/features/di/di";
import { moduleLoader as credentialRepositoryModuleLoader } from "@calcom/features/di/modules/Credential";
import { IntegrationAttributeSyncService } from "@calcom/features/ee/integration-attribute-sync/services/IntegrationAttributeSyncService";
import { moduleLoader as teamRepositoryModuleLoader } from "@calcom/features/oauth/di/TeamRepository.module";
import { INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS } from "./tokens";
import { moduleLoader as integrationAttributeSyncRepositoryModuleLoader } from "./IntegrationAttributeSyncRepository.module";
@@ -16,6 +17,7 @@ const loadModule = bindModuleToClassOnToken({
depsMap: {
credentialRepository: credentialRepositoryModuleLoader,
integrationAttributeSyncRepository: integrationAttributeSyncRepositoryModuleLoader,
teamRepository: teamRepositoryModuleLoader,
},
});
@@ -3,4 +3,14 @@ export const INTEGRATION_ATTRIBUTE_SYNC_DI_TOKENS = {
INTEGRATION_ATTRIBUTE_SYNC_SERVICE_MODULE: Symbol("IntegrationAttributeSyncServiceModule"),
INTEGRATION_ATTRIBUTE_SYNC_REPOSITORY: Symbol("IntegrationAttributeSyncRepository"),
INTEGRATION_ATTRIBUTE_SYNC_REPOSITORY_MODULE: Symbol("IntegrationAttributeSyncRepositoryModule"),
ATTRIBUTE_SYNC_RULE_SERVICE: Symbol("AttributeSyncRuleService"),
ATTRIBUTE_SYNC_RULE_SERVICE_MODULE: Symbol("AttributeSyncRuleServiceModule"),
ATTRIBUTE_TO_USER_REPOSITORY: Symbol("AttributeToUserRepository"),
ATTRIBUTE_TO_USER_REPOSITORY_MODULE: Symbol("AttributeToUserRepositoryModule"),
ATTRIBUTE_SYNC_FIELD_MAPPING_SERVICE: Symbol("AttributeSyncFieldMappingService"),
ATTRIBUTE_SYNC_FIELD_MAPPING_SERVICE_MODULE: Symbol("AttributeSyncFieldMappingServiceModule"),
ATTRIBUTE_REPOSITORY: Symbol("AttributeRepository"),
ATTRIBUTE_REPOSITORY_MODULE: Symbol("AttributeRepositoryModule"),
ATTRIBUTE_OPTION_REPOSITORY: Symbol("AttributeOptionRepository"),
ATTRIBUTE_OPTION_REPOSITORY_MODULE: Symbol("AttributeOptionRepositoryModule"),
};
@@ -123,14 +123,31 @@ export interface IUpdateAttributeSyncInput {
}
export interface IIntegrationAttributeSyncRepository {
getByOrganizationId(organizationId: number): Promise<IntegrationAttributeSync[]>;
getByOrganizationId(
organizationId: number
): Promise<IntegrationAttributeSync[]>;
getById(id: string): Promise<IntegrationAttributeSync | null>;
getSyncFieldMappings(integrationAttributeSyncId: string): Promise<AttributeSyncFieldMapping[]>;
getMappedAttributeIdsByOrganization(organizationId: number, excludeSyncId?: string): Promise<string[]>;
getAttributeIdsByOrganization(organizationId: number, attributeIds: string[]): Promise<string[]>;
create(params: IIntegrationAttributeSyncCreateParams): Promise<IntegrationAttributeSync>;
updateTransactionWithRuleAndMappings(params: IIntegrationAttributeSyncUpdateParams): Promise<void>;
getSyncFieldMappings(
integrationAttributeSyncId: string
): Promise<AttributeSyncFieldMapping[]>;
getMappedAttributeIdsByOrganization(
organizationId: number,
excludeSyncId?: string
): Promise<string[]>;
getAttributeIdsByOrganization(
organizationId: number,
attributeIds: string[]
): Promise<string[]>;
create(
params: IIntegrationAttributeSyncCreateParams
): Promise<IntegrationAttributeSync>;
updateTransactionWithRuleAndMappings(
params: IIntegrationAttributeSyncUpdateParams
): Promise<void>;
deleteById(id: string): Promise<void>;
getAllByCredentialId(
credentialId: number
): Promise<IntegrationAttributeSync[]>;
}
export interface IIntegrationAttributeSyncUpdateParams {
@@ -1,5 +1,5 @@
import type { Prisma } from "@calcom/prisma/client";
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import { IntegrationAttributeSyncOutputMapper } from "../mappers/IntegrationAttributeSyncOutputMapper";
import type {
@@ -207,4 +207,24 @@ export class PrismaIntegrationAttributeSyncRepository implements IIntegrationAtt
})
.then(() => {});
}
async getAllByCredentialId(credentialId: number) {
const integrationAttributeSyncsQuery = await this.prismaClient.integrationAttributeSync.findMany({
where: {
credentialId,
},
select: {
id: true,
name: true,
organizationId: true,
integration: true,
credentialId: true,
enabled: true,
attributeSyncRule: true,
syncFieldMappings: true,
},
});
return IntegrationAttributeSyncOutputMapper.toDomainList(integrationAttributeSyncsQuery);
}
}
@@ -0,0 +1,560 @@
import type { PrismaAttributeOptionRepository } from "@calcom/features/attributes/repositories/PrismaAttributeOptionRepository";
import type { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import type { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import type { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { IFieldMapping } from "../repositories/IIntegrationAttributeSyncRepository";
import { AttributeSyncFieldMappingService } from "./AttributeSyncFieldMappingService";
describe("AttributeSyncFieldMappingService", () => {
let service: AttributeSyncFieldMappingService;
let mockAttributeToUserRepository: {
deleteMany: ReturnType<typeof vi.fn>;
createManySkipDuplicates: ReturnType<typeof vi.fn>;
};
let mockAttributeRepository: {
findManyByIdsAndOrgIdWithOptions: ReturnType<typeof vi.fn>;
};
let mockAttributeOptionRepository: {
createMany: ReturnType<typeof vi.fn>;
findMany: ReturnType<typeof vi.fn>;
};
let mockMembershipRepository: {
findUniqueByUserIdAndTeamId: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.resetAllMocks();
mockAttributeToUserRepository = {
deleteMany: vi.fn(),
createManySkipDuplicates: vi.fn(),
};
mockAttributeRepository = {
findManyByIdsAndOrgIdWithOptions: vi.fn(),
};
mockAttributeOptionRepository = {
createMany: vi.fn(),
findMany: vi.fn(),
};
mockMembershipRepository = {
findUniqueByUserIdAndTeamId: vi.fn(),
};
service = new AttributeSyncFieldMappingService({
attributeToUserRepository: mockAttributeToUserRepository as unknown as PrismaAttributeToUserRepository,
attributeRepository: mockAttributeRepository as unknown as PrismaAttributeRepository,
attributeOptionRepository: mockAttributeOptionRepository as unknown as PrismaAttributeOptionRepository,
membershipRepository: mockMembershipRepository as unknown as MembershipRepository,
});
});
describe("syncIntegrationFieldsToAttributes", () => {
const baseParams = {
userId: 1,
organizationId: 100,
};
it("should return early when no membership found", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue(null);
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings: [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: true },
],
integrationFields: { Department: "Engineering" },
});
expect(mockAttributeRepository.findManyByIdsAndOrgIdWithOptions).not.toHaveBeenCalled();
expect(mockAttributeToUserRepository.deleteMany).not.toHaveBeenCalled();
expect(mockAttributeToUserRepository.createManySkipDuplicates).not.toHaveBeenCalled();
});
it("should return early when no enabled mappings with matching integration fields", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings: [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: false },
],
integrationFields: { Department: "Engineering" },
});
expect(mockAttributeRepository.findManyByIdsAndOrgIdWithOptions).not.toHaveBeenCalled();
});
it("should sync SINGLE_SELECT attribute with matching option", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Department",
type: "SINGLE_SELECT",
options: [
{ id: "opt-1", value: "Engineering", slug: "engineering" },
{ id: "opt-2", value: "Sales", slug: "sales" },
],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Department: "Engineering" },
});
expect(mockAttributeToUserRepository.deleteMany).toHaveBeenCalledWith({
memberId: 1,
attributeOption: {
attributeId: { in: ["attr-1"] },
},
});
expect(mockAttributeToUserRepository.createManySkipDuplicates).toHaveBeenCalledWith([
{ memberId: 1, attributeOptionId: "opt-1" },
]);
});
it("should sync MULTI_SELECT attribute with multiple matching options", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Skills",
type: "MULTI_SELECT",
options: [
{ id: "opt-1", value: "JavaScript", slug: "javascript" },
{ id: "opt-2", value: "TypeScript", slug: "typescript" },
{ id: "opt-3", value: "Python", slug: "python" },
],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Skills", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Skills: "JavaScript, TypeScript" },
});
expect(mockAttributeToUserRepository.createManySkipDuplicates).toHaveBeenCalledWith([
{ memberId: 1, attributeOptionId: "opt-1" },
{ memberId: 1, attributeOptionId: "opt-2" },
]);
});
it("should handle case-insensitive option matching", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Department",
type: "SINGLE_SELECT",
options: [{ id: "opt-1", value: "Engineering", slug: "engineering" }],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Department: "ENGINEERING" },
});
expect(mockAttributeToUserRepository.createManySkipDuplicates).toHaveBeenCalledWith([
{ memberId: 1, attributeOptionId: "opt-1" },
]);
});
it("should create new option for TEXT attribute when no matching option exists", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Title",
type: "TEXT",
options: [],
},
]);
mockAttributeOptionRepository.findMany.mockResolvedValue([
{ id: "new-opt-1", attributeId: "attr-1", value: "Senior Engineer", slug: "senior-engineer" },
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Title", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Title: "Senior Engineer" },
});
expect(mockAttributeOptionRepository.createMany).toHaveBeenCalledWith({
createManyInput: [{ attributeId: "attr-1", value: "Senior Engineer", slug: "senior-engineer" }],
});
expect(mockAttributeToUserRepository.createManySkipDuplicates).toHaveBeenCalledWith([
{ memberId: 1, attributeOptionId: "new-opt-1" },
]);
});
it("should use existing option for TEXT attribute when matching option exists", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Title",
type: "TEXT",
options: [{ id: "opt-1", value: "Senior Engineer", slug: "senior-engineer" }],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Title", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Title: "Senior Engineer" },
});
expect(mockAttributeOptionRepository.createMany).not.toHaveBeenCalled();
expect(mockAttributeToUserRepository.createManySkipDuplicates).toHaveBeenCalledWith([
{ memberId: 1, attributeOptionId: "opt-1" },
]);
});
it("should skip mapping when attribute not found", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Department: "Engineering" },
});
expect(mockAttributeToUserRepository.deleteMany).not.toHaveBeenCalled();
expect(mockAttributeToUserRepository.createManySkipDuplicates).not.toHaveBeenCalled();
});
it("should skip non-matching options for SINGLE_SELECT attribute", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Department",
type: "SINGLE_SELECT",
options: [
{ id: "opt-1", value: "Engineering", slug: "engineering" },
{ id: "opt-2", value: "Sales", slug: "sales" },
],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Department: "Marketing" },
});
expect(mockAttributeToUserRepository.deleteMany).toHaveBeenCalledWith({
memberId: 1,
attributeOption: {
attributeId: { in: ["attr-1"] },
},
});
expect(mockAttributeToUserRepository.createManySkipDuplicates).not.toHaveBeenCalled();
});
it("should handle multiple mappings for different attributes", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Department",
type: "SINGLE_SELECT",
options: [{ id: "opt-1", value: "Engineering", slug: "engineering" }],
},
{
id: "attr-2",
name: "Level",
type: "SINGLE_SELECT",
options: [{ id: "opt-2", value: "Senior", slug: "senior" }],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: true },
{ id: "mapping-2", integrationFieldName: "Level", attributeId: "attr-2", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Department: "Engineering", Level: "Senior" },
});
expect(mockAttributeToUserRepository.deleteMany).toHaveBeenCalledWith({
memberId: 1,
attributeOption: {
attributeId: { in: ["attr-1", "attr-2"] },
},
});
expect(mockAttributeToUserRepository.createManySkipDuplicates).toHaveBeenCalledWith([
{ memberId: 1, attributeOptionId: "opt-1" },
{ memberId: 1, attributeOptionId: "opt-2" },
]);
});
it("should only process enabled mappings", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Department",
type: "SINGLE_SELECT",
options: [{ id: "opt-1", value: "Engineering", slug: "engineering" }],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: true },
{ id: "mapping-2", integrationFieldName: "Level", attributeId: "attr-2", enabled: false },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Department: "Engineering", Level: "Senior" },
});
expect(mockAttributeRepository.findManyByIdsAndOrgIdWithOptions).toHaveBeenCalledWith({
attributeIds: ["attr-1"],
orgId: 100,
});
});
it("should handle SINGLE_SELECT with comma-separated value by taking first value only", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Department",
type: "SINGLE_SELECT",
options: [
{ id: "opt-1", value: "Engineering", slug: "engineering" },
{ id: "opt-2", value: "Sales", slug: "sales" },
],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Department", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Department: "Engineering, Sales" },
});
expect(mockAttributeToUserRepository.createManySkipDuplicates).toHaveBeenCalledWith([
{ memberId: 1, attributeOptionId: "opt-1" },
]);
});
it("should handle NUMBER attribute type", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Years of Experience",
type: "NUMBER",
options: [],
},
]);
mockAttributeOptionRepository.findMany.mockResolvedValue([
{ id: "new-opt-1", attributeId: "attr-1", value: "5", slug: "5" },
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Experience", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Experience: "5" },
});
expect(mockAttributeOptionRepository.createMany).toHaveBeenCalledWith({
createManyInput: [{ attributeId: "attr-1", value: "5", slug: "5" }],
});
});
it("should clear old assignments even when field value is empty", async () => {
mockMembershipRepository.findUniqueByUserIdAndTeamId.mockResolvedValue({
id: 1,
userId: 1,
teamId: 100,
accepted: true,
role: "MEMBER",
disableImpersonation: false,
});
mockAttributeRepository.findManyByIdsAndOrgIdWithOptions.mockResolvedValue([
{
id: "attr-1",
name: "Skills",
type: "MULTI_SELECT",
options: [{ id: "opt-1", value: "JavaScript", slug: "javascript" }],
},
]);
const syncFieldMappings: IFieldMapping[] = [
{ id: "mapping-1", integrationFieldName: "Skills", attributeId: "attr-1", enabled: true },
];
await service.syncIntegrationFieldsToAttributes({
...baseParams,
syncFieldMappings,
integrationFields: { Skills: "" },
});
expect(mockAttributeToUserRepository.deleteMany).toHaveBeenCalledWith({
memberId: 1,
attributeOption: {
attributeId: { in: ["attr-1"] },
},
});
expect(mockAttributeToUserRepository.createManySkipDuplicates).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,271 @@
import { PrismaAttributeOptionRepository } from "@calcom/features/attributes/repositories/PrismaAttributeOptionRepository";
import {
buildSlugFromValue,
canSetValueBeyondOptions,
doesSupportMultipleValues,
hasOptions,
} from "@calcom/features/ee/dsync/lib/assignValueToUserUtils";
import logger from "@calcom/lib/logger";
import { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import type { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import type { IFieldMapping } from "../repositories/IIntegrationAttributeSyncRepository";
import type { AttributeType } from "@calcom/prisma/enums";
const log = logger.getSubLogger({
prefix: ["[AttributeSyncFieldMappingService]"],
});
interface IAttributeSyncFieldMappingServiceDeps {
attributeToUserRepository: PrismaAttributeToUserRepository;
attributeRepository: PrismaAttributeRepository;
attributeOptionRepository: PrismaAttributeOptionRepository;
membershipRepository: MembershipRepository;
}
export class AttributeSyncFieldMappingService {
constructor(private readonly deps: IAttributeSyncFieldMappingServiceDeps) {}
async syncIntegrationFieldsToAttributes({
userId,
organizationId,
syncFieldMappings,
integrationFields,
}: {
userId: number;
organizationId: number;
syncFieldMappings: IFieldMapping[];
integrationFields: Record<string, string>;
}): Promise<void> {
const membership = await this.deps.membershipRepository.findUniqueByUserIdAndTeamId({
userId,
teamId: organizationId,
});
if (!membership) {
log.warn(
`No membership found for user ${userId} in org ${organizationId}`
);
return;
}
const memberId = membership.id;
const enabledSyncFieldMappings = syncFieldMappings.filter(
(mapping) =>
mapping.enabled &&
integrationFields[mapping.integrationFieldName] !== undefined
);
if (enabledSyncFieldMappings.length === 0) {
log.warn("No enabled mappings with matching integration fields");
return;
}
const attributeIds = enabledSyncFieldMappings.map((m) => m.attributeId);
const attributes =
await this.deps.attributeRepository.findManyByIdsAndOrgIdWithOptions({
attributeIds,
orgId: organizationId,
});
const attributeMap = new Map(attributes.map((a) => [a.id, a]));
const { attributeIdsToSync, optionsToCreate, assignmentsToCreate } =
this.processMappings({
enabledMappings: enabledSyncFieldMappings,
attributeMap,
integrationFields,
memberId,
orgId: organizationId,
});
if (optionsToCreate.length > 0) {
const newAssignments = await this.createOptionsAndGetAssignments({
optionsToCreate,
memberId,
orgId: organizationId,
});
assignmentsToCreate.push(...newAssignments);
}
// Delete old assignments before creating new ones
if (attributeIdsToSync.length > 0) {
await this.deps.attributeToUserRepository.deleteMany({
memberId,
attributeOption: {
attributeId: { in: attributeIdsToSync },
},
});
}
if (assignmentsToCreate.length > 0) {
await this.deps.attributeToUserRepository.createManySkipDuplicates(assignmentsToCreate);
log.info(
`Synced ${assignmentsToCreate.length} attribute(s) for member ${memberId}`
);
}
}
private processMappings({
enabledMappings,
attributeMap,
integrationFields,
memberId,
orgId,
}: {
enabledMappings: IFieldMapping[];
attributeMap: Map<
string,
{
id: string;
name: string;
type: AttributeType;
options: { id: string; value: string; slug: string }[];
}
>;
integrationFields: Record<string, unknown>;
memberId: number;
orgId: number;
}): {
attributeIdsToSync: string[];
optionsToCreate: Array<{
attributeId: string;
value: string;
slug: string;
}>;
assignmentsToCreate: Array<{ memberId: number; attributeOptionId: string }>;
} {
const attributeIdsToSync: string[] = [];
const optionsToCreate: Array<{
attributeId: string;
value: string;
slug: string;
}> = [];
const assignmentsToCreate: Array<{
memberId: number;
attributeOptionId: string;
}> = [];
for (const mapping of enabledMappings) {
const attribute = attributeMap.get(mapping.attributeId);
if (!attribute) {
log.warn(`Attribute ${mapping.attributeId} not found for org ${orgId}`);
continue;
}
const rawFieldValue = String(
integrationFields[mapping.integrationFieldName]
);
if (hasOptions({ attribute })) {
// SINGLE_SELECT / MULTI_SELECT - must find existing option
const isMultiSelect = doesSupportMultipleValues({ attribute });
// For MULTI_SELECT, process all comma-separated values; for SINGLE_SELECT, take the first only
const fieldValues = isMultiSelect
? rawFieldValue
.split(",")
.map((v) => v.trim())
.filter(Boolean)
: [rawFieldValue.split(",")[0].trim()].filter(Boolean);
// Always mark for sync so old assignments get cleared (even if field is blank)
attributeIdsToSync.push(attribute.id);
for (const fieldValue of fieldValues) {
const matchingOption = attribute.options.find(
(opt) => opt.value.toLowerCase() === fieldValue.toLowerCase()
);
if (!matchingOption) {
log.warn(
`No matching option for value "${fieldValue}" in attribute ${attribute.id} (${attribute.name})`
);
continue;
}
assignmentsToCreate.push({
memberId,
attributeOptionId: matchingOption.id,
});
}
} else if (canSetValueBeyondOptions({ attribute })) {
// TEXT / NUMBER - find existing option or create new one
// For TEXT/NUMBER, use first value if comma-separated
const fieldValue = rawFieldValue.split(",")[0].trim();
const existingOption = attribute.options.find(
(opt) => opt.value.toLowerCase() === fieldValue.toLowerCase()
);
attributeIdsToSync.push(attribute.id);
if (existingOption) {
assignmentsToCreate.push({
memberId,
attributeOptionId: existingOption.id,
});
} else {
// Need to create a new option
optionsToCreate.push({
attributeId: attribute.id,
value: fieldValue,
slug: buildSlugFromValue({ value: fieldValue }),
});
}
}
}
return { attributeIdsToSync, optionsToCreate, assignmentsToCreate };
}
private async createOptionsAndGetAssignments({
optionsToCreate,
memberId,
orgId,
}: {
optionsToCreate: Array<{
attributeId: string;
value: string;
slug: string;
}>;
memberId: number;
orgId: number;
}): Promise<Array<{ memberId: number; attributeOptionId: string }>> {
await this.deps.attributeOptionRepository.createMany({
createManyInput: optionsToCreate,
});
const allOptions = await this.deps.attributeOptionRepository.findMany({
orgId,
});
const optionLookup = new Map(
allOptions.map((o) => [`${o.attributeId}:${o.value.toLowerCase()}`, o])
);
const assignments: Array<{ memberId: number; attributeOptionId: string }> =
[];
for (const newOption of optionsToCreate) {
const key = `${newOption.attributeId}:${newOption.value.toLowerCase()}`;
const createdOption = optionLookup.get(key);
if (createdOption) {
assignments.push({
memberId,
attributeOptionId: createdOption.id,
});
} else {
log.error(
`Failed to find newly created option for attribute ${newOption.attributeId}`
);
}
}
return assignments;
}
}
@@ -0,0 +1,708 @@
import type { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import type { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
ConditionIdentifierEnum,
ConditionOperatorEnum,
type IAttributeSyncRule,
RuleOperatorEnum,
} from "../repositories/IIntegrationAttributeSyncRepository";
import { AttributeSyncRuleService } from "./AttributeSyncRuleService";
vi.mock("@calcom/features/attributes/di/AttributeService.container", () => ({
getAttributeService: vi.fn(() => ({
getUsersAttributesByOrgMembershipId: vi.fn(),
})),
}));
import { getAttributeService } from "@calcom/features/attributes/di/AttributeService.container";
describe("AttributeSyncRuleService", () => {
let service: AttributeSyncRuleService;
let mockMembershipRepository: {
findAllByUserId: ReturnType<typeof vi.fn>;
};
let mockAttributeToUserRepository: {
findManyIncludeAttribute: ReturnType<typeof vi.fn>;
};
let mockAttributeService: {
getUsersAttributesByOrgMembershipId: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.resetAllMocks();
mockMembershipRepository = {
findAllByUserId: vi.fn(),
};
mockAttributeToUserRepository = {
findManyIncludeAttribute: vi.fn(),
};
mockAttributeService = {
getUsersAttributesByOrgMembershipId: vi.fn(),
};
vi.mocked(getAttributeService).mockReturnValue(mockAttributeService);
service = new AttributeSyncRuleService({
membershipRepository: mockMembershipRepository as unknown as MembershipRepository,
attributeToUserRepository: mockAttributeToUserRepository as unknown as PrismaAttributeToUserRepository,
});
});
describe("shouldSyncApplyToUser", () => {
describe("team conditions", () => {
it("should return true when user is in specified team with IN operator and AND rule", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([
{ teamId: 10, accepted: true },
{ teamId: 30, accepted: true },
]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
expect(mockMembershipRepository.findAllByUserId).toHaveBeenCalledWith({
userId: 1,
filters: { accepted: true },
});
});
it("should return false when user is not in any specified team with IN operator and AND rule", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10, 20],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([
{ teamId: 30, accepted: true },
{ teamId: 40, accepted: true },
]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should return true when user is not in specified team with NOT_IN operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.NOT_IN,
value: [10],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([{ teamId: 20, accepted: true }]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return false when user is in specified team with NOT_IN operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.NOT_IN,
value: [10],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([{ teamId: 10, accepted: true }]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should evaluate multiple team IDs in a single condition - all must match for AND rule", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10, 20],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([
{ teamId: 10, accepted: true },
{ teamId: 20, accepted: true },
]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return false when user is not in all specified teams with IN operator and AND rule", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10, 20, 30],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([
{ teamId: 10, accepted: true },
{ teamId: 20, accepted: true },
]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should return true when user is in any specified team with IN operator and OR rule", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.OR,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10, 20, 30],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([{ teamId: 10, accepted: true }]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
});
describe("attribute conditions", () => {
it("should return true when user has matching SINGLE_SELECT attribute with EQUALS operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.EQUALS,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "option-1",
value: "Option 1",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return false when user has non-matching SINGLE_SELECT attribute with EQUALS operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.EQUALS,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "option-2",
value: "Option 2",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should return true when user has matching TEXT attribute with EQUALS operator (case-insensitive)", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.EQUALS,
value: ["ENGINEERING"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "TEXT",
optionId: null,
value: "engineering",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return true when user has MULTI_SELECT attribute containing all required options with IN operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.IN,
value: ["option-1", "option-2"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "MULTI_SELECT",
optionIds: new Set(["option-1", "option-2", "option-3"]),
values: new Set(["Option 1", "Option 2", "Option 3"]),
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return false when user has MULTI_SELECT attribute missing some required options with IN operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.IN,
value: ["option-1", "option-2"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "MULTI_SELECT",
optionIds: new Set(["option-1", "option-3"]),
values: new Set(["Option 1", "Option 3"]),
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should return true when user has MULTI_SELECT attribute without any excluded options with NOT_IN operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.NOT_IN,
value: ["option-4", "option-5"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "MULTI_SELECT",
optionIds: new Set(["option-1", "option-2"]),
values: new Set(["Option 1", "Option 2"]),
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return false when user has MULTI_SELECT attribute with some excluded options with NOT_IN operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.NOT_IN,
value: ["option-1", "option-5"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "MULTI_SELECT",
optionIds: new Set(["option-1", "option-2"]),
values: new Set(["Option 1", "Option 2"]),
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should return false when user does not have the attribute with IN/EQUALS operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.IN,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should return true when user does not have the attribute with NOT_IN/NOT_EQUALS operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.NOT_IN,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return true when user has non-matching SINGLE_SELECT attribute with NOT_EQUALS operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.NOT_EQUALS,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "option-2",
value: "Option 2",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
});
describe("rule operators", () => {
it("should return true with AND operator when all conditions pass", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10],
},
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.EQUALS,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([{ teamId: 10, accepted: true }]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "option-1",
value: "Option 1",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return false with AND operator when any condition fails", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10],
},
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.EQUALS,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([{ teamId: 10, accepted: true }]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "option-2",
value: "Option 2",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should return true with OR operator when any condition passes", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.OR,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10],
},
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.EQUALS,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([{ teamId: 20, accepted: true }]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "option-1",
value: "Option 1",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return false with OR operator when all conditions fail", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.OR,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10],
},
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.EQUALS,
value: ["option-1"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([{ teamId: 20, accepted: true }]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "option-2",
value: "Option 2",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
});
describe("edge cases", () => {
it("should return true with AND operator and empty conditions", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
it("should return false with OR operator and empty conditions", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.OR,
conditions: [],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should handle user with no team memberships", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.TEAM_ID,
operator: ConditionOperatorEnum.IN,
value: [10],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(false);
});
it("should handle NUMBER attribute type with EQUALS operator", async () => {
const user = { id: 1, organizationId: 100 };
const attributeSyncRule: IAttributeSyncRule = {
operator: RuleOperatorEnum.AND,
conditions: [
{
identifier: ConditionIdentifierEnum.ATTRIBUTE_ID,
attributeId: "attr-1",
operator: ConditionOperatorEnum.EQUALS,
value: ["42"],
},
],
};
mockMembershipRepository.findAllByUserId.mockResolvedValue([]);
mockAttributeService.getUsersAttributesByOrgMembershipId.mockResolvedValue({
"attr-1": {
type: "NUMBER",
optionId: null,
value: "42",
},
});
const result = await service.shouldSyncApplyToUser({ user, attributeSyncRule });
expect(result).toBe(true);
});
});
});
});
@@ -0,0 +1,197 @@
import { isTeamCondition, isAttributeCondition } from "../lib/ruleHelpers";
import {
ConditionOperatorEnum,
type IAttributeSyncRule,
type ITeamCondition,
type IAttributeCondition,
RuleOperatorEnum,
} from "../repositories/IIntegrationAttributeSyncRepository";
import type { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import type { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import { getAttributeService } from "@calcom/features/attributes/di/AttributeService.container";
import type { UserAttribute } from "@calcom/features/attributes/services/AttributeService";
interface IAttributeSyncRuleServiceDeps {
membershipRepository: MembershipRepository;
attributeToUserRepository: PrismaAttributeToUserRepository;
}
export class AttributeSyncRuleService {
constructor(private readonly deps: IAttributeSyncRuleServiceDeps) {}
async shouldSyncApplyToUser({
user,
attributeSyncRule,
}: {
user: { id: number; organizationId: number };
attributeSyncRule: IAttributeSyncRule;
}): Promise<boolean> {
const { operator: ruleOperator, conditions } = attributeSyncRule;
const teamConditions = conditions.filter(isTeamCondition);
const attributeConditions = conditions.filter(isAttributeCondition);
const conditionChecks = await Promise.all([
this.handleTeamConditions({ userId: user.id, teamConditions }),
this.handleAttributeConditions({ user, attributeConditions }),
]);
const conditionChecksFlattened = conditionChecks.flat();
if (ruleOperator === RuleOperatorEnum.AND) {
return !conditionChecksFlattened.some((condition) => !condition);
} else {
return conditionChecksFlattened.some((condition) => condition);
}
}
private async handleTeamConditions({
userId,
teamConditions,
}: {
userId: number;
teamConditions: ITeamCondition[];
}) {
const userMemberships =
await this.deps.membershipRepository.findAllByUserId({
userId,
filters: { accepted: true },
});
const userTeamIdSet = new Set(
userMemberships.map((membership) => membership.teamId)
);
const teamConditionEvaluated: boolean[] = [];
for (const teamCondition of teamConditions) {
const teamIds = teamCondition.value;
const conditionOperator = teamCondition.operator;
for (const teamId of teamIds) {
if (conditionOperator === ConditionOperatorEnum.IN) {
teamConditionEvaluated.push(userTeamIdSet.has(teamId));
}
if (conditionOperator === ConditionOperatorEnum.NOT_IN) {
teamConditionEvaluated.push(!userTeamIdSet.has(teamId));
}
}
}
return teamConditionEvaluated;
}
private async handleAttributeConditions({
user,
attributeConditions,
}: {
user: { id: number; organizationId: number };
attributeConditions: IAttributeCondition[];
}): Promise<boolean[]> {
const attributeService = getAttributeService();
const userAttributes =
await attributeService.getUsersAttributesByOrgMembershipId({
userId: user.id,
orgId: user.organizationId,
});
const attributeConditionResults: boolean[] = [];
for (const condition of attributeConditions) {
const userAttribute = userAttributes[condition.attributeId];
const result = this.evaluateAttributeCondition(userAttribute, condition);
attributeConditionResults.push(result);
}
return attributeConditionResults;
}
private evaluateAttributeCondition(
userAttribute: UserAttribute | undefined,
condition: IAttributeCondition
): boolean {
const { operator } = condition;
if (!userAttribute) {
if (
operator === ConditionOperatorEnum.IN ||
operator === ConditionOperatorEnum.EQUALS
) {
return false;
}
// For NOT_IN/NOT_EQUALS: user doesn't have attribute, condition passes
return true;
}
if (userAttribute.type === "MULTI_SELECT") {
return this.evaluateMultiSelectCondition(
userAttribute,
operator,
condition
);
} else {
return this.evaluateSingleValueCondition(
userAttribute,
operator,
condition
);
}
}
private evaluateMultiSelectCondition(
userAttribute: Extract<UserAttribute, { type: "MULTI_SELECT" }>,
operator: ConditionOperatorEnum,
condition: IAttributeCondition
): boolean {
const userAttributeOptionIds = userAttribute.optionIds;
const conditionAttributeOptionIds = condition.value;
switch (operator) {
case ConditionOperatorEnum.IN:
return conditionAttributeOptionIds.every((id) =>
userAttributeOptionIds.has(id)
);
case ConditionOperatorEnum.NOT_IN:
return !conditionAttributeOptionIds.some((id) =>
userAttributeOptionIds.has(id)
);
default:
return false;
}
}
private evaluateSingleValueCondition(
userAttribute: Extract<
UserAttribute,
{ type: "TEXT" | "NUMBER" | "SINGLE_SELECT" }
>,
operator: ConditionOperatorEnum,
condition: IAttributeCondition
): boolean {
// For SINGLE_SELECT: condition stores option IDs, compare against optionId (exact match)
// For TEXT/NUMBER: condition stores actual values, compare against value (case-insensitive)
const isSingleSelect = userAttribute.type === "SINGLE_SELECT";
const userValue = isSingleSelect
? userAttribute.optionId
: userAttribute.value?.toLowerCase() ?? null;
const conditionValue = isSingleSelect
? condition.value[0] ?? null
: condition.value[0]?.toLowerCase() ?? null;
switch (operator) {
case ConditionOperatorEnum.EQUALS:
return userValue === conditionValue;
case ConditionOperatorEnum.NOT_EQUALS:
return userValue !== conditionValue;
default:
return false;
}
}
}
@@ -1,10 +1,14 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
import type { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { enabledAppSlugs } from "../constants";
import type { IIntegrationAttributeSyncRepository } from "../repositories/IIntegrationAttributeSyncRepository";
import { IntegrationAttributeSyncService, UnauthorizedAttributeError } from "./IntegrationAttributeSyncService";
import {
IntegrationAttributeSyncService,
UnauthorizedAttributeError,
} from "./IntegrationAttributeSyncService";
describe("IntegrationAttributeSyncService", () => {
let service: IntegrationAttributeSyncService;
@@ -20,6 +24,9 @@ describe("IntegrationAttributeSyncService", () => {
updateTransactionWithRuleAndMappings: ReturnType<typeof vi.fn>;
deleteById: ReturnType<typeof vi.fn>;
};
let mockTeamRepository: {
findTeamsNotBelongingToOrgByIds: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.resetAllMocks();
@@ -38,10 +45,15 @@ describe("IntegrationAttributeSyncService", () => {
deleteById: vi.fn(),
};
mockTeamRepository = {
findTeamsNotBelongingToOrgByIds: vi.fn(),
};
service = new IntegrationAttributeSyncService({
credentialRepository: mockCredentialRepository as unknown as CredentialRepository,
integrationAttributeSyncRepository:
mockIntegrationAttributeSyncRepository as unknown as IIntegrationAttributeSyncRepository,
teamRepository: mockTeamRepository as unknown as TeamRepository,
});
});
@@ -171,6 +183,7 @@ describe("IntegrationAttributeSyncService", () => {
mockIntegrationAttributeSyncRepository.getAttributeIdsByOrganization.mockResolvedValue(["attr-1", "attr-2"]);
mockIntegrationAttributeSyncRepository.getSyncFieldMappings.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings.mockResolvedValue(undefined);
mockTeamRepository.findTeamsNotBelongingToOrgByIds.mockResolvedValue([]);
await service.updateIncludeRulesAndMappings(formData);
@@ -208,6 +221,7 @@ describe("IntegrationAttributeSyncService", () => {
{ id: "mapping-2", integrationFieldName: "field2", attributeId: "attr-2", enabled: true },
]);
mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings.mockResolvedValue(undefined);
mockTeamRepository.findTeamsNotBelongingToOrgByIds.mockResolvedValue([]);
await service.updateIncludeRulesAndMappings(formData);
@@ -245,6 +259,7 @@ describe("IntegrationAttributeSyncService", () => {
{ id: "mapping-3", integrationFieldName: "field3", attributeId: "attr-3", enabled: true },
]);
mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings.mockResolvedValue(undefined);
mockTeamRepository.findTeamsNotBelongingToOrgByIds.mockResolvedValue([]);
await service.updateIncludeRulesAndMappings(formData);
@@ -282,6 +297,7 @@ describe("IntegrationAttributeSyncService", () => {
{ id: "mapping-2", integrationFieldName: "field2", attributeId: "attr-2", enabled: true },
]);
mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings.mockResolvedValue(undefined);
mockTeamRepository.findTeamsNotBelongingToOrgByIds.mockResolvedValue([]);
await service.updateIncludeRulesAndMappings(formData);
@@ -412,6 +428,7 @@ describe("IntegrationAttributeSyncService", () => {
mockIntegrationAttributeSyncRepository.getAttributeIdsByOrganization.mockResolvedValue(["attr-1", "attr-2"]);
mockIntegrationAttributeSyncRepository.getSyncFieldMappings.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings.mockResolvedValue(undefined);
mockTeamRepository.findTeamsNotBelongingToOrgByIds.mockResolvedValue([]);
await expect(service.updateIncludeRulesAndMappings(formData)).resolves.not.toThrow();
});
@@ -426,6 +443,7 @@ describe("IntegrationAttributeSyncService", () => {
mockIntegrationAttributeSyncRepository.getAttributeIdsByOrganization.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.getSyncFieldMappings.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings.mockResolvedValue(undefined);
mockTeamRepository.findTeamsNotBelongingToOrgByIds.mockResolvedValue([]);
await expect(service.updateIncludeRulesAndMappings(formData)).resolves.not.toThrow();
});
@@ -441,4 +459,103 @@ describe("IntegrationAttributeSyncService", () => {
expect(mockIntegrationAttributeSyncRepository.deleteById).toHaveBeenCalledWith(syncId);
});
});
describe("team validation", () => {
describe("updateIncludeRulesAndMappings", () => {
const baseFormData = {
id: "sync-123",
name: "Test Sync",
credentialId: 1,
enabled: true,
organizationId: 123,
ruleId: "rule-123",
syncFieldMappings: [],
};
it("should throw error when team IDs do not belong to organization", async () => {
const formData = {
...baseFormData,
rule: {
operator: "AND" as const,
conditions: [
{
identifier: "teamId" as const,
operator: "equals" as const,
value: [1, 2, 3],
},
],
},
};
mockIntegrationAttributeSyncRepository.getMappedAttributeIdsByOrganization.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.getAttributeIdsByOrganization.mockResolvedValue([]);
mockTeamRepository.findTeamsNotBelongingToOrgByIds.mockResolvedValue([{ id: 2 }, { id: 3 }]);
await expect(service.updateIncludeRulesAndMappings(formData)).rejects.toThrow(
"Teams do not belong to this organization: 2, 3"
);
expect(mockTeamRepository.findTeamsNotBelongingToOrgByIds).toHaveBeenCalledWith({
teamIds: [1, 2, 3],
orgId: 123,
});
});
it("should not validate teams when no team conditions in rule", async () => {
const formData = {
...baseFormData,
rule: {
operator: "OR" as const,
conditions: [
{
identifier: "attributeId" as const,
attributeId: "attr-123",
operator: "in" as const,
value: ["option-1"],
},
],
},
};
mockIntegrationAttributeSyncRepository.getMappedAttributeIdsByOrganization.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.getAttributeIdsByOrganization.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.getSyncFieldMappings.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings.mockResolvedValue(undefined);
await service.updateIncludeRulesAndMappings(formData);
expect(mockTeamRepository.findTeamsNotBelongingToOrgByIds).not.toHaveBeenCalled();
});
it("should proceed when all team IDs belong to organization", async () => {
const formData = {
...baseFormData,
rule: {
operator: "AND" as const,
conditions: [
{
identifier: "teamId" as const,
operator: "equals" as const,
value: [1, 2],
},
],
},
};
mockTeamRepository.findTeamsNotBelongingToOrgByIds.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.getMappedAttributeIdsByOrganization.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.getAttributeIdsByOrganization.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.getSyncFieldMappings.mockResolvedValue([]);
mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings.mockResolvedValue(undefined);
await service.updateIncludeRulesAndMappings(formData);
expect(mockTeamRepository.findTeamsNotBelongingToOrgByIds).toHaveBeenCalledWith({
teamIds: [1, 2],
orgId: 123,
});
expect(mockIntegrationAttributeSyncRepository.updateTransactionWithRuleAndMappings).toHaveBeenCalled();
});
});
});
});
@@ -1,11 +1,15 @@
import type { CredentialRepository } from "@calcom/features/credentials/repositories/CredentialRepository";
import type { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import type { ZCreateAttributeSyncSchema } from "@calcom/trpc/server/routers/viewer/attribute-sync/createAttributeSync.schema";
import { enabledAppSlugs } from "../constants";
import {
type IIntegrationAttributeSyncRepository,
type ISyncFormData,
type ITeamCondition,
type IAttributeSyncRule,
AttributeSyncIntegrations,
ConditionIdentifierEnum,
} from "../repositories/IIntegrationAttributeSyncRepository";
import { attributeSyncRuleSchema } from "../schemas/zod";
@@ -40,11 +44,42 @@ export class CredentialNotFoundError extends Error {
interface IIntegrationAttributeSyncServiceDeps {
credentialRepository: CredentialRepository;
integrationAttributeSyncRepository: IIntegrationAttributeSyncRepository;
teamRepository: TeamRepository;
}
export class IntegrationAttributeSyncService {
constructor(private readonly deps: IIntegrationAttributeSyncServiceDeps) {}
private extractTeamIdsFromRule(rule: IAttributeSyncRule): number[] {
return rule.conditions
.filter(
(c): c is ITeamCondition =>
c.identifier === ConditionIdentifierEnum.TEAM_ID
)
.flatMap((c) => c.value);
}
private async validateTeamsBelongToOrg(
teamIds: number[],
organizationId: number
): Promise<void> {
if (teamIds.length === 0) return;
const invalidTeams =
await this.deps.teamRepository.findTeamsNotBelongingToOrgByIds({
teamIds,
orgId: organizationId,
});
if (invalidTeams.length > 0) {
throw new Error(
`Teams do not belong to this organization: ${invalidTeams
.map((t) => t.id)
.join(", ")}`
);
}
}
private validateWithinSyncUniqueness(
mappings: { attributeId: string }[]
): void {
@@ -125,6 +160,9 @@ export class IntegrationAttributeSyncService {
const parsedRule = attributeSyncRuleSchema.parse(input.rule);
const teamIds = this.extractTeamIdsFromRule(parsedRule);
await this.validateTeamsBelongToOrg(teamIds, organizationId);
const integrationValue = credential.app?.slug || credential.type;
if (
!Object.values(AttributeSyncIntegrations).includes(
@@ -177,6 +215,9 @@ export class IntegrationAttributeSyncService {
const parsedRule = attributeSyncRuleSchema.parse(rule);
const teamIds = this.extractTeamIdsFromRule(parsedRule);
await this.validateTeamsBelongToOrg(teamIds, data.organizationId);
const incomingMappingIds = new Set(
syncFieldMappings.reduce((ids, mapping) => {
if ("id" in mapping) ids.push(mapping.id);
@@ -209,4 +250,10 @@ export class IntegrationAttributeSyncService {
async deleteById(id: string) {
return this.deps.integrationAttributeSyncRepository.deleteById(id);
}
async getAllByCredentialId(credentialId: number) {
return this.deps.integrationAttributeSyncRepository.getAllByCredentialId(
credentialId
);
}
}