diff --git a/packages/trpc/server/routers/viewer/teams/removeMember.handler.ts b/packages/trpc/server/routers/viewer/teams/removeMember.handler.ts index 4797f6561dbda5..9f9ed4bbb6b643 100644 --- a/packages/trpc/server/routers/viewer/teams/removeMember.handler.ts +++ b/packages/trpc/server/routers/viewer/teams/removeMember.handler.ts @@ -3,6 +3,7 @@ import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants"; import { isTeamAdmin, isTeamOwner } from "@calcom/lib/server/queries/teams"; import { closeComDeleteTeamMembership } from "@calcom/lib/sync/SyncServiceManager"; import type { PrismaClient } from "@calcom/prisma"; +import { teamMetadataSchema } from "@calcom/prisma/zod-utils"; import type { TrpcSessionUser } from "@calcom/trpc/server/trpc"; import { TRPCError } from "@trpc/server"; @@ -54,6 +55,47 @@ export const removeMemberHandler = async ({ ctx, input }: RemoveMemberOptions) = if (input.isOrg) { // Deleting membership from all child teams + const foundUser = await ctx.prisma.user.findUnique({ + where: { id: input.memberId }, + select: { + email: true, + password: true, + username: true, + completedOnboarding: true, + }, + }); + + const orgInfo = await ctx.prisma.team.findUnique({ + where: { id: input.teamId }, + select: { + metadata: true, + }, + }); + + if (!foundUser || !orgInfo) throw new TRPCError({ code: "NOT_FOUND" }); + + const parsedMetadata = teamMetadataSchema.parse(orgInfo.metadata); + + if ( + parsedMetadata?.isOrganization && + parsedMetadata.isOrganizationVerified && + parsedMetadata.orgAutoAcceptEmail + ) { + if (foundUser.email.endsWith(parsedMetadata.orgAutoAcceptEmail)) { + await ctx.prisma.user.delete({ + where: { id: input.memberId }, + }); + // This should cascade delete all memberships and hosts etc + return; + } + } else if ((!foundUser.username || !foundUser.password) && !foundUser.completedOnboarding) { + await ctx.prisma.user.delete({ + where: { id: input.memberId }, + }); + // This should cascade delete all memberships and hosts etc + return; + } + await ctx.prisma.membership.deleteMany({ where: { team: {