diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json index 47f38c1470..99db111065 100644 --- a/apps/web/public/static/locales/en/common.json +++ b/apps/web/public/static/locales/en/common.json @@ -2468,5 +2468,8 @@ "x_unmarked_as_no_show": "{{x}} unmarked as no-show", "no_show_updated": "No-show status updated for attendees", "email_copied": "Email copied", + "USER_PENDING_MEMBER_OF_THE_ORG": "User is a pending member of the organization", + "USER_ALREADY_INVITED_OR_MEMBER": "User is already invited or a member", + "USER_MEMBER_OF_OTHER_ORGANIZATION": "User is member of an organization that this team is not a part of.", "ADD_NEW_STRINGS_ABOVE_THIS_LINE_TO_PREVENT_MERGE_CONFLICTS": "↑↑↑↑↑↑↑↑↑↑↑↑↑ Add your new strings above here ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑" } diff --git a/packages/features/ee/organizations/pages/settings/other-team-members-view.tsx b/packages/features/ee/organizations/pages/settings/other-team-members-view.tsx index d2b77da2dd..3108552b14 100644 --- a/packages/features/ee/organizations/pages/settings/other-team-members-view.tsx +++ b/packages/features/ee/organizations/pages/settings/other-team-members-view.tsx @@ -215,7 +215,7 @@ const MembersView = () => { if (Array.isArray(data.usernameOrEmail)) { showToast( t("email_invite_team_bulk", { - userCount: data.usernameOrEmail.length, + userCount: data.numUsersInvited, }), "success" ); diff --git a/packages/features/ee/teams/components/AddNewTeamMembers.tsx b/packages/features/ee/teams/components/AddNewTeamMembers.tsx index 182645e235..446e6f9cca 100644 --- a/packages/features/ee/teams/components/AddNewTeamMembers.tsx +++ b/packages/features/ee/teams/components/AddNewTeamMembers.tsx @@ -153,7 +153,7 @@ export const AddNewTeamMembersForm = ({ if (Array.isArray(data.usernameOrEmail)) { showToast( t("email_invite_team_bulk", { - userCount: data.usernameOrEmail.length, + userCount: data.numUsersInvited, }), "success" ); diff --git a/packages/features/ee/teams/components/TeamListItem.tsx b/packages/features/ee/teams/components/TeamListItem.tsx index c96830708e..42bef77cfb 100644 --- a/packages/features/ee/teams/components/TeamListItem.tsx +++ b/packages/features/ee/teams/components/TeamListItem.tsx @@ -134,7 +134,7 @@ export default function TeamListItem(props: Props) { if (Array.isArray(data.usernameOrEmail)) { showToast( t("email_invite_team_bulk", { - userCount: data.usernameOrEmail.length, + userCount: data.numUsersInvited, }), "success" ); diff --git a/packages/features/ee/teams/pages/team-members-view.tsx b/packages/features/ee/teams/pages/team-members-view.tsx index 89e3a9e55e..1ddf2f0a00 100644 --- a/packages/features/ee/teams/pages/team-members-view.tsx +++ b/packages/features/ee/teams/pages/team-members-view.tsx @@ -225,7 +225,7 @@ const MembersView = () => { if (Array.isArray(data.usernameOrEmail)) { showToast( t("email_invite_team_bulk", { - userCount: data.usernameOrEmail.length, + userCount: data.numUsersInvited, }), "success" ); diff --git a/packages/features/users/components/UserTable/InviteMemberModal.tsx b/packages/features/users/components/UserTable/InviteMemberModal.tsx index ceeb642ce7..05219fdff1 100644 --- a/packages/features/users/components/UserTable/InviteMemberModal.tsx +++ b/packages/features/users/components/UserTable/InviteMemberModal.tsx @@ -27,7 +27,7 @@ export function InviteMemberModal(props: Props) { if (Array.isArray(data.usernameOrEmail)) { showToast( t("email_invite_team_bulk", { - userCount: data.usernameOrEmail.length, + userCount: data.numUsersInvited, }), "success" ); diff --git a/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler.ts b/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler.ts index 1b8abe0c6d..b4d5fae6f2 100644 --- a/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler.ts +++ b/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler.ts @@ -19,9 +19,9 @@ import type { TeamWithParent } from "./types"; import { checkPermissions, getTeamOrThrow, - getUsernameOrEmailsToInvite, + getUniqueUsernameOrEmailsOrThrow, getOrgConnectionInfo, - getIsOrgVerified, + getOrgState, sendSignupToOrganizationEmail, getExistingUsersToInvite, createNewUsersConnectToOrgIfExists, @@ -29,6 +29,7 @@ import { groupUsersByJoinability, sendExistingUserTeamInviteEmails, sendEmails, + INVITE_STATUS, } from "./utils"; const log = logger.getSubLogger({ prefix: ["inviteMember.handler"] }); @@ -61,9 +62,9 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) = isOrg, }); - const { autoAcceptEmailDomain, orgVerified } = getIsOrgVerified(isOrg, team); + const { autoAcceptEmailDomain, orgVerified } = getOrgState(isOrg, team); - const usernameOrEmailsToInvite = await getUsernameOrEmailsToInvite(input.usernameOrEmail); + const usernameOrEmailsToInvite = await getUniqueUsernameOrEmailsOrThrow(input.usernameOrEmail); const isBulkInvite = usernameOrEmailsToInvite.length > 1; const beSilentAboutErrors = isBulkInvite; @@ -87,9 +88,23 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) = // Existing users have a criteria to be invited const existingUsersWithMembershipsThatNeedToBeInvited = existingUsersWithMemberships.filter( - (invitee) => invitee.canBeInvited + (invitee) => invitee.canBeInvited === INVITE_STATUS.CAN_BE_INVITED ); + // beSilentAboutErrors is false only when there is a single user being invited, so we just check the first item status here + // Bulk invites error are silently ignored and they should be logged differently when needed + const firstExistingUser = existingUsersWithMemberships[0]; + if ( + !beSilentAboutErrors && + firstExistingUser && + firstExistingUser.canBeInvited !== INVITE_STATUS.CAN_BE_INVITED + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: translation(existingUsersWithMemberships[0].canBeInvited), + }); + } + const existingUsersEmailsAndUsernames = existingUsersWithMemberships.reduce( (acc, user) => ({ emails: user.email ? [...acc.emails, user.email] : acc.emails, @@ -105,17 +120,6 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) = !existingUsersEmailsAndUsernames.usernames.includes(usernameOrEmail) ); - if ( - !beSilentAboutErrors && - existingUsersWithMemberships.length && - !existingUsersWithMembershipsThatNeedToBeInvited.length - ) { - throw new TRPCError({ - code: "BAD_REQUEST", - message: "Could not invite the user as he might be part of another organization", - }); - } - myLog.debug( "Notable variables:", safeStringify({ @@ -169,7 +173,11 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) = await updateQuantitySubscriptionFromStripe(input.teamId); } } - return input; + return { + ...input, + numUsersInvited: + existingUsersWithMembershipsThatNeedToBeInvited.length + newUsersEmailsOrUsernames.length, + }; }; export default inviteMemberHandler; diff --git a/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMemberUtils.test.ts b/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMemberUtils.test.ts index c76814ed9f..6ffacc1667 100644 --- a/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMemberUtils.test.ts +++ b/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMemberUtils.test.ts @@ -8,10 +8,11 @@ import { TRPCError } from "@trpc/server"; import type { TeamWithParent } from "./types"; import type { UserWithMembership } from "./utils"; +import { INVITE_STATUS } from "./utils"; import { checkPermissions, - getUsernameOrEmailsToInvite, - getIsOrgVerified, + getUniqueUsernameOrEmailsOrThrow, + getOrgState, getOrgConnectionInfo, canBeInvited, getAutoJoinStatus, @@ -89,6 +90,8 @@ const mockedRegularTeam: TeamWithParent = { isOrganization: false, calVideoLogo: "", bannerUrl: "", + isPlatform: false, + smsLockState: "LOCKED", }; const mockedSubTeam = { @@ -138,18 +141,18 @@ describe("Invite Member Utils", () => { await expect(checkPermissions({ userId: 1, teamId: 1 })).resolves.not.toThrow(); }); }); - describe("getUsernameOrEmailsToInvite", () => { + describe("getUniqueUsernameOrEmailsOrThrow", () => { it("should throw a TRPCError with code BAD_REQUEST if no emails are provided", async () => { - await expect(getUsernameOrEmailsToInvite([])).rejects.toThrow(TRPCError); + await expect(getUniqueUsernameOrEmailsOrThrow([])).rejects.toThrow(TRPCError); }); it("should return an array with one email if a string is provided", async () => { - const result = await getUsernameOrEmailsToInvite("test@example.com"); + const result = await getUniqueUsernameOrEmailsOrThrow("test@example.com"); expect(result).toEqual(["test@example.com"]); }); it("should return an array with multiple emails if an array is provided", async () => { - const result = await getUsernameOrEmailsToInvite(["test1@example.com", "test2@example.com"]); + const result = await getUniqueUsernameOrEmailsOrThrow(["test1@example.com", "test2@example.com"]); expect(result).toEqual(["test1@example.com", "test2@example.com"]); }); }); @@ -232,7 +235,7 @@ describe("Invite Member Utils", () => { expect(result).toEqual({ orgId: mockedRegularTeam.id, autoAccept: false }); }); }); - describe("getIsOrgVerified", () => { + describe("getOrgState", () => { it("should return the correct values when isOrg is true and teamMetadata.orgAutoAcceptEmail is true", () => { const team = { organizationSettings: { @@ -245,7 +248,7 @@ describe("Invite Member Utils", () => { slug: "abc", parent: null, }; - const result = getIsOrgVerified(true, { ...mockedRegularTeam, ...team }); + const result = getOrgState(true, { ...mockedRegularTeam, ...team }); expect(result).toEqual({ isInOrgScope: true, orgVerified: true, @@ -269,7 +272,7 @@ describe("Invite Member Utils", () => { }, }, }; - const result = getIsOrgVerified(false, { ...mockedRegularTeam, ...team }); + const result = getOrgState(false, { ...mockedRegularTeam, ...team }); expect(result).toEqual({ isInOrgScope: true, orgVerified: false, @@ -284,7 +287,7 @@ describe("Invite Member Utils", () => { metadata: {}, parent: null, }; - const result = getIsOrgVerified(false, { ...mockedRegularTeam, ...team }); + const result = getOrgState(false, { ...mockedRegularTeam, ...team }); expect(result).toEqual({ isInOrgScope: false, }); @@ -300,39 +303,161 @@ describe("Invite Member Utils", () => { profiles: [], }; - it("should return true when inviting to an organization's team an existing org user", () => { + it("should return CAN_BE_INVITED when inviting to an sub-team if the invitee is a member of the organization", () => { + const inviteeOrganizationId = 2; + const inviteeWithOrg: UserWithMembership = { + ...invitee, + profiles: [getSampleProfile({ organizationId: inviteeOrganizationId })], + }; + + const subTeam = { + ...mockedRegularTeam, + parentId: inviteeOrganizationId, + }; + + expect(canBeInvited(inviteeWithOrg, subTeam)).toBe(INVITE_STATUS.CAN_BE_INVITED); + }); + + it("should return CAN_BE_INVITED if the user is invited to a sub-team of the organization the user belongs to", () => { + const inviteeOrgId = 2; + const subTeamOrgId = inviteeOrgId; const inviteeWithOrg: UserWithMembership = { ...invitee, profiles: [getSampleProfile({ organizationId: 2 })], + teams: [{ teamId: 2, accepted: true, userId: invitee.id, role: "ADMIN" }], }; - const teamWithOrg = { - ...mockedRegularTeam, - parentId: 2, - }; - expect(canBeInvited(inviteeWithOrg, teamWithOrg)).toBe(true); - }); - it("should return false when inviting a user who is already a member of the team", () => { - const inviteeWithOrg: UserWithMembership = { - ...invitee, - profiles: [getSampleProfile()], - teams: [{ teamId: 1, accepted: true, userId: invitee.id, role: "ADMIN" }], - }; - const teamWithOrg = { + const subTeam = { ...mockedRegularTeam, + parentId: subTeamOrgId, id: 1, }; - expect(canBeInvited(inviteeWithOrg, teamWithOrg)).toBe(false); + expect(canBeInvited(inviteeWithOrg, subTeam)).toBe(INVITE_STATUS.CAN_BE_INVITED); }); - it("should return true if the invitee already exists in Cal.com and is being invited to an organization", () => { - expect(canBeInvited(invitee, mockedRegularTeam)).toBe(true); + it("should return CAN_BE_INVITED if the invitee does not already belong to another organization and is being invited to a regular team", () => { + expect(canBeInvited(invitee, mockedRegularTeam)).toBe(INVITE_STATUS.CAN_BE_INVITED); }); - it("should return true if the invitee does not already belong to another organization and is not being invited to an organization", () => { - expect(canBeInvited(invitee, mockedRegularTeam)).toBe(true); + it("should return USER_ALREADY_INVITED_OR_MEMBER when inviting a user who is already a member of the team", () => { + const teamId = 1; + const inviteeWithOrg: UserWithMembership = { + ...invitee, + teams: [{ teamId: teamId, accepted: true, userId: invitee.id, role: "ADMIN" }], + }; + const regularTeam = { + ...mockedRegularTeam, + id: teamId, + }; + expect(canBeInvited(inviteeWithOrg, regularTeam)).toBe(INVITE_STATUS.USER_ALREADY_INVITED_OR_MEMBER); + }); + + it("should return USER_ALREADY_INVITED_OR_MEMBER when inviting a user to sub-team who is already a member of the sub-team", () => { + const teamId = 1; + const inviteeOrgId = 2; + const inviteeWithOrg: UserWithMembership = { + ...invitee, + profiles: [getSampleProfile({ organizationId: inviteeOrgId })], + teams: [ + { teamId: teamId, accepted: true, userId: invitee.id, role: "ADMIN" }, + { teamId: inviteeOrgId, accepted: true, userId: invitee.id, role: "ADMIN" }, + ], + }; + const subTeam = { + ...mockedRegularTeam, + parentId: inviteeOrgId, + id: teamId, + }; + expect(canBeInvited(inviteeWithOrg, subTeam)).toBe(INVITE_STATUS.USER_ALREADY_INVITED_OR_MEMBER); + }); + + it("should return USER_ALREADY_INVITED_OR_MEMBER when inviting a user to an organization who is already a member of the organization", () => { + const inviteeOrgId = 2; + const inviteeWithOrg: UserWithMembership = { + ...invitee, + profiles: [getSampleProfile({ organizationId: inviteeOrgId })], + teams: [{ teamId: inviteeOrgId, accepted: true, userId: invitee.id, role: "ADMIN" }], + }; + const organization = { + ...mockedRegularTeam, + parentId: null, + id: inviteeOrgId, + }; + expect(canBeInvited(inviteeWithOrg, organization)).toBe(INVITE_STATUS.USER_ALREADY_INVITED_OR_MEMBER); + }); + + it("should return USER_PENDING_MEMBER_OF_THE_ORG if the invitee is being invited to a team in an organization but he has not accepted the organization membership", () => { + const inviteeOrganizationId = 2; + const inviteeWithOrg: UserWithMembership = { + ...invitee, + teams: [{ teamId: inviteeOrganizationId, accepted: false, userId: invitee.id, role: "ADMIN" }], + }; + + const subTeam = { + ...mockedRegularTeam, + parentId: inviteeOrganizationId, + id: 1, + }; + expect(canBeInvited(inviteeWithOrg, subTeam)).toBe(INVITE_STATUS.USER_PENDING_MEMBER_OF_THE_ORG); + }); + + it("should return USER_MEMBER_OF_OTHER_ORGANIZATION if the invitee is being invited to an organization but he belongs to another organization", () => { + const inviteeOrganizationId = 2; + const organizationIdBeingInvitedTo = 3; + const inviteeWithOrg: UserWithMembership = { + ...invitee, + profiles: [ + getSampleProfile({ + organizationId: inviteeOrganizationId, + }), + ], + teams: [{ teamId: inviteeOrganizationId, accepted: true, userId: invitee.id, role: "ADMIN" }], + }; + + const organization = { + ...mockedRegularTeam, + id: organizationIdBeingInvitedTo, + }; + expect(canBeInvited(inviteeWithOrg, organization)).toBe( + INVITE_STATUS.USER_MEMBER_OF_OTHER_ORGANIZATION + ); + }); + + it("should return USER_MEMBER_OF_OTHER_ORGANIZATION if the invitee is being invited to a sub-team in an organization but he belongs to another organization", () => { + const inviteeOrganizationId = 2; + const subTeamOrganizationId = 3; + const inviteeWithOrg: UserWithMembership = { + ...invitee, + profiles: [ + getSampleProfile({ + organizationId: inviteeOrganizationId, + }), + ], + teams: [{ teamId: inviteeOrganizationId, accepted: true, userId: invitee.id, role: "ADMIN" }], + }; + + const teamWithOrg = { + ...mockedRegularTeam, + parentId: subTeamOrganizationId, + id: 1, + }; + expect(canBeInvited(inviteeWithOrg, teamWithOrg)).toBe(INVITE_STATUS.USER_MEMBER_OF_OTHER_ORGANIZATION); + }); + + it("should return 'USER_MEMBER_OF_OTHER_ORGANIZATION' when the invitee is invited to a regular team but the he is a part of an organization", () => { + const inviteeOrganizationId = 2; + const inviteeWithOrg: UserWithMembership = { + ...invitee, + profiles: [getSampleProfile({ organizationId: inviteeOrganizationId })], + teams: [{ teamId: inviteeOrganizationId, accepted: true, userId: invitee.id, role: "ADMIN" }], + }; + + const regularTeam = { ...mockedRegularTeam }; + + expect(canBeInvited(inviteeWithOrg, regularTeam)).toBe(INVITE_STATUS.USER_MEMBER_OF_OTHER_ORGANIZATION); }); }); + describe("shouldAutoJoinIfInOrg", () => { it("should return autoAccept: false if the team is a sub-team but not in the user's organization", async () => { const result = getAutoJoinStatus({ diff --git a/packages/trpc/server/routers/viewer/teams/inviteMember/utils.ts b/packages/trpc/server/routers/viewer/teams/inviteMember/utils.ts index 2ca4f84a62..32a9d7608f 100644 --- a/packages/trpc/server/routers/viewer/teams/inviteMember/utils.ts +++ b/packages/trpc/server/routers/viewer/teams/inviteMember/utils.ts @@ -44,7 +44,7 @@ export async function checkPermissions({ teamId: number; isOrg?: boolean; }) { - // Checks if the team they are inviteing to IS the org. Not a child team + // Checks if the team they are inviting to IS the org. Not a child team if (isOrg) { if (!(await isOrganisationAdmin(userId, teamId))) throw new TRPCError({ code: "UNAUTHORIZED" }); } else { @@ -85,7 +85,7 @@ export async function getTeamOrThrow(teamId: number) { return { ...team, metadata: teamMetadataSchema.parse(team.metadata) }; } -export async function getUsernameOrEmailsToInvite(usernameOrEmail: string | string[]) { +export async function getUniqueUsernameOrEmailsOrThrow(usernameOrEmail: string | string[]) { const emailsToInvite = Array.isArray(usernameOrEmail) ? Array.from(new Set(usernameOrEmail)) : [usernameOrEmail]; @@ -100,26 +100,35 @@ export async function getUsernameOrEmailsToInvite(usernameOrEmail: string | stri return emailsToInvite; } +export const enum INVITE_STATUS { + USER_PENDING_MEMBER_OF_THE_ORG = "USER_PENDING_MEMBER_OF_THE_ORG", + USER_ALREADY_INVITED_OR_MEMBER = "USER_ALREADY_INVITED_OR_MEMBER", + USER_MEMBER_OF_OTHER_ORGANIZATION = "USER_MEMBER_OF_OTHER_ORGANIZATION", + CAN_BE_INVITED = "CAN_BE_INVITED", +} + export function canBeInvited(invitee: UserWithMembership, team: TeamWithParent) { const myLog = log.getSubLogger({ prefix: ["canBeInvited"] }); myLog.debug("Checking if user can be invited", safeStringify({ invitee, team })); const alreadyInvited = invitee.teams?.find(({ teamId: membershipTeamId }) => team.id === membershipTeamId); if (alreadyInvited) { - return false; + return INVITE_STATUS.USER_ALREADY_INVITED_OR_MEMBER; } - const orgMembership = invitee.teams?.find((membersip) => membersip.teamId === team.parentId); - // invitee is invited to the org's team and is already part of the organization + const orgMembership = invitee.teams?.find((membership) => membership.teamId === team.parentId); + + // An invitee here won't be a member of the team + // If he is invited to a sub-team and is already part of the organization. if ( team.parentId && UserRepository.isAMemberOfOrganization({ user: invitee, organizationId: team.parentId }) ) { - return true; + return INVITE_STATUS.CAN_BE_INVITED; } // user invited to join a team inside an org, but has not accepted invite to org yet if (team.parentId && orgMembership && !orgMembership.accepted) { - return false; + return INVITE_STATUS.USER_PENDING_MEMBER_OF_THE_ORG; } if ( @@ -127,9 +136,9 @@ export function canBeInvited(invitee: UserWithMembership, team: TeamWithParent) // Member of an organization is invited to join a team that is not a subteam of the organization invitee.profiles.find((profile) => profile.organizationId != team.parentId) ) { - return false; + return INVITE_STATUS.USER_MEMBER_OF_OTHER_ORGANIZATION; } - return true; + return INVITE_STATUS.CAN_BE_INVITED; } export async function getExistingUsersToInvite({ @@ -420,7 +429,7 @@ type TeamAndOrganizationSettings = Team & { organizationSettings?: OrganizationSettings | null; }; -export function getIsOrgVerified( +export function getOrgState( isOrg: boolean, team: TeamAndOrganizationSettings & { parent: TeamAndOrganizationSettings | null;