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:
43 files changed
+3438
-105
No files matched your search
@@ -3,7 +3,10 @@ import type { z } from "zod";
|
||||
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { getParsedTeam } from "@calcom/features/ee/teams/lib/getParsedTeam";
|
||||
import { ProfileRepository } from "@calcom/features/profile/repositories/ProfileRepository";
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
|
||||
import {
|
||||
DEFAULT_SCHEDULE,
|
||||
getAvailabilityFromSchedule,
|
||||
} from "@calcom/lib/availability";
|
||||
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
@@ -11,7 +14,11 @@ import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { withSelectedCalendars } from "@calcom/lib/server/withSelectedCalendars";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { availabilityUserSelect } from "@calcom/prisma";
|
||||
import type { User as UserType, DestinationCalendar, SelectedCalendar } from "@calcom/prisma/client";
|
||||
import type {
|
||||
User as UserType,
|
||||
DestinationCalendar,
|
||||
SelectedCalendar,
|
||||
} from "@calcom/prisma/client";
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
import type { CreationSource } from "@calcom/prisma/enums";
|
||||
import { MembershipRole, BookingStatus } from "@calcom/prisma/enums";
|
||||
@@ -120,6 +127,7 @@ const userSelect = {
|
||||
lastActiveAt: true,
|
||||
identityProvider: true,
|
||||
teams: true,
|
||||
profiles: true,
|
||||
} satisfies Prisma.UserSelect;
|
||||
|
||||
export class UserRepository {
|
||||
@@ -137,8 +145,12 @@ export class UserRepository {
|
||||
},
|
||||
});
|
||||
|
||||
const acceptedTeamMemberships = teamMemberships.filter((membership) => membership.accepted);
|
||||
const pendingTeamMemberships = teamMemberships.filter((membership) => !membership.accepted);
|
||||
const acceptedTeamMemberships = teamMemberships.filter(
|
||||
(membership) => membership.accepted
|
||||
);
|
||||
const pendingTeamMemberships = teamMemberships.filter(
|
||||
(membership) => !membership.accepted
|
||||
);
|
||||
|
||||
return {
|
||||
teams: acceptedTeamMemberships.map((membership) => membership.team),
|
||||
@@ -157,7 +169,9 @@ export class UserRepository {
|
||||
(membership) => membership.team.isOrganization
|
||||
);
|
||||
|
||||
const organizations = acceptedOrgMemberships.map((membership) => membership.team);
|
||||
const organizations = acceptedOrgMemberships.map(
|
||||
(membership) => membership.team
|
||||
);
|
||||
|
||||
return {
|
||||
organizations,
|
||||
@@ -167,11 +181,18 @@ export class UserRepository {
|
||||
/**
|
||||
* It is aware of the fact that a user can be part of multiple organizations.
|
||||
*/
|
||||
async findUsersByUsername({ orgSlug, usernameList }: { orgSlug: string | null; usernameList: string[] }) {
|
||||
const { where, profiles } = await this._getWhereClauseForFindingUsersByUsername({
|
||||
orgSlug,
|
||||
usernameList,
|
||||
});
|
||||
async findUsersByUsername({
|
||||
orgSlug,
|
||||
usernameList,
|
||||
}: {
|
||||
orgSlug: string | null;
|
||||
usernameList: string[];
|
||||
}) {
|
||||
const { where, profiles } =
|
||||
await this._getWhereClauseForFindingUsersByUsername({
|
||||
orgSlug,
|
||||
usernameList,
|
||||
});
|
||||
|
||||
return (
|
||||
await this.prismaClient.user.findMany({
|
||||
@@ -186,9 +207,13 @@ export class UserRepository {
|
||||
profile: ProfileRepository.buildPersonalProfileFromUser({ user }),
|
||||
};
|
||||
}
|
||||
const profile = profiles.find((profile) => profile.user.id === user.id) ?? null;
|
||||
const profile =
|
||||
profiles.find((profile) => profile.user.id === user.id) ?? null;
|
||||
if (!profile) {
|
||||
log.error("Profile not found for user", safeStringify({ user, profiles }));
|
||||
log.error(
|
||||
"Profile not found for user",
|
||||
safeStringify({ user, profiles })
|
||||
);
|
||||
// Profile must be there because profile itself was used to retrieve the user
|
||||
throw new Error("Profile couldn't be found");
|
||||
}
|
||||
@@ -200,7 +225,11 @@ export class UserRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async findPlatformMembersByUsernames({ usernameList }: { usernameList: string[] }) {
|
||||
async findPlatformMembersByUsernames({
|
||||
usernameList,
|
||||
}: {
|
||||
usernameList: string[];
|
||||
}) {
|
||||
return (
|
||||
await this.prismaClient.user.findMany({
|
||||
select: userSelect,
|
||||
@@ -259,7 +288,8 @@ export class UserRepository {
|
||||
},
|
||||
...(orgSlug
|
||||
? {
|
||||
organization: whereClauseForOrgWithSlugOrRequestedSlug(orgSlug),
|
||||
organization:
|
||||
whereClauseForOrgWithSlugOrRequestedSlug(orgSlug),
|
||||
}
|
||||
: {
|
||||
organization: null,
|
||||
@@ -278,7 +308,11 @@ export class UserRepository {
|
||||
return user;
|
||||
}
|
||||
|
||||
async findManyByEmailsWithEmailVerificationSettings({ emails }: { emails: string[] }) {
|
||||
async findManyByEmailsWithEmailVerificationSettings({
|
||||
emails,
|
||||
}: {
|
||||
emails: string[];
|
||||
}) {
|
||||
const normalizedEmails = emails.map((e) => e.toLowerCase());
|
||||
|
||||
if (!normalizedEmails.length) return [];
|
||||
@@ -365,7 +399,8 @@ export class UserRepository {
|
||||
return null;
|
||||
}
|
||||
|
||||
const allProfiles = await ProfileRepository.findAllProfilesForUserIncludingMovedUser(user);
|
||||
const allProfiles =
|
||||
await ProfileRepository.findAllProfilesForUserIncludingMovedUser(user);
|
||||
return {
|
||||
...user,
|
||||
allProfiles,
|
||||
@@ -454,7 +489,9 @@ export class UserRepository {
|
||||
user: { profiles: { organizationId: number }[] };
|
||||
organizationId: number;
|
||||
}) {
|
||||
return user.profiles.some((profile) => profile.organizationId === organizationId);
|
||||
return user.profiles.some(
|
||||
(profile) => profile.organizationId === organizationId
|
||||
);
|
||||
}
|
||||
|
||||
async findIfAMemberOfSomeOrganization({ user }: { user: { id: number } }) {
|
||||
@@ -477,7 +514,11 @@ export class UserRepository {
|
||||
return !!user.metadata?.migratedToOrgFrom;
|
||||
}
|
||||
|
||||
async isMovedToAProfile({ user }: { user: Pick<UserType, "movedToProfileId"> }) {
|
||||
async isMovedToAProfile({
|
||||
user,
|
||||
}: {
|
||||
user: Pick<UserType, "movedToProfileId">;
|
||||
}) {
|
||||
return !!user.movedToProfileId;
|
||||
}
|
||||
|
||||
@@ -519,13 +560,9 @@ export class UserRepository {
|
||||
return updatedUser;
|
||||
}
|
||||
|
||||
async enrichUserWithTheProfile<T extends { username: string | null; id: number }>({
|
||||
user,
|
||||
upId,
|
||||
}: {
|
||||
user: T;
|
||||
upId: UpId;
|
||||
}) {
|
||||
async enrichUserWithTheProfile<
|
||||
T extends { username: string | null; id: number }
|
||||
>({ user, upId }: { user: T; upId: UpId }) {
|
||||
const profile = await ProfileRepository.findByUpIdWithAuth(upId, user.id);
|
||||
if (!profile) {
|
||||
return {
|
||||
@@ -628,7 +665,9 @@ export class UserRepository {
|
||||
};
|
||||
}
|
||||
|
||||
async enrichUsersWithTheirProfiles<T extends { id: number; username: string | null }>(
|
||||
async enrichUsersWithTheirProfiles<
|
||||
T extends { id: number; username: string | null }
|
||||
>(
|
||||
users: T[]
|
||||
): Promise<
|
||||
Array<
|
||||
@@ -655,7 +694,10 @@ export class UserRepository {
|
||||
// Precompute personal profiles for all users
|
||||
const personalProfileMap = new Map<number, UserProfile>();
|
||||
users.forEach((user) => {
|
||||
personalProfileMap.set(user.id, ProfileRepository.buildPersonalProfileFromUser({ user }));
|
||||
personalProfileMap.set(
|
||||
user.id,
|
||||
ProfileRepository.buildPersonalProfileFromUser({ user })
|
||||
);
|
||||
});
|
||||
|
||||
return users.map((user) => {
|
||||
@@ -687,7 +729,9 @@ export class UserRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async enrichUsersWithTheirProfileExcludingOrgMetadata<T extends { id: number; username: string | null }>(
|
||||
async enrichUsersWithTheirProfileExcludingOrgMetadata<
|
||||
T extends { id: number; username: string | null }
|
||||
>(
|
||||
users: T[]
|
||||
): Promise<
|
||||
Array<
|
||||
@@ -723,7 +767,9 @@ export class UserRepository {
|
||||
});
|
||||
}
|
||||
|
||||
enrichUserWithItsProfileBuiltFromUser<T extends { id: number; username: string | null }>({
|
||||
enrichUserWithItsProfileBuiltFromUser<
|
||||
T extends { id: number; username: string | null }
|
||||
>({
|
||||
user,
|
||||
}: {
|
||||
user: T;
|
||||
@@ -787,7 +833,9 @@ export class UserRepository {
|
||||
if (!profiles.length) {
|
||||
return {
|
||||
...entity,
|
||||
profile: ProfileRepository.buildPersonalProfileFromUser({ user: entity.user }),
|
||||
profile: ProfileRepository.buildPersonalProfileFromUser({
|
||||
user: entity.user,
|
||||
}),
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
@@ -824,7 +872,10 @@ export class UserRepository {
|
||||
}
|
||||
|
||||
async create(
|
||||
data: Omit<Prisma.UserCreateInput, "password" | "organization" | "movedToProfile"> & {
|
||||
data: Omit<
|
||||
Prisma.UserCreateInput,
|
||||
"password" | "organization" | "movedToProfile"
|
||||
> & {
|
||||
username: string;
|
||||
hashedPassword?: string;
|
||||
organizationId: number | null;
|
||||
@@ -833,9 +884,15 @@ export class UserRepository {
|
||||
}
|
||||
) {
|
||||
const organizationIdValue = data.organizationId;
|
||||
const { email, username, creationSource, locked, hashedPassword, ...rest } = data;
|
||||
const { email, username, creationSource, locked, hashedPassword, ...rest } =
|
||||
data;
|
||||
|
||||
logger.info("create user", { email, username, organizationIdValue, locked });
|
||||
logger.info("create user", {
|
||||
email,
|
||||
username,
|
||||
organizationIdValue,
|
||||
locked,
|
||||
});
|
||||
const t = await getTranslation("en", "common");
|
||||
const availability = getAvailabilityFromSchedule(DEFAULT_SCHEDULE);
|
||||
|
||||
@@ -843,7 +900,9 @@ export class UserRepository {
|
||||
data: {
|
||||
username,
|
||||
email: email,
|
||||
...(hashedPassword && { password: { create: { hash: hashedPassword } } }),
|
||||
...(hashedPassword && {
|
||||
password: { create: { hash: hashedPassword } },
|
||||
}),
|
||||
// Default schedule
|
||||
schedules: {
|
||||
create: {
|
||||
@@ -902,7 +961,9 @@ export class UserRepository {
|
||||
members: {
|
||||
some: {
|
||||
id: userId,
|
||||
role: { in: [MembershipRole.ADMIN, MembershipRole.OWNER] },
|
||||
role: {
|
||||
in: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -931,7 +992,13 @@ export class UserRepository {
|
||||
},
|
||||
});
|
||||
}
|
||||
async isAdminOfTeamOrParentOrg({ userId, teamId }: { userId: number; teamId: number }) {
|
||||
async isAdminOfTeamOrParentOrg({
|
||||
userId,
|
||||
teamId,
|
||||
}: {
|
||||
userId: number;
|
||||
teamId: number;
|
||||
}) {
|
||||
const membershipQuery = {
|
||||
members: {
|
||||
some: {
|
||||
@@ -956,7 +1023,13 @@ export class UserRepository {
|
||||
});
|
||||
return !!teams.length;
|
||||
}
|
||||
async isAdminOrOwnerOfTeam({ userId, teamId }: { userId: number; teamId: number }) {
|
||||
async isAdminOrOwnerOfTeam({
|
||||
userId,
|
||||
teamId,
|
||||
}: {
|
||||
userId: number;
|
||||
teamId: number;
|
||||
}) {
|
||||
const isAdminOrOwnerOfTeam = await this.prismaClient.membership.findUnique({
|
||||
where: {
|
||||
userId_teamId: {
|
||||
@@ -1067,7 +1140,8 @@ export class UserRepository {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { credentials, ...userWithSelectedCalendars } = withSelectedCalendars(user);
|
||||
const { credentials, ...userWithSelectedCalendars } =
|
||||
withSelectedCalendars(user);
|
||||
return {
|
||||
...userWithSelectedCalendars,
|
||||
credentials: buildNonDelegationCredentials(credentials),
|
||||
@@ -1188,7 +1262,11 @@ export class UserRepository {
|
||||
};
|
||||
}
|
||||
|
||||
async findManyByIdsIncludeDestinationAndSelectedCalendars({ ids }: { ids: number[] }) {
|
||||
async findManyByIdsIncludeDestinationAndSelectedCalendars({
|
||||
ids,
|
||||
}: {
|
||||
ids: number[];
|
||||
}) {
|
||||
const users = await this.prismaClient.user.findMany({
|
||||
where: { id: { in: ids } },
|
||||
include: {
|
||||
@@ -1214,7 +1292,13 @@ export class UserRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async updateWhitelistWorkflows({ id, whitelistWorkflows }: { id: number; whitelistWorkflows: boolean }) {
|
||||
async updateWhitelistWorkflows({
|
||||
id,
|
||||
whitelistWorkflows,
|
||||
}: {
|
||||
id: number;
|
||||
whitelistWorkflows: boolean;
|
||||
}) {
|
||||
return this.prismaClient.user.update({
|
||||
where: { id },
|
||||
data: { whitelistWorkflows },
|
||||
@@ -1260,7 +1344,13 @@ export class UserRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async findUsersWithLastBooking({ userIds, eventTypeId }: { userIds: number[]; eventTypeId: number }) {
|
||||
async findUsersWithLastBooking({
|
||||
userIds,
|
||||
eventTypeId,
|
||||
}: {
|
||||
userIds: number[];
|
||||
eventTypeId: number;
|
||||
}) {
|
||||
return this.prismaClient.user.findMany({
|
||||
where: {
|
||||
id: {
|
||||
@@ -1342,14 +1432,20 @@ export class UserRepository {
|
||||
* @param userId - The user ID
|
||||
* @returns User with username or null
|
||||
*/
|
||||
async findByIdWithUsername(userId: number): Promise<{ username: string | null } | null> {
|
||||
async findByIdWithUsername(
|
||||
userId: number
|
||||
): Promise<{ username: string | null } | null> {
|
||||
return this.prismaClient.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { username: true },
|
||||
});
|
||||
}
|
||||
|
||||
async findManyByIdsWithCredentialsAndSelectedCalendars({ userIds }: { userIds: number[] }) {
|
||||
async findManyByIdsWithCredentialsAndSelectedCalendars({
|
||||
userIds,
|
||||
}: {
|
||||
userIds: number[];
|
||||
}) {
|
||||
const users = await this.prismaClient.user.findMany({
|
||||
where: {
|
||||
id: {
|
||||
@@ -1370,4 +1466,25 @@ export class UserRepository {
|
||||
});
|
||||
return users.map(withSelectedCalendars);
|
||||
}
|
||||
|
||||
async findByEmailAndTeamId({
|
||||
email,
|
||||
teamId,
|
||||
}: {
|
||||
email: string;
|
||||
teamId: number;
|
||||
}) {
|
||||
return this.prismaClient.user.findFirst({
|
||||
where: {
|
||||
email: email.toLowerCase(),
|
||||
teams: {
|
||||
some: {
|
||||
teamId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: userSelect,
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user