feat: Fix invite bug - added tests (#9945)

Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
sean-brydonandHariom Balhara authored and GitHub committed 2023-07-06 15:03:31 +05:30
1 parent b5f0f0c0de
commit c8f7b36307
11 files changed
+497 -165

No files matched your search

@@ -153,6 +153,7 @@ const MembersView = () => {
isOpen={showMemberInvitationModal}
members={team.members}
onExit={() => setShowMemberInvitationModal(false)}
isLoading={inviteMemberMutation.isLoading}
onSubmit={(values) => {
inviteMemberMutation.mutate({
teamId: team.id,
@@ -92,6 +92,7 @@ export const AddNewTeamMembersForm = ({
) : (
<>
<MemberInvitationModal
isLoading={inviteMemberMutation.isLoading}
isOpen={memberInviteModal}
teamId={teamId}
token={team?.inviteToken?.token}
@@ -38,6 +38,7 @@ type MemberInvitationModalProps = {
teamId: number;
members: PendingMember[];
token?: string;
isLoading?: boolean;
};
type MembershipRoleOption = {
@@ -336,6 +337,7 @@ export default function MemberInvitationModal(props: MemberInvitationModalProps)
{t("cancel")}
</Button>
<Button
loading={props.isLoading || createInviteMutation.isLoading}
type="submit"
color="primary"
className="me-2 ms-2"
@@ -120,6 +120,7 @@ export default function TeamListItem(props: Props) {
onExit={() => {
setOpenMemberInvitationModal(false);
}}
isLoading={inviteMemberMutation.isLoading}
onSubmit={(values, resetFields) => {
inviteMemberMutation.mutate(
{
@@ -146,6 +146,7 @@ const MembersView = () => {
</div>
{showMemberInvitationModal && team && (
<MemberInvitationModal
isLoading={inviteMemberMutation.isLoading}
isOpen={showMemberInvitationModal}
members={team.members}
teamId={team.id}
@@ -9,7 +9,7 @@ import { ZDeleteInviteInputSchema } from "./deleteInvite.schema";
import { ZGetInputSchema } from "./get.schema";
import { ZGetMemberAvailabilityInputSchema } from "./getMemberAvailability.schema";
import { ZGetMembershipbyUserInputSchema } from "./getMembershipbyUser.schema";
import { ZInviteMemberInputSchema } from "./inviteMember.schema";
import { ZInviteMemberInputSchema } from "./inviteMember/inviteMember.schema";
import { ZInviteMemberByTokenSchemaInputSchema } from "./inviteMemberByToken.schema";
import { ZListMembersInputSchema } from "./listMembers.schema";
import { ZPublishInputSchema } from "./publish.schema";
@@ -25,7 +25,7 @@ type TeamsRouterHandlerCache = {
update?: typeof import("./update.handler").updateHandler;
delete?: typeof import("./delete.handler").deleteHandler;
removeMember?: typeof import("./removeMember.handler").removeMemberHandler;
inviteMember?: typeof import("./inviteMember.handler").inviteMemberHandler;
inviteMember?: typeof import("./inviteMember/inviteMember.handler").inviteMemberHandler;
acceptOrLeave?: typeof import("./acceptOrLeave.handler").acceptOrLeaveHandler;
changeMemberRole?: typeof import("./changeMemberRole.handler").changeMemberRoleHandler;
getMemberAvailability?: typeof import("./getMemberAvailability.handler").getMemberAvailabilityHandler;
@@ -147,7 +147,7 @@ export const viewerTeamsRouter = router({
inviteMember: authedProcedure.input(ZInviteMemberInputSchema).mutation(async ({ ctx, input }) => {
if (!UNSTABLE_HANDLER_CACHE.inviteMember) {
UNSTABLE_HANDLER_CACHE.inviteMember = await import("./inviteMember.handler").then(
UNSTABLE_HANDLER_CACHE.inviteMember = await import("./inviteMember/inviteMember.handler").then(
(mod) => mod.inviteMemberHandler
);
}
@@ -0,0 +1,126 @@
import { randomBytes } from "crypto";
import { sendTeamInviteEmail } from "@calcom/emails";
import { updateQuantitySubscriptionFromStripe } from "@calcom/features/ee/teams/lib/payments";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { getTranslation } from "@calcom/lib/server/i18n";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import { isEmail } from "../util";
import type { TInviteMemberInputSchema } from "./inviteMember.schema";
import {
checkPermissions,
getTeamOrThrow,
getEmailsToInvite,
getUserToInviteOrThrowIfExists,
checkInputEmailIsValid,
getOrgConnectionInfo,
createNewUserConnectToOrgIfExists,
throwIfInviteIsToOrgAndUserExists,
createProvisionalMembership,
getIsOrgVerified,
sendVerificationEmail,
} from "./utils";
type InviteMemberOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TInviteMemberInputSchema;
};
export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) => {
const team = await getTeamOrThrow(input.teamId, input.isOrg);
const { autoAcceptEmailDomain, orgVerified } = getIsOrgVerified(input.isOrg, team);
await checkPermissions({ userId: ctx.user.id, teamId: input.teamId, isOrg: input.isOrg });
const translation = await getTranslation(input.language ?? "en", "common");
const emailsToInvite = await getEmailsToInvite(input.usernameOrEmail);
for (const usernameOrEmail of emailsToInvite) {
const connectionInfo = getOrgConnectionInfo({
orgVerified,
orgAutoAcceptDomain: autoAcceptEmailDomain,
usersEmail: usernameOrEmail,
team,
isOrg: input.isOrg,
});
const invitee = await getUserToInviteOrThrowIfExists({
usernameOrEmail,
orgId: input.teamId,
isOrg: input.isOrg,
});
if (!invitee) {
checkInputEmailIsValid(usernameOrEmail);
// valid email given, create User and add to team
await createNewUserConnectToOrgIfExists({
usernameOrEmail,
input,
connectionInfo,
parentId: team.parentId,
});
await sendVerificationEmail({ usernameOrEmail, team, translation, ctx, input, connectionInfo });
} else {
throwIfInviteIsToOrgAndUserExists(invitee, team, input.isOrg);
// create provisional membership
await createProvisionalMembership({
input,
invitee,
});
let sendTo = usernameOrEmail;
if (!isEmail(usernameOrEmail)) {
sendTo = invitee.email;
}
// inform user of membership by email
if (input.sendEmailInvitation && ctx?.user?.name && team?.name) {
const inviteTeamOptions = {
joinLink: `${WEBAPP_URL}/auth/login?callbackUrl=/settings/teams`,
isCalcomMember: true,
};
/**
* Here we want to redirect to a differnt place if onboarding has been completed or not. This prevents the flash of going to teams -> Then to onboarding - also show a differnt email template.
* This only changes if the user is a CAL user and has not completed onboarding and has no password
*/
if (!invitee.completedOnboarding && !invitee.password && invitee.identityProvider === "CAL") {
const token = randomBytes(32).toString("hex");
await prisma.verificationToken.create({
data: {
identifier: usernameOrEmail,
token,
expires: new Date(new Date().setHours(168)), // +1 week
},
});
inviteTeamOptions.joinLink = `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`;
inviteTeamOptions.isCalcomMember = false;
}
await sendTeamInviteEmail({
language: translation,
from: ctx.user.name,
to: sendTo,
teamName: team.name,
...inviteTeamOptions,
isOrg: input.isOrg,
});
}
}
}
if (IS_TEAM_BILLING_ENABLED) {
if (team.parentId) {
await updateQuantitySubscriptionFromStripe(team.parentId);
} else {
await updateQuantitySubscriptionFromStripe(input.teamId);
}
}
return input;
};
@@ -0,0 +1,293 @@
import { describe, it, vi, expect } from "vitest";
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import { checkInputEmailIsValid, checkPermissions, getEmailsToInvite, getIsOrgVerified, getOrgConnectionInfo, throwIfInviteIsToOrgAndUserExists } from "./utils";
import { MembershipRole } from "@calcom/prisma/enums";
import { isTeamAdmin } from "@calcom/lib/server/queries";
import { TRPCError } from "@trpc/server";
import type { TeamWithParent } from "./types";
import type { User } from "@calcom/prisma/client";
vi.mock("@calcom/lib/server/queries", () => {
return {
isTeamAdmin: vi.fn(),
};
});
vi.mock("@calcom/lib/server/queries/organisations", () => {
return {
isOrganisationAdmin: vi.fn(),
};
});
const mockedReturnSuccessCheckPerms = { accepted: true, disableImpersonation: false, id: 1, role: MembershipRole.ADMIN, userId: 1, teamId: 1 }
const mockedTeam: TeamWithParent = {
id: 1,
name: "Team A",
slug: null,
logo: null,
appLogo: null,
appIconLogo: null,
bio: null,
hideBranding: false,
hideBookATeamMember: false,
createdAt: new Date(),
brandColor: "#292929",
darkBrandColor: "#fafafa",
timeZone: "Europe/London",
weekStart: "Sunday",
theme: null,
timeFormat: null,
metadata: null,
parentId: null,
parent: null
};
const mockUser: User = {
id: 4,
username: 'pro',
name: 'Pro Example',
email: '[email protected]',
emailVerified: new Date(),
password: '',
bio: null,
avatar: null,
timeZone: 'Europe/London',
weekStart: 'Sunday',
startTime: 0,
endTime: 1440,
bufferTime: 0,
hideBranding: false,
theme: null,
createdDate: new Date(),
trialEndsAt: null,
defaultScheduleId: null,
completedOnboarding: true,
locale: 'en',
timeFormat: 12,
twoFactorSecret: null,
twoFactorEnabled: false,
identityProvider: 'CAL',
identityProviderId: null,
invitedTo: null,
brandColor: '#292929',
darkBrandColor: '#fafafa',
away: false,
allowDynamicBooking: true,
metadata: null,
verified: false,
role: 'USER',
disableImpersonation: false,
organizationId: null
}
describe("Invite Member Utils", () => {
describe("checkPermissions", () => {
it("It should throw an error if the user is not an admin of the ORG", async () => {
vi.mocked(isOrganisationAdmin).mockResolvedValue(false);
await expect(checkPermissions({ userId: 1, teamId: 1, isOrg: true })).rejects.toThrow();
})
it("It should NOT throw an error if the user is an admin of the ORG", async () => {
vi.mocked(isOrganisationAdmin).mockResolvedValue(mockedReturnSuccessCheckPerms);
await expect(checkPermissions({ userId: 1, teamId: 1, isOrg: true })).resolves.not.toThrow();
})
it("It should throw an error if the user is not an admin of the team", async () => {
vi.mocked(isTeamAdmin).mockResolvedValue(false);
await expect(checkPermissions({ userId: 1, teamId: 1 })).rejects.toThrow();
})
it("It should NOT throw an error if the user is an admin of a team", async () => {
vi.mocked(isTeamAdmin).mockResolvedValue(mockedReturnSuccessCheckPerms);
await expect(checkPermissions({ userId: 1, teamId: 1 })).resolves.not.toThrow();
})
})
describe('getEmailsToInvite', () => {
it('should throw a TRPCError with code BAD_REQUEST if no emails are provided', async () => {
await expect(getEmailsToInvite([])).rejects.toThrow(TRPCError);
});
it('should return an array with one email if a string is provided', async () => {
const result = await getEmailsToInvite('[email protected]');
expect(result).toEqual(['[email protected]']);
});
it('should return an array with multiple emails if an array is provided', async () => {
const result = await getEmailsToInvite(['[email protected]', '[email protected]']);
expect(result).toEqual(['[email protected]', '[email protected]']);
});
});
describe('checkInputEmailIsValid', () => {
it('should throw a TRPCError with code BAD_REQUEST if the email is invalid', () => {
const invalidEmail = 'invalid-email';
expect(() => checkInputEmailIsValid(invalidEmail)).toThrow(TRPCError);
expect(() => checkInputEmailIsValid(invalidEmail)).toThrowError(
'Invite failed because invalid-email is not a valid email address'
);
});
it('should not throw an error if the email is valid', () => {
const validEmail = '[email protected]';
expect(() => checkInputEmailIsValid(validEmail)).not.toThrow();
});
});
describe("getOrgConnectionInfo", () => {
const orgAutoAcceptDomain = "example.com";
const usersEmail = "[email protected]";
it("should return orgId and autoAccept as true if team has parent and usersEmail domain matches orgAutoAcceptDomain and orgVerified is true", () => {
const result = getOrgConnectionInfo({
orgAutoAcceptDomain,
orgVerified: true,
usersEmail,
team: {
...mockedTeam,
parentId: 2,
},
isOrg: false,
});
expect(result).toEqual({ orgId: 2, autoAccept: true });
});
it("should return orgId and autoAccept as false if team has parent and usersEmail domain does not match orgAutoAcceptDomain", () => {
const result = getOrgConnectionInfo({
orgAutoAcceptDomain,
usersEmail: "[email protected]",
team: {
...mockedTeam,
parentId: 2,
},
isOrg: false,
});
expect(result).toEqual({ orgId: undefined, autoAccept: false });
});
it("should return orgId and autoAccept as false if team has parent and usersEmail domain matches orgAutoAcceptDomain but orgVerified is false", () => {
const result = getOrgConnectionInfo({
orgAutoAcceptDomain,
orgVerified: false,
usersEmail,
team: { ...mockedTeam },
isOrg: false,
});
expect(result).toEqual({ orgId: undefined, autoAccept: false });
});
it("should return orgId and autoAccept as true if team has no parent and isOrg is true and usersEmail domain matches orgAutoAcceptDomain and orgVerified is true", () => {
const result = getOrgConnectionInfo({
orgAutoAcceptDomain,
orgVerified: true,
usersEmail,
team: { ...mockedTeam, parentId: null },
isOrg: true,
});
expect(result).toEqual({ orgId: 1, autoAccept: true });
});
it("should return orgId and autoAccept as false if team has no parent and isOrg is true and usersEmail domain does not match orgAutoAcceptDomain", () => {
const result = getOrgConnectionInfo({
orgAutoAcceptDomain,
usersEmail: "[email protected]",
team: { ...mockedTeam, parentId: null },
isOrg: true,
});
expect(result).toEqual({ orgId: undefined, autoAccept: false });
});
it("should return orgId and autoAccept as false if team has no parent and isOrg is true and usersEmail domain matches orgAutoAcceptDomain but orgVerified is false", () => {
const result = getOrgConnectionInfo({
orgAutoAcceptDomain,
orgVerified: false,
usersEmail,
team: { ...mockedTeam, parentId: null },
isOrg: true,
});
expect(result).toEqual({ orgId: mockedTeam.id, autoAccept: false });
});
});
describe("getIsOrgVerified", () => {
it("should return the correct values when isOrg is true and teamMetadata.orgAutoAcceptEmail is true", () => {
const team = {
metadata: {
isOrganizationVerified: true,
orgAutoAcceptEmail: "example.com",
},
parent: null,
};
const result = getIsOrgVerified(true, { ...mockedTeam, ...team });
expect(result).toEqual({
isInOrgScope: true,
orgVerified: true,
autoAcceptEmailDomain: "example.com",
});
});
it("should return the correct values when orgMetadataIfExists.orgAutoAcceptEmail is true", () => {
const team = {
metadata: {},
parent: {
...mockedTeam,
metadata: {
isOrganizationVerified: false,
orgAutoAcceptEmail: "example.com",
},
},
};
const result = getIsOrgVerified(false, { ...mockedTeam, ...team });
expect(result).toEqual({
isInOrgScope: true,
orgVerified: false,
autoAcceptEmailDomain: "example.com",
});
});
it("should return the correct values when neither isOrg nor orgMetadataIfExists.orgAutoAcceptEmail is true", () => {
const team = {
metadata: {},
parent: null,
};
const result = getIsOrgVerified(false, { ...mockedTeam, ...team });
expect(result).toEqual({
isInOrgScope: false,
});
});
});
describe("throwIfInviteIsToOrgAndUserExists", () => {
const invitee: User = {
...mockUser,
id: 1,
username: "testuser",
email: "[email protected]",
organizationId: null,
};
const isOrg = false;
it("should throw a TRPCError with code FORBIDDEN if the invitee is already a member of another organization", () => {
const inviteeWithOrg: User = {
...invitee,
organizationId: 2,
};
const teamWithOrg = {
...mockedTeam,
parentId: 2,
}
expect(() =>
throwIfInviteIsToOrgAndUserExists(inviteeWithOrg, teamWithOrg, isOrg)
).toThrow(TRPCError);
});
it("should throw a TRPCError with code FORBIDDEN if the invitee already exists in Cal.com and is being invited to an organization", () => {
const isOrg = true;
expect(() =>
throwIfInviteIsToOrgAndUserExists(invitee, mockedTeam, isOrg)
).toThrow(TRPCError);
});
it("should not throw an error if the invitee does not already belong to another organization and is not being invited to an organization", () => {
expect(() =>
throwIfInviteIsToOrgAndUserExists(invitee, mockedTeam, isOrg)
).not.toThrow();
});
});
})
@@ -0,0 +1,15 @@
import type { Team } from "@calcom/prisma/client";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import type { TInviteMemberInputSchema } from "./inviteMember.schema";
export type InviteMemberOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TInviteMemberInputSchema;
};
export type TeamWithParent = Team & {
parent: Team | null;
};
@@ -1,36 +1,23 @@
import { Prisma } from "@prisma/client";
import { randomBytes } from "crypto";
import type { TFunction } from "next-i18next";
import { sendOrganizationAutoJoinEmail, sendTeamInviteEmail } from "@calcom/emails";
import { updateQuantitySubscriptionFromStripe } from "@calcom/features/ee/teams/lib/payments";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { getTranslation } from "@calcom/lib/server/i18n";
import { sendTeamInviteEmail, sendOrganizationAutoJoinEmail } from "@calcom/emails";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { isTeamAdmin } from "@calcom/lib/server/queries";
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
import { prisma } from "@calcom/prisma";
import type { Team, User } from "@calcom/prisma/client";
import type { Team } from "@calcom/prisma/client";
import { Prisma, type User } from "@calcom/prisma/client";
import type { MembershipRole } from "@calcom/prisma/enums";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import { TRPCError } from "@trpc/server";
import type { TInviteMemberInputSchema } from "./inviteMember.schema";
import { isEmail } from "./util";
import type { TrpcSessionUser } from "../../../../trpc";
import { isEmail } from "../util";
import type { InviteMemberOptions, TeamWithParent } from "./types";
type InviteMemberOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TInviteMemberInputSchema;
};
type TeamWithParent = Team & {
parent: Team | null;
};
async function checkPermissions({
export async function checkPermissions({
userId,
teamId,
isOrg,
@@ -48,7 +35,7 @@ async function checkPermissions({
}
}
async function getTeamOrThrow(teamId: number, isOrg?: boolean) {
export async function getTeamOrThrow(teamId: number, isOrg?: boolean) {
const team = await prisma.team.findFirst({
where: {
id: teamId,
@@ -64,7 +51,7 @@ async function getTeamOrThrow(teamId: number, isOrg?: boolean) {
return team;
}
async function getEmailsToInvite(usernameOrEmail: string | string[]) {
export async function getEmailsToInvite(usernameOrEmail: string | string[]) {
const emailsToInvite = Array.isArray(usernameOrEmail) ? usernameOrEmail : [usernameOrEmail];
if (emailsToInvite.length === 0) {
@@ -77,7 +64,7 @@ async function getEmailsToInvite(usernameOrEmail: string | string[]) {
return emailsToInvite;
}
async function getUserToInviteOrThrowIfExists({
export async function getUserToInviteOrThrowIfExists({
usernameOrEmail,
orgId,
isOrg,
@@ -104,7 +91,7 @@ async function getUserToInviteOrThrowIfExists({
return invitee;
}
function checkInputEmailIsValid(email: string) {
export function checkInputEmailIsValid(email: string) {
if (!isEmail(email))
throw new TRPCError({
code: "BAD_REQUEST",
@@ -112,7 +99,37 @@ function checkInputEmailIsValid(email: string) {
});
}
async function createNewUserConnectToOrgIfExists({
export function getOrgConnectionInfo({
orgAutoAcceptDomain,
orgVerified,
isOrg,
usersEmail,
team,
}: {
orgAutoAcceptDomain?: string | null;
orgVerified?: boolean | null;
usersEmail: string;
team: TeamWithParent;
isOrg: boolean;
}) {
let orgId: number | undefined = undefined;
let autoAccept = false;
if (team.parentId || isOrg) {
orgId = team.parentId || team.id;
if (usersEmail.split("@")[1] == orgAutoAcceptDomain) {
autoAccept = orgVerified ?? true;
} else {
// No longer throw error - not needed we just dont auto accept them
orgId = undefined;
autoAccept = false;
}
}
return { orgId, autoAccept };
}
export async function createNewUserConnectToOrgIfExists({
usernameOrEmail,
input,
parentId,
@@ -153,7 +170,7 @@ async function createNewUserConnectToOrgIfExists({
}
}
async function createProvisionalMembership({
export async function createProvisionalMembership({
input,
invitee,
parentId,
@@ -195,7 +212,7 @@ async function createProvisionalMembership({
}
}
async function sendVerificationEmail({
export async function sendVerificationEmail({
usernameOrEmail,
team,
translation,
@@ -261,21 +278,22 @@ async function sendVerificationEmail({
}
}
function checkIfUserIsInDifOrg(
invitee: User,
team: Team & {
parent: Team | null;
}
) {
if (invitee.organizationId !== team.parentId) {
export function throwIfInviteIsToOrgAndUserExists(invitee: User, team: TeamWithParent, isOrg: boolean) {
if (invitee.organizationId && invitee.organizationId !== team.parentId) {
throw new TRPCError({
code: "FORBIDDEN",
message: `User ${invitee.username} is already a member of another organization.`,
});
}
if ((invitee && isOrg) || (team.parentId && invitee)) {
throw new TRPCError({
code: "FORBIDDEN",
message: `You cannot add a user that already exists in Cal.com to an organization. If they wish to join via this email address, they must update their email address in their profile to that of your organization.`,
});
}
}
function getIsOrgVerified(
export function getIsOrgVerified(
isOrg: boolean,
team: Team & {
parent: Team | null;
@@ -303,129 +321,3 @@ function getIsOrgVerified(
isInOrgScope: false,
} as { isInOrgScope: false; orgVerified: never; autoAcceptEmailDomain: never };
}
function getOrgConnectionInfo({
orgAutoAcceptDomain,
orgVerified,
isOrg,
usersEmail,
team,
}: {
orgAutoAcceptDomain?: string | null;
orgVerified?: boolean | null;
usersEmail: string;
team: TeamWithParent;
isOrg: boolean;
}) {
let orgId: number | undefined = undefined;
let autoAccept = false;
if (team.parentId || isOrg) {
orgId = team.parentId || team.id;
if (usersEmail.split("@")[1] == orgAutoAcceptDomain) {
autoAccept = orgVerified ?? true;
} else {
// No longer throw error - not needed we just dont auto accept them
orgId = undefined;
autoAccept = false;
}
}
return { orgId, autoAccept };
}
export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) => {
const team = await getTeamOrThrow(input.teamId, input.isOrg);
const { autoAcceptEmailDomain, orgVerified } = getIsOrgVerified(input.isOrg, team);
await checkPermissions({ userId: ctx.user.id, teamId: input.teamId, isOrg: input.isOrg });
const translation = await getTranslation(input.language ?? "en", "common");
const emailsToInvite = await getEmailsToInvite(input.usernameOrEmail);
for (const usernameOrEmail of emailsToInvite) {
const connectionInfo = getOrgConnectionInfo({
orgVerified,
orgAutoAcceptDomain: autoAcceptEmailDomain,
usersEmail: usernameOrEmail,
team,
isOrg: input.isOrg,
});
const invitee = await getUserToInviteOrThrowIfExists({
usernameOrEmail,
orgId: input.teamId,
isOrg: input.isOrg,
});
if (!invitee) {
checkInputEmailIsValid(usernameOrEmail);
// valid email given, create User and add to team
await createNewUserConnectToOrgIfExists({
usernameOrEmail,
input,
connectionInfo,
parentId: team.parentId,
});
await sendVerificationEmail({ usernameOrEmail, team, translation, ctx, input, connectionInfo });
} else {
checkIfUserIsInDifOrg(invitee, team);
// create provisional membership
await createProvisionalMembership({
input,
invitee,
...(team.parentId ? { parentId: team.parentId } : {}),
});
let sendTo = usernameOrEmail;
if (!isEmail(usernameOrEmail)) {
sendTo = invitee.email;
}
// inform user of membership by email
if (input.sendEmailInvitation && ctx?.user?.name && team?.name) {
const inviteTeamOptions = {
joinLink: `${WEBAPP_URL}/auth/login?callbackUrl=/settings/teams`,
isCalcomMember: true,
};
/**
* Here we want to redirect to a differnt place if onboarding has been completed or not. This prevents the flash of going to teams -> Then to onboarding - also show a differnt email template.
* This only changes if the user is a CAL user and has not completed onboarding and has no password
*/
if (!invitee.completedOnboarding && !invitee.password && invitee.identityProvider === "CAL") {
const token = randomBytes(32).toString("hex");
await prisma.verificationToken.create({
data: {
identifier: usernameOrEmail,
token,
expires: new Date(new Date().setHours(168)), // +1 week
},
});
inviteTeamOptions.joinLink = `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`;
inviteTeamOptions.isCalcomMember = false;
}
await sendTeamInviteEmail({
language: translation,
from: ctx.user.name,
to: sendTo,
teamName: team.name,
...inviteTeamOptions,
isOrg: input.isOrg,
});
}
}
}
if (IS_TEAM_BILLING_ENABLED) {
if (team.parentId) {
await updateQuantitySubscriptionFromStripe(team.parentId);
} else {
await updateQuantitySubscriptionFromStripe(input.teamId);
}
}
return input;
};