refactor: SCIM - handleGroupEvents (#20537)
* Add logging to `handleGroupEvents` * `createUsersAndConnectOrg` skipDuplicates when creating new users * `ProfileRepository.createMany` to get username from `orgAutoAcceptEmail` * Refactor `createUsersAndConnectToOrg` to use `createMany` instead of individual db calls * Add error logging to `sendSignupToOrganizationEmail` * Move `sendSignupToOrganizationEmail` to a `Promise.allSettled` * Add `createManyForExistingUsers` and `createManyPromise` * Move creating existing users profiles to `ProfileRepository.createManyForExistingUsers` * Move `sendExistingUserTeamInviteEmails` to a `Promise.allSettled` * Refactor `createUsersAndConnectToOrg` to use `ProfileRepository.createManyPromise` * Type fix * Create `generateNewChildEventTypeDataForDB` * Create `addNewMembersToEventTypes` * Type fix * Type fix * Type fix * `createMany` new workflowsOnEventTypes * Introduce `DATABASE_CHUNK_SIZE` * Batch connect children event types * Batch connect profiles to existing users
This commit is contained in:
1 parent
31ccdba203
commit
5bfb6fc148
9 files changed
+405
-107
No files matched your search
@@ -1,10 +1,10 @@
|
||||
import type { DirectorySyncEvent, Group } from "@boxyhq/saml-jackson";
|
||||
|
||||
import { createAProfileForAnExistingUser } from "@calcom/lib/createAProfileForAnExistingUser";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries";
|
||||
import { addNewMembersToEventTypes } from "@calcom/lib/server/queries";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
|
||||
import {
|
||||
@@ -15,18 +15,28 @@ import {
|
||||
|
||||
import createUsersAndConnectToOrg from "./users/createUsersAndConnectToOrg";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["dsync/handleGroupEvents"] });
|
||||
|
||||
const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: number) => {
|
||||
log.debug("called", safeStringify(event));
|
||||
const log = logger.getSubLogger({
|
||||
prefix: [`dsync/handleGroupEvents: directoryId: ${event.directory_id}`],
|
||||
});
|
||||
|
||||
log.info(
|
||||
"called",
|
||||
safeStringify({
|
||||
event: event.event,
|
||||
tenant: event.tenant,
|
||||
product: event.product,
|
||||
})
|
||||
);
|
||||
// Find the group name associated with the event
|
||||
const eventData = event.data as Group;
|
||||
|
||||
// If the group doesn't have any members assigned then return early
|
||||
if (!eventData.raw.members.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
log.info(`Event contains ${eventData.raw.members.length} members`);
|
||||
|
||||
const groupNames = await prisma.dSyncTeamGroupMapping.findMany({
|
||||
where: {
|
||||
directoryId: event.directory_id,
|
||||
@@ -67,6 +77,8 @@ const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: numb
|
||||
userEmails = eventData.raw.members.map((member: { display: string }) => member.display);
|
||||
}
|
||||
|
||||
log.info(`Event contains ${userEmails.length} emails`);
|
||||
|
||||
// Find existing users
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
@@ -97,6 +109,9 @@ const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: numb
|
||||
|
||||
const newUserEmails = userEmails.filter((email) => !users.find((user) => user.email === email));
|
||||
let newUsers;
|
||||
|
||||
log.info(`Event processing ${newUserEmails.length} new users and ${users.length} existing users`);
|
||||
|
||||
// For each team linked to the dsync group name provision members
|
||||
for (const group of groupNames) {
|
||||
if (newUserEmails.length) {
|
||||
@@ -117,7 +132,7 @@ const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: numb
|
||||
accepted: true,
|
||||
})),
|
||||
});
|
||||
await Promise.all(
|
||||
await Promise.allSettled(
|
||||
newUserEmails.map((email) => {
|
||||
return sendSignupToOrganizationEmail({
|
||||
usernameOrEmail: email,
|
||||
@@ -126,6 +141,16 @@ const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: numb
|
||||
inviterName: org.name,
|
||||
teamId: group.teamId,
|
||||
isOrg: false,
|
||||
}).catch((error) => {
|
||||
log.error(
|
||||
"Failed to send signup to organization email",
|
||||
safeStringify({
|
||||
email,
|
||||
organizationId,
|
||||
teamId: group.teamId,
|
||||
}),
|
||||
error
|
||||
);
|
||||
});
|
||||
})
|
||||
);
|
||||
@@ -161,7 +186,7 @@ const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: numb
|
||||
const newOrgMembers = users.filter(
|
||||
(user) => !user.profiles.find((profile) => profile.organizationId === organizationId)
|
||||
);
|
||||
await Promise.all([
|
||||
await Promise.allSettled([
|
||||
...newMembers.map(async (user) => {
|
||||
const translation = await getTranslation(user.locale || "en", "common");
|
||||
return sendExistingUserTeamInviteEmails({
|
||||
@@ -178,28 +203,31 @@ const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: numb
|
||||
isAutoJoin: true,
|
||||
currentUserParentTeamName: org.name,
|
||||
orgSlug: null,
|
||||
});
|
||||
}),
|
||||
...newOrgMembers.map((user) => {
|
||||
return createAProfileForAnExistingUser({
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
currentUsername: user.username,
|
||||
},
|
||||
organizationId,
|
||||
}).catch((error) => {
|
||||
log.error(
|
||||
"Failed to send team invite to existing user",
|
||||
safeStringify({
|
||||
email: user.email,
|
||||
organizationId,
|
||||
teamId: group.teamId,
|
||||
}),
|
||||
error
|
||||
);
|
||||
});
|
||||
}),
|
||||
]);
|
||||
|
||||
await ProfileRepository.createManyForExistingUsers({
|
||||
users: newOrgMembers,
|
||||
organizationId,
|
||||
orgAutoAcceptEmail: org.organizationSettings?.orgAutoAcceptEmail ?? "",
|
||||
});
|
||||
|
||||
// Add users to team event types if assignAllTeamMembers is enabled
|
||||
await Promise.all([
|
||||
...(newUsers?.map((newUser) => {
|
||||
return updateNewTeamMemberEventTypes(newUser.id, group.teamId);
|
||||
}) ?? []),
|
||||
...users.map((user) => {
|
||||
return updateNewTeamMemberEventTypes(user.id, group.teamId);
|
||||
}),
|
||||
]);
|
||||
await addNewMembersToEventTypes({
|
||||
userIds: [...(newUsers ? newUsers.map((user) => user.id) : []), ...users.map((user) => user.id)],
|
||||
teamId: group.teamId,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createOrUpdateMemberships } from "@calcom/features/auth/signup/utils/createOrUpdateMemberships";
|
||||
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { IdentityProvider } from "@calcom/prisma/enums";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
import { CreationSource, MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
import {
|
||||
deriveNameFromOrgUsername,
|
||||
@@ -48,6 +49,7 @@ export const createUsersAndConnectToOrg = async ({
|
||||
creationSource: CreationSource.WEBAPP,
|
||||
};
|
||||
}),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
@@ -58,17 +60,24 @@ export const createUsersAndConnectToOrg = async ({
|
||||
},
|
||||
select: dSyncUserSelect,
|
||||
});
|
||||
// Assign created users to organization
|
||||
for (const user of users) {
|
||||
await createOrUpdateMemberships({
|
||||
user,
|
||||
team: {
|
||||
id: org.id,
|
||||
isOrganization: true,
|
||||
parentId: null, // orgs don't have a parentId
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create profiles for new users
|
||||
await ProfileRepository.createManyPromise({
|
||||
users,
|
||||
organizationId: org.id,
|
||||
orgAutoAcceptEmail: org.organizationSettings?.orgAutoAcceptEmail ?? "",
|
||||
});
|
||||
|
||||
// Create memberships for new members
|
||||
await MembershipRepository.createMany(
|
||||
users.map((user) => ({
|
||||
userId: user.id,
|
||||
teamId: org.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
}))
|
||||
);
|
||||
|
||||
return users;
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user