-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathbulkDeleteUsers.handler.ts
73 lines (62 loc) · 2.32 KB
/
bulkDeleteUsers.handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { updateQuantitySubscriptionFromStripe } from "@calcom/features/ee/teams/lib/payments";
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { prisma } from "@calcom/prisma";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../trpc";
import type { TBulkUsersDelete } from "./bulkDeleteUsers.schema.";
type BulkDeleteUsersHandler = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TBulkUsersDelete;
};
export async function bulkDeleteUsersHandler({ ctx, input }: BulkDeleteUsersHandler) {
const currentUser = ctx.user;
if (!currentUser.organizationId) throw new TRPCError({ code: "UNAUTHORIZED" });
// check if user is admin of organization
if (!(await isOrganisationAdmin(currentUser?.id, currentUser.organizationId)))
throw new TRPCError({ code: "UNAUTHORIZED" });
// Loop over all users in input.userIds and remove all memberships for the organization including child teams
const deleteMany = prisma.membership.deleteMany({
where: {
userId: {
in: input.userIds,
},
team: {
OR: [
{
parentId: currentUser.organizationId,
},
{ id: currentUser.organizationId },
],
},
},
});
const removeOrgrelation = prisma.user.updateMany({
where: {
id: {
in: input.userIds,
},
},
data: {
organizationId: null,
// Set username to null - to make sure there is no conflicts
username: null,
// Set completedOnboarding to false - to make sure the user has to complete onboarding again -> Setup a new username
completedOnboarding: false,
},
});
const removeProfiles = ProfileRepository.deleteMany({
userIds: input.userIds,
});
// We do this in a transaction to make sure that all memberships are removed before we remove the organization relation from the user
// We also do this to make sure that if one of the queries fail, the whole transaction fails
await prisma.$transaction([removeProfiles, deleteMany, removeOrgrelation]);
await updateQuantitySubscriptionFromStripe(currentUser.organizationId);
return {
success: true,
usersDeleted: input.userIds.length,
};
}
export default bulkDeleteUsersHandler;