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,14 @@
import { createContainer } from "@calcom/features/di/di";
import {
type AttributeService,
moduleLoader as attributeServiceModule,
} from "./AttributeService.module";
const attributeServiceContainer = createContainer();
export function getAttributeService(): AttributeService {
attributeServiceModule.loadModule(attributeServiceContainer);
return attributeServiceContainer.get<AttributeService>(attributeServiceModule.token);
}
@@ -0,0 +1,29 @@
import {
bindModuleToClassOnToken,
createModule,
type ModuleLoader,
} from "@calcom/features/di/di";
import { AttributeService } from "../services/AttributeService";
import { moduleLoader as attributeToUserRepositoryModuleLoader } from "./AttributeToUserRepository.module";
import { ATTRIBUTE_DI_TOKENS } from "./tokens";
export const attributeServiceModule = createModule();
const token = ATTRIBUTE_DI_TOKENS.ATTRIBUTE_SERVICE;
const moduleToken = ATTRIBUTE_DI_TOKENS.ATTRIBUTE_SERVICE_MODULE;
const loadModule = bindModuleToClassOnToken({
module: attributeServiceModule,
moduleToken,
token,
classs: AttributeService,
depsMap: {
attributeToUserRepository: attributeToUserRepositoryModuleLoader,
},
});
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
export type { AttributeService };
@@ -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 "../repositories/PrismaAttributeToUserRepository";
import { ATTRIBUTE_DI_TOKENS } from "./tokens";
export const attributeToUserRepositoryModule = createModule();
const token = ATTRIBUTE_DI_TOKENS.ATTRIBUTE_TO_USER_REPOSITORY;
const moduleToken = ATTRIBUTE_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 };
@@ -0,0 +1,6 @@
export const ATTRIBUTE_DI_TOKENS = {
ATTRIBUTE_SERVICE: Symbol("AttributeService"),
ATTRIBUTE_SERVICE_MODULE: Symbol("AttributeServiceModule"),
ATTRIBUTE_TO_USER_REPOSITORY: Symbol("AttributeToUserRepository"),
ATTRIBUTE_TO_USER_REPOSITORY_MODULE: Symbol("AttributeToUserRepositoryModule"),
};
@@ -1,9 +1,11 @@
import { prisma } from "@calcom/prisma";
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
export class PrismaAttributeOptionRepository {
static async findMany({ orgId }: { orgId: number }) {
return prisma.attributeOption.findMany({
constructor(private prismaClient: PrismaClient) {}
async findMany({ orgId }: { orgId: number }) {
return this.prismaClient.attributeOption.findMany({
where: {
attribute: {
teamId: orgId,
@@ -18,8 +20,8 @@ export class PrismaAttributeOptionRepository {
});
}
static async createMany({ createManyInput }: { createManyInput: Prisma.AttributeOptionCreateManyInput[] }) {
const { count } = await prisma.attributeOption.createMany({
async createMany({ createManyInput }: { createManyInput: Prisma.AttributeOptionCreateManyInput[] }) {
const { count } = await this.prismaClient.attributeOption.createMany({
data: createManyInput,
});
@@ -96,4 +96,30 @@ export class PrismaAttributeRepository {
},
});
}
findManyByIdsAndOrgIdWithOptions({
attributeIds,
orgId,
}: {
attributeIds: string[];
orgId: number;
}) {
return this.prismaClient.attribute.findMany({
where: {
teamId: orgId,
id: {
in: attributeIds,
},
},
include: {
options: {
select: {
id: true,
value: true,
slug: true,
},
},
},
});
}
}
@@ -0,0 +1,68 @@
import type { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import { AttributeType } from "@calcom/prisma/enums";
interface IAttributeServiceDeps {
attributeToUserRepository: PrismaAttributeToUserRepository;
}
type MultiSelectAttribute = {
type: "MULTI_SELECT";
optionIds: Set<string>;
values: Set<string>;
};
type SingleValueAttribute = {
type: "TEXT" | "NUMBER" | "SINGLE_SELECT";
optionId: string | null;
value: string | null;
};
export type UserAttribute = MultiSelectAttribute | SingleValueAttribute;
export class AttributeService {
constructor(private readonly deps: IAttributeServiceDeps) {}
/** Grouped by attribute */
async getUsersAttributesByOrgMembershipId({
userId,
orgId,
}: {
userId: number;
orgId: number;
}): Promise<Record<string, UserAttribute>> {
const attributeOptionsAssignedToUser =
await this.deps.attributeToUserRepository.findManyIncludeAttribute({
member: { userId, teamId: orgId },
});
const userAttributes: Record<string, UserAttribute> = {};
for (const assignedAttribute of attributeOptionsAssignedToUser) {
const attribute = assignedAttribute.attributeOption.attribute;
const attributeOptionId = assignedAttribute.attributeOptionId;
const attributeValue = assignedAttribute.attributeOption.value;
if (attribute.type === AttributeType.MULTI_SELECT) {
if (attribute.id in userAttributes) {
const existing = userAttributes[attribute.id] as MultiSelectAttribute;
existing.optionIds.add(attributeOptionId);
existing.values.add(attributeValue);
} else {
userAttributes[attribute.id] = {
type: "MULTI_SELECT",
optionIds: new Set([attributeOptionId]),
values: new Set([attributeValue]),
};
}
} else {
// For TEXT, NUMBER, SINGLE_SELECT - only store single value
userAttributes[attribute.id] = {
type: attribute.type as "TEXT" | "NUMBER" | "SINGLE_SELECT",
optionId: attributeOptionId,
value: attributeValue,
};
}
}
return userAttributes;
}
}
@@ -0,0 +1,318 @@
import type { PrismaAttributeToUserRepository } from "@calcom/features/attributes/repositories/PrismaAttributeToUserRepository";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AttributeService } from "./AttributeService";
describe("AttributeService", () => {
let service: AttributeService;
let mockAttributeToUserRepository: {
findManyIncludeAttribute: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.resetAllMocks();
mockAttributeToUserRepository = {
findManyIncludeAttribute: vi.fn(),
};
service = new AttributeService({
attributeToUserRepository:
mockAttributeToUserRepository as unknown as PrismaAttributeToUserRepository,
});
});
describe("getUsersAttributesByOrgMembershipId", () => {
it("should return empty object when user has no attributes", async () => {
mockAttributeToUserRepository.findManyIncludeAttribute.mockResolvedValue(
[]
);
const result = await service.getUsersAttributesByOrgMembershipId({
userId: 1,
orgId: 100,
});
expect(result).toEqual({});
expect(
mockAttributeToUserRepository.findManyIncludeAttribute
).toHaveBeenCalledWith({
member: { userId: 1, teamId: 100 },
});
});
it("should return SINGLE_SELECT attribute correctly", async () => {
mockAttributeToUserRepository.findManyIncludeAttribute.mockResolvedValue([
{
attributeOptionId: "opt-1",
attributeOption: {
value: "Engineering",
attribute: {
id: "attr-1",
type: "SINGLE_SELECT",
},
},
},
]);
const result = await service.getUsersAttributesByOrgMembershipId({
userId: 1,
orgId: 100,
});
expect(result).toEqual({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "opt-1",
value: "Engineering",
},
});
});
it("should return TEXT attribute correctly", async () => {
mockAttributeToUserRepository.findManyIncludeAttribute.mockResolvedValue([
{
attributeOptionId: "opt-1",
attributeOption: {
value: "Senior Engineer",
attribute: {
id: "attr-1",
type: "TEXT",
},
},
},
]);
const result = await service.getUsersAttributesByOrgMembershipId({
userId: 1,
orgId: 100,
});
expect(result).toEqual({
"attr-1": {
type: "TEXT",
optionId: "opt-1",
value: "Senior Engineer",
},
});
});
it("should return NUMBER attribute correctly", async () => {
mockAttributeToUserRepository.findManyIncludeAttribute.mockResolvedValue([
{
attributeOptionId: "opt-1",
attributeOption: {
value: "42",
attribute: {
id: "attr-1",
type: "NUMBER",
},
},
},
]);
const result = await service.getUsersAttributesByOrgMembershipId({
userId: 1,
orgId: 100,
});
expect(result).toEqual({
"attr-1": {
type: "NUMBER",
optionId: "opt-1",
value: "42",
},
});
});
it("should return MULTI_SELECT attribute with multiple options correctly", async () => {
mockAttributeToUserRepository.findManyIncludeAttribute.mockResolvedValue([
{
attributeOptionId: "opt-1",
attributeOption: {
value: "JavaScript",
attribute: {
id: "attr-1",
type: "MULTI_SELECT",
},
},
},
{
attributeOptionId: "opt-2",
attributeOption: {
value: "TypeScript",
attribute: {
id: "attr-1",
type: "MULTI_SELECT",
},
},
},
{
attributeOptionId: "opt-3",
attributeOption: {
value: "Python",
attribute: {
id: "attr-1",
type: "MULTI_SELECT",
},
},
},
]);
const result = await service.getUsersAttributesByOrgMembershipId({
userId: 1,
orgId: 100,
});
expect(result).toEqual({
"attr-1": {
type: "MULTI_SELECT",
optionIds: new Set(["opt-1", "opt-2", "opt-3"]),
values: new Set(["JavaScript", "TypeScript", "Python"]),
},
});
});
it("should handle multiple attributes of different types", async () => {
mockAttributeToUserRepository.findManyIncludeAttribute.mockResolvedValue([
{
attributeOptionId: "opt-1",
attributeOption: {
value: "Engineering",
attribute: {
id: "attr-1",
type: "SINGLE_SELECT",
},
},
},
{
attributeOptionId: "opt-2",
attributeOption: {
value: "JavaScript",
attribute: {
id: "attr-2",
type: "MULTI_SELECT",
},
},
},
{
attributeOptionId: "opt-3",
attributeOption: {
value: "TypeScript",
attribute: {
id: "attr-2",
type: "MULTI_SELECT",
},
},
},
{
attributeOptionId: "opt-4",
attributeOption: {
value: "Senior Engineer",
attribute: {
id: "attr-3",
type: "TEXT",
},
},
},
]);
const result = await service.getUsersAttributesByOrgMembershipId({
userId: 1,
orgId: 100,
});
expect(result).toEqual({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "opt-1",
value: "Engineering",
},
"attr-2": {
type: "MULTI_SELECT",
optionIds: new Set(["opt-2", "opt-3"]),
values: new Set(["JavaScript", "TypeScript"]),
},
"attr-3": {
type: "TEXT",
optionId: "opt-4",
value: "Senior Engineer",
},
});
});
it("should overwrite SINGLE_SELECT attribute if multiple values exist (last one wins)", async () => {
mockAttributeToUserRepository.findManyIncludeAttribute.mockResolvedValue([
{
attributeOptionId: "opt-1",
attributeOption: {
value: "Engineering",
attribute: {
id: "attr-1",
type: "SINGLE_SELECT",
},
},
},
{
attributeOptionId: "opt-2",
attributeOption: {
value: "Sales",
attribute: {
id: "attr-1",
type: "SINGLE_SELECT",
},
},
},
]);
const result = await service.getUsersAttributesByOrgMembershipId({
userId: 1,
orgId: 100,
});
expect(result).toEqual({
"attr-1": {
type: "SINGLE_SELECT",
optionId: "opt-2",
value: "Sales",
},
});
});
it("should accumulate MULTI_SELECT options correctly", async () => {
mockAttributeToUserRepository.findManyIncludeAttribute.mockResolvedValue([
{
attributeOptionId: "opt-1",
attributeOption: {
value: "Skill A",
attribute: {
id: "attr-1",
type: "MULTI_SELECT",
},
},
},
{
attributeOptionId: "opt-1",
attributeOption: {
value: "Skill A",
attribute: {
id: "attr-1",
type: "MULTI_SELECT",
},
},
},
]);
const result = await service.getUsersAttributesByOrgMembershipId({
userId: 1,
orgId: 100,
});
expect(result["attr-1"]).toEqual({
type: "MULTI_SELECT",
optionIds: new Set(["opt-1"]),
values: new Set(["Skill A"]),
});
});
});
});