Scheduling infrastructure for absolutely everyone.
fix: Support adding a non-existent email as the owner of the organization (#14569)
Hariom Balhara3a0c766ed519
diff --git a/apps/web/playwright/organization/booking.e2e.ts b/apps/web/playwright/organization/booking.e2e.tsindex 4c0cc0d2e3c..f9e4bab934c 100644--- a/apps/web/playwright/organization/booking.e2e.ts+++ b/apps/web/playwright/organization/booking.e2e.ts@@ -2,7 +2,6 @@ import type { Page } from "@playwright/test";import { expect } from "@playwright/test";import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";-import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";import { MembershipRole, SchedulingType } from "@calcom/prisma/enums";import { test } from "../lib/fixtures";@@ -14,6 +13,7 @@ import {testName,} from "../lib/testUtils";import { expectExistingUserToBeInvitedToOrganization } from "../team/expects";+import { gotoPathAndExpectRedirectToOrgDomain } from "./lib/gotoPathAndExpectRedirectToOrgDomain";import { acceptTeamOrOrgInvite, inviteExistingUserToOrganization } from "./lib/inviteUser";test.describe("Bookings", () => {@@ -380,11 +380,11 @@ test.describe("Bookings", () => {await test.step("Booking through old link redirects to new link on org domain", async () => {const event = await userOutsideOrganization.getFirstEventAsOwner();- await expectRedirectToOrgDomain({+ await gotoPathAndExpectRedirectToOrgDomain({page,org,- eventSlug: `/${usernameOutsideOrg}/${event.slug}`,- expectedEventSlug: `/${usernameInOrg}/${event.slug}`,+ path: `/${usernameOutsideOrg}/${event.slug}`,+ expectedPath: `/${usernameInOrg}/${event.slug}`,});// As the redirection correctly happens, the booking would work too which we have verified in previous step. But we can't test that with org domain as that domain doesn't exist.});@@ -463,39 +463,3 @@ async function expectPageToBeNotFound({ page, url }: { page: Page; url: string }await page.goto(`${url}`);await expect(page.locator(`text=${NotFoundPageTextAppDir}`)).toBeVisible();}--async function expectRedirectToOrgDomain({- page,- org,- eventSlug,- expectedEventSlug,-}: {- page: Page;- org: { slug: string | null };- eventSlug: string;- expectedEventSlug: string;-}) {- if (!org.slug) {- throw new Error("Org slug is not defined");- }- page.goto(eventSlug).catch((e) => {- console.log("Expected navigation error to happen");- });-- const orgSlug = org.slug;-- const orgRedirectUrl = await new Promise(async (resolve) => {- page.on("request", (request) => {- if (request.isNavigationRequest()) {- const requestedUrl = request.url();- console.log("Requested navigation to", requestedUrl);- // Resolve on redirection to org domain- if (requestedUrl.includes(orgSlug)) {- resolve(requestedUrl);- }- }- });- });-- expect(orgRedirectUrl).toContain(`${getOrgFullOrigin(org.slug)}${expectedEventSlug}`);-}diff --git a/apps/web/playwright/organization/lib/gotoPathAndExpectRedirectToOrgDomain.ts b/apps/web/playwright/organization/lib/gotoPathAndExpectRedirectToOrgDomain.tsnew file mode 100644index 00000000000..bc50d795d78--- /dev/null+++ b/apps/web/playwright/organization/lib/gotoPathAndExpectRedirectToOrgDomain.ts@@ -0,0 +1,40 @@+import type { Page } from "@playwright/test";+import { expect } from "@playwright/test";++import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";++export async function gotoPathAndExpectRedirectToOrgDomain({+ page,+ org,+ path,+ expectedPath,+}: {+ page: Page;+ org: { slug: string | null };+ path: string;+ expectedPath: string;+}) {+ if (!org.slug) {+ throw new Error("Org slug is not defined");+ }+ page.goto(path).catch((e) => {+ console.log("Expected navigation error to happen");+ });++ const orgSlug = org.slug;++ const orgRedirectUrl = await new Promise(async (resolve) => {+ page.on("request", (request) => {+ if (request.isNavigationRequest()) {+ const requestedUrl = request.url();+ console.log("Requested navigation to", requestedUrl);+ // Resolve on redirection to org domain+ if (requestedUrl.includes(orgSlug)) {+ resolve(requestedUrl);+ }+ }+ });+ });++ expect(orgRedirectUrl).toContain(`${getOrgFullOrigin(org.slug)}${expectedPath}`);+}diff --git a/apps/web/playwright/organization/organization-creation.e2e.ts b/apps/web/playwright/organization/organization-creation.e2e.tsindex 7427a670907..8ee81bca59e 100644--- a/apps/web/playwright/organization/organization-creation.e2e.ts+++ b/apps/web/playwright/organization/organization-creation.e2e.ts@@ -1,11 +1,94 @@+import type { Page } from "@playwright/test";import { expect } from "@playwright/test";+import { JSDOM } from "jsdom";+import type { Messages } from "mailhog";import path from "path";import { uuid } from "short-uuid";import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants";+import type { createEmailsFixture } from "../fixtures/emails";import { test } from "../lib/fixtures";import { fillStripeTestCheckout } from "../lib/testUtils";+import { getEmailsReceivedByUser } from "../lib/testUtils";+import { gotoPathAndExpectRedirectToOrgDomain } from "./lib/gotoPathAndExpectRedirectToOrgDomain";++async function expectEmailWithSubject(+ page: Page,+ emails: ReturnType<typeof createEmailsFixture>,+ userEmail: string,+ subject: string+) {+ if (!emails) return null;++ // eslint-disable-next-line playwright/no-wait-for-timeout+ await page.waitForTimeout(2000);+ const receivedEmails = await getEmailsReceivedByUser({ emails, userEmail });++ const allEmails = (receivedEmails as Messages).items;+ const email = allEmails.find((email) => email.subject === subject);+ if (!email) {+ throw new Error(`Email with subject ${subject} not found`);+ }+ const dom = new JSDOM(email.html);+ return dom;+}++export async function expectOrganizationCreationEmailToBeSent({+ page,+ emails,+ userEmail,+ orgSlug,+}: {+ page: Page;+ emails: ReturnType<typeof createEmailsFixture>;+ userEmail: string;+ orgSlug: string;+}) {+ const dom = await expectEmailWithSubject(page, emails, userEmail, "Your organization has been created");+ const document = dom?.window?.document;+ expect(document?.querySelector(`[href*=${orgSlug}]`)).toBeTruthy();+ return dom;+}++async function expectOrganizationCreationEmailToBeSentWithLinks({+ page,+ emails,+ userEmail,+ oldUsername,+ newUsername,+ orgSlug,+}: {+ page: Page;+ emails: ReturnType<typeof createEmailsFixture>;+ userEmail: string;+ oldUsername: string;+ newUsername: string;+ orgSlug: string;+}) {+ const dom = await expectOrganizationCreationEmailToBeSent({+ page,+ emails,+ userEmail,+ orgSlug,+ });+ const document = dom?.window.document;+ const links = document?.querySelectorAll(`[data-testid="organization-link-info"] [href]`);+ if (!links) {+ throw new Error(`data-testid="organization-link-info doesn't have links`);+ }+ expect((links[0] as unknown as HTMLAnchorElement).href).toContain(oldUsername);+ expect((links[1] as unknown as HTMLAnchorElement).href).toContain(newUsername);+}++export async function expectEmailVerificationEmailToBeSent(+ page: Page,+ emails: ReturnType<typeof createEmailsFixture>,+ userEmail: string+) {+ const subject = "Cal.com: Verify your account";+ return expectEmailWithSubject(page, emails, userEmail, subject);+}test.afterAll(({ users, orgs }) => {users.deleteAll();@@ -20,26 +103,33 @@ function capitalize(text: string) {}test.describe("Organization", () => {- test("Admin should be able to create an org for a target user", async ({ page, users, emails }) => {+ test("Admin should be able to create an org where an existing user is made an owner", async ({+ page,+ users,+ emails,+ }) => {const appLevelAdmin = await users.create({role: "ADMIN",});await appLevelAdmin.apiLogin();- const stringUUID = uuid();- const orgOwnerUsername = `owner-${stringUUID}`;+ const orgOwnerUsernamePrefix = "owner";- const targetOrgEmail = users.trackEmail({- username: orgOwnerUsername,+ const orgOwnerEmail = users.trackEmail({+ username: orgOwnerUsernamePrefix,domain: `example.com`,});+const orgOwnerUser = await users.create({- username: orgOwnerUsername,- email: targetOrgEmail,+ username: orgOwnerUsernamePrefix,+ email: orgOwnerEmail,role: "ADMIN",});- const orgName = capitalize(`${orgOwnerUsername}`);+ const orgOwnerUsernameOutsideOrg = orgOwnerUser.username;+ const orgOwnerUsernameInOrg = orgOwnerEmail.split("@")[0];+ const orgName = capitalize(`${orgOwnerUser.username}`);+ const orgSlug = `myOrg-${uuid()}`.toLowerCase();await page.goto("/settings/organizations/new");await page.waitForLoadState("networkidle");@@ -49,17 +139,16 @@ test.describe("Organization", () => {await expect(page.locator(".text-red-700")).toHaveCount(3);// Happy path- await page.locator("input[name=orgOwnerEmail]").fill(targetOrgEmail);- // Since we are admin fill in this infomation instead of deriving it- await page.locator("input[name=name]").fill(orgName);- await page.locator("input[name=slug]").fill(orgOwnerUsername);-- // Fill in seat infomation- await page.locator("input[name=seats]").fill("30");- await page.locator("input[name=pricePerSeat]").fill("30");+ await fillAndSubmitFirstStepAsAdmin(page, orgOwnerEmail, orgName, orgSlug);+ });- await page.locator("button[type=submit]").click();- await page.waitForLoadState("networkidle");+ await expectOrganizationCreationEmailToBeSentWithLinks({+ page,+ emails,+ userEmail: orgOwnerEmail,+ oldUsername: orgOwnerUsernameOutsideOrg || "",+ newUsername: orgOwnerUsernameInOrg,+ orgSlug,});await test.step("About the organization", async () => {@@ -149,6 +238,56 @@ test.describe("Organization", () => {await expect(upgradeButtonHidden).toBeHidden();});++ // Verify that the owner's old username redirect is properly set+ await gotoPathAndExpectRedirectToOrgDomain({+ page,+ org: {+ slug: orgSlug,+ },+ path: `/${orgOwnerUsernameOutsideOrg}`,+ expectedPath: `/${orgOwnerUsernameInOrg}`,+ });+ });++ test("Admin should be able to create an org where the owner doesn't exist yet", async ({+ page,+ users,+ emails,+ }) => {+ const appLevelAdmin = await users.create({+ role: "ADMIN",+ });+ await appLevelAdmin.apiLogin();+ const orgOwnerUsername = `owner`;+ const orgName = capitalize(`${orgOwnerUsername}`);+ const orgSlug = `myOrg-${uuid()}`.toLowerCase();+ const orgOwnerEmail = users.trackEmail({+ username: orgOwnerUsername,+ domain: `example.com`,+ });++ await page.goto("/settings/organizations/new");+ await page.waitForLoadState("networkidle");++ await test.step("Basic info", async () => {+ // Check required fields+ await page.locator("button[type=submit]").click();+ await expect(page.locator(".text-red-700")).toHaveCount(3);++ // Happy path+ await fillAndSubmitFirstStepAsAdmin(page, orgOwnerEmail, orgName, orgSlug);+ });++ const dom = await expectOrganizationCreationEmailToBeSent({+ page,+ emails,+ userEmail: orgOwnerEmail,+ orgSlug,+ });+ expect(dom?.window.document.querySelector(`[href*=${orgSlug}]`)).toBeTruthy();+ await expectEmailVerificationEmailToBeSent(page, emails, orgOwnerEmail);+ // Rest of the steps remain same as org creation with existing user as owner. So skipping them});test("User can create and upgrade a org", async ({ page, users, emails }) => {@@ -426,3 +565,24 @@ test.describe("Organization", () => {});});});++async function fillAndSubmitFirstStepAsAdmin(+ page: Page,+ targetOrgEmail: string,+ orgName: string,+ orgSlug: string+) {+ await page.locator("input[name=orgOwnerEmail]").fill(targetOrgEmail);+ // Since we are admin fill in this infomation instead of deriving it+ await page.locator("input[name=name]").fill(orgName);+ await page.locator("input[name=slug]").fill(orgSlug);++ // Fill in seat infomation+ await page.locator("input[name=seats]").fill("30");+ await page.locator("input[name=pricePerSeat]").fill("30");++ await Promise.all([+ page.waitForResponse("**/api/trpc/organizations/create**"),+ page.locator("button[type=submit]").click(),+ ]);+}diff --git a/packages/emails/src/templates/OrganizationCreationEmail.tsx b/packages/emails/src/templates/OrganizationCreationEmail.tsxindex 9743d3f69a1..b386b66ca4e 100644--- a/packages/emails/src/templates/OrganizationCreationEmail.tsx+++ b/packages/emails/src/templates/OrganizationCreationEmail.tsx@@ -11,6 +11,7 @@ export const OrganizationCreationEmail = (const { prevLink, newLink, orgName: teamName } = props;const prevLinkWithoutProtocol = props.prevLink?.replace(/https?:\/\//, "");const newLinkWithoutProtocol = props.newLink?.replace(/https?:\/\//, "");+ const isNewUser = props.ownerOldUsername === null;return (<V2BaseEmailHtml subject={props.language(`email_organization_created|subject`)}><p style={{ fontSize: "24px", marginBottom: "16px", textAlign: "center" }}>@@ -35,14 +36,11 @@ export const OrganizationCreationEmail = (marginTop: "32px",lineHeightStep: "24px",}}>- <>- {props.language(`You have been added as an owner of the organization.`, {- invitedBy: props.from.toString(),- appName: APP_NAME,- })}- </>+ You have been added as an owner of the organization. To publish your new organization, visit{" "}+ <a href={`${WEBAPP_URL}/upgrade`}>{WEBAPP_URL}/upgrade</a></p><p+ data-testid="organization-link-info"style={{fontWeight: 400,lineHeight: "24px",@@ -50,26 +48,32 @@ export const OrganizationCreationEmail = (marginTop: "48px",lineHeightStep: "24px",}}>- <Trans i18nKey="email|existing_user_added_link_changed">- Your link has been changed from <a href={prevLink ?? ""}>{prevLinkWithoutProtocol}</a> to{" "}- <a href={newLink ?? ""}>{newLinkWithoutProtocol}</a> but don't worry, all previous links still- work and redirect appropriately.- <br />- <br />- Please note: All of your personal event types have been moved into the <strong>- {teamName}- </strong>{" "}- organisation, which may also include potential personal link.- <br />- <br />- Please log in and make sure you have no private events on your new organisational account.- <br />- <br />- For personal events we recommend creating a new account with a personal email address.- <br />- <br />- Enjoy your new clean link: <a href={`${newLink}?orgRedirection=true`}>{newLinkWithoutProtocol}</a>- </Trans>+ {isNewUser ? (+ <Trans>+ Enjoy your new organization link: <a href={`${newLink}`}>{newLinkWithoutProtocol}</a>+ </Trans>+ ) : (+ <Trans i18nKey="email|existing_user_added_link_changed">+ Your link has been changed from <a href={prevLink ?? ""}>{prevLinkWithoutProtocol}</a> to{" "}+ <a href={newLink ?? ""}>{newLinkWithoutProtocol}</a> but don't worry, all previous links+ still work and redirect appropriately.+ <br />+ <br />+ Please note: All of your personal event types have been moved into the <strong>+ {teamName}+ </strong>{" "}+ organisation, which may also include potential personal link.+ <br />+ <br />+ Please log in and make sure you have no private events on your new organisational account.+ <br />+ <br />+ For personal events we recommend creating a new account with a personal email address.+ <br />+ <br />+ Enjoy your new clean link: <a href={`${newLink}?orgRedirection=true`}>{newLinkWithoutProtocol}</a>+ </Trans>+ )}</p><div className="">diff --git a/packages/emails/templates/organization-creation-email.ts b/packages/emails/templates/organization-creation-email.tsindex 8fffc251322..c6d5de4b449 100644--- a/packages/emails/templates/organization-creation-email.ts+++ b/packages/emails/templates/organization-creation-email.ts@@ -10,10 +10,10 @@ export type OrganizationCreation = {from: string;to: string;ownerNewUsername: string;- ownerOldUsername: string;+ ownerOldUsername: string | null;orgDomain: string;orgName: string;- prevLink: string;+ prevLink: string | null;newLink: string;};diff --git a/packages/features/ee/dsync/lib/handleGroupEvents.ts b/packages/features/ee/dsync/lib/handleGroupEvents.tsindex 507363e4519..9f625205050 100644--- a/packages/features/ee/dsync/lib/handleGroupEvents.ts+++ b/packages/features/ee/dsync/lib/handleGroupEvents.ts@@ -161,7 +161,7 @@ const handleGroupEvents = async (event: DirectorySyncEvent, organizationId: numbconst translation = await getTranslation(user.locale || "en", "common");return sendExistingUserTeamInviteEmails({currentUserTeamName: group.team.name,- existingUsersWithMembersips: [+ existingUsersWithMemberships: [{...user,profile: null,diff --git a/packages/features/ee/dsync/lib/handleUserEvents.ts b/packages/features/ee/dsync/lib/handleUserEvents.tsindex 527ef4c324a..f301467c287 100644--- a/packages/features/ee/dsync/lib/handleUserEvents.ts+++ b/packages/features/ee/dsync/lib/handleUserEvents.ts@@ -49,7 +49,7 @@ const handleUserEvents = async (event: DirectorySyncEvent, organizationId: numbeawait sendExistingUserTeamInviteEmails({currentUserName: user.username,currentUserTeamName: org.name,- existingUsersWithMembersips: [+ existingUsersWithMemberships: [{...addedUser,profile: null,diff --git a/packages/features/ee/dsync/lib/inviteExistingUserToOrg.ts b/packages/features/ee/dsync/lib/inviteExistingUserToOrg.tsindex a1c990cf474..3ccb8a1b5f0 100644--- a/packages/features/ee/dsync/lib/inviteExistingUserToOrg.ts+++ b/packages/features/ee/dsync/lib/inviteExistingUserToOrg.ts@@ -42,7 +42,7 @@ const inviteExistingUserToOrg = async ({await sendExistingUserTeamInviteEmails({currentUserName: user.username,currentUserTeamName: org.name,- existingUsersWithMembersips: [user],+ existingUsersWithMemberships: [user],language: translation,isOrg: true,teamId: org.id,diff --git a/packages/features/ee/organizations/components/CreateANewOrganizationForm.tsx b/packages/features/ee/organizations/components/CreateANewOrganizationForm.tsxindex 0e96cc76ab0..8c1bce1aca0 100644--- a/packages/features/ee/organizations/components/CreateANewOrganizationForm.tsx+++ b/packages/features/ee/organizations/components/CreateANewOrganizationForm.tsx@@ -38,7 +38,6 @@ const CreateANewOrganizationFormChild = ({ session }: { session: Ensure<SessionCconst telemetry = useTelemetry();const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);const isAdmin = session.data.user.role === UserPermissionRole.ADMIN;- const isImpersonated = session.data.user.impersonatedBy;const defaultOrgOwnerEmail = session.data.user.email ?? "";const newOrganizationFormMethods = useForm<{name: string;@@ -115,7 +114,7 @@ const CreateANewOrganizationFormChild = ({ session }: { session: Ensure<SessionCcontainerClassName="w-full"placeholder="[email protected]"name="orgOwnerEmail"- disabled={!isAdmin && !isImpersonated}+ disabled={!isAdmin}label={t("admin_email")}defaultValue={value}onChange={(e) => {@@ -188,7 +187,7 @@ const CreateANewOrganizationFormChild = ({ session }: { session: Ensure<SessionC/></div>- {(isAdmin || isImpersonated) && (+ {isAdmin && (<><section className="grid grid-cols-2 gap-2"><div className="w-full">diff --git a/packages/features/ee/teams/components/TeamList.tsx b/packages/features/ee/teams/components/TeamList.tsxindex 5067a1a4d4a..5e1218e5a6e 100644--- a/packages/features/ee/teams/components/TeamList.tsx+++ b/packages/features/ee/teams/components/TeamList.tsx@@ -1,6 +1,6 @@import { useState } from "react";-import { ORG_SELF_SERVE_ENABLED } from "@calcom/lib/constants";+import { ORG_SELF_SERVE_ENABLED, ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE } from "@calcom/lib/constants";import { trackFormbricksAction } from "@calcom/lib/formbricks-client";import { useLocale } from "@calcom/lib/hooks/useLocale";import type { RouterOutputs } from "@calcom/trpc/react";@@ -55,7 +55,7 @@ export default function TeamList(props: Props) {{ORG_SELF_SERVE_ENABLED &&!props.pending &&!isUserAlreadyInAnOrganization &&- props.teams.length > 2 &&+ props.teams.length >= ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE &&props.teams.map((team, i) =>team.role !== "MEMBER" &&diff --git a/packages/lib/server/repository/organization.ts b/packages/lib/server/repository/organization.tsindex 45b0c918863..1c5be89ec20 100644--- a/packages/lib/server/repository/organization.ts+++ b/packages/lib/server/repository/organization.ts@@ -1,3 +1,4 @@+import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants";import logger from "@calcom/lib/logger";import { safeStringify } from "@calcom/lib/safeStringify";@@ -5,6 +6,7 @@ import { prisma } from "@calcom/prisma";import { MembershipRole } from "@calcom/prisma/enums";import { createAProfileForAnExistingUser } from "../../createAProfileForAnExistingUser";+import { UserRepository } from "./user";const orgSelect = {id: true,@@ -13,7 +15,7 @@ const orgSelect = {logoUrl: true,};export class OrganizationRepository {- static async createWithOwner({+ static async createWithExistingUserAsOwner({orgData,owner,}: {@@ -33,8 +35,84 @@ export class OrganizationRepository {nonOrgUsername: string;};}) {- logger.debug("Creating organization with owner", safeStringify({ orgData, owner }));- const organization = await prisma.team.create({+ logger.debug("createWithExistingUserAsOwner", safeStringify({ orgData, owner }));+ const organization = await this.create(orgData);+ const ownerProfile = await createAProfileForAnExistingUser({+ user: {+ id: owner.id,+ email: owner.email,+ currentUsername: owner.nonOrgUsername,+ },+ organizationId: organization.id,+ });++ await prisma.membership.create({+ data: {+ userId: owner.id,+ role: MembershipRole.OWNER,+ accepted: true,+ teamId: organization.id,+ },+ });+ return { organization, ownerProfile };+ }++ static async createWithNonExistentOwner({+ orgData,+ owner,+ }: {+ orgData: {+ name: string;+ slug: string;+ isOrganizationConfigured: boolean;+ isOrganizationAdminReviewed: boolean;+ autoAcceptEmail: string;+ seats: number | null;+ pricePerSeat: number | null;+ isPlatform: boolean;+ };+ owner: {+ email: string;+ };+ }) {+ logger.debug("createWithNonExistentOwner", safeStringify({ orgData, owner }));+ const organization = await this.create(orgData);+ const ownerUsernameInOrg = getOrgUsernameFromEmail(owner.email, orgData.autoAcceptEmail);+ const ownerInDb = await UserRepository.create({+ email: owner.email,+ username: ownerUsernameInOrg,+ organizationId: organization.id,+ });++ await prisma.membership.create({+ data: {+ userId: ownerInDb.id,+ role: MembershipRole.OWNER,+ accepted: true,+ teamId: organization.id,+ },+ });++ return {+ orgOwner: ownerInDb,+ organization,+ ownerProfile: {+ username: ownerUsernameInOrg,+ },+ };+ }++ static async create(orgData: {+ name: string;+ slug: string;+ isOrganizationConfigured: boolean;+ isOrganizationAdminReviewed: boolean;+ autoAcceptEmail: string;+ seats: number | null;+ pricePerSeat: number | null;+ isPlatform: boolean;+ }) {+ return await prisma.team.create({data: {name: orgData.name,isOrganization: true,@@ -55,25 +133,6 @@ export class OrganizationRepository {},},});-- const ownerProfile = await createAProfileForAnExistingUser({- user: {- id: owner.id,- email: owner.email,- currentUsername: owner.nonOrgUsername,- },- organizationId: organization.id,- });-- await prisma.membership.create({- data: {- userId: owner.id,- role: MembershipRole.OWNER,- accepted: true,- teamId: organization.id,- },- });- return { organization, ownerProfile };}static async findById({ id }: { id: number }) {diff --git a/packages/lib/server/repository/user.ts b/packages/lib/server/repository/user.tsindex c20a12875a4..a0b12fbcba4 100644--- a/packages/lib/server/repository/user.ts+++ b/packages/lib/server/repository/user.ts@@ -1,11 +1,17 @@+import { createHash } from "crypto";+import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";+import { hashPassword } from "@calcom/features/auth/lib/hashPassword";+import logger from "@calcom/lib/logger";+import { safeStringify } from "@calcom/lib/safeStringify";+import { getTranslation } from "@calcom/lib/server/i18n";import prisma from "@calcom/prisma";import { Prisma } from "@calcom/prisma/client";import type { User as UserType } from "@calcom/prisma/client";import type { UpId, UserProfile } from "@calcom/types/UserProfile";-import logger from "../../logger";-import { safeStringify } from "../../safeStringify";+import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "../../availability";+import slugify from "../../slugify";import { ProfileRepository } from "./profile";import { getParsedTeam } from "./teamUtils";@@ -435,4 +441,52 @@ export class UserRepository {},});}++ static async create({+ email,+ username,+ organizationId,+ }: {+ email: string;+ username: string;+ organizationId: number | null;+ }) {+ const password = createHash("md5").update(`${email}${process.env.CALENDSO_ENCRYPTION_KEY}`).digest("hex");+ const hashedPassword = await hashPassword(password);+ const t = await getTranslation("en", "common");+ const availability = getAvailabilityFromSchedule(DEFAULT_SCHEDULE);++ return await prisma.user.create({+ data: {+ username: slugify(username),+ email: email,+ password: { create: { hash: hashedPassword } },+ // Default schedule+ schedules: {+ create: {+ name: t("default_schedule_name"),+ availability: {+ createMany: {+ data: availability.map((schedule) => ({+ days: schedule.days,+ startTime: schedule.startTime,+ endTime: schedule.endTime,+ })),+ },+ },+ },+ },+ organizationId: organizationId,+ profiles: organizationId+ ? {+ create: {+ username: slugify(username),+ organizationId: organizationId,+ uid: ProfileRepository.generateProfileUid(),+ },+ }+ : undefined,+ },+ });+ }}diff --git a/packages/trpc/server/routers/viewer/organizations/create.handler.ts b/packages/trpc/server/routers/viewer/organizations/create.handler.tsindex 556d1ed108e..44f221817e8 100644--- a/packages/trpc/server/routers/viewer/organizations/create.handler.ts+++ b/packages/trpc/server/routers/viewer/organizations/create.handler.ts@@ -2,12 +2,13 @@ import { lookup } from "dns";import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";import { sendAdminOrganizationNotification, sendOrganizationCreationEmail } from "@calcom/emails";+import { sendEmailVerification } from "@calcom/features/auth/lib/verifyEmail";import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";import {RESERVED_SUBDOMAINS,- WEBAPP_URL,ORG_SELF_SERVE_ENABLED,ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE,+ WEBAPP_URL,} from "@calcom/lib/constants";import { createDomain } from "@calcom/lib/domainManager/organization";import { getTranslation } from "@calcom/lib/server/i18n";@@ -46,6 +47,7 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {select: {id: true,role: true,+ email: true,teams: {select: {team: {@@ -65,13 +67,20 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {throw new TRPCError({ code: "FORBIDDEN", message: "Only admins can create organizations" });}+ if (!IS_USER_ADMIN && loggedInUser.email !== orgOwnerEmail) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You can only create organization where you are the owner",+ });+ }+const publishedTeams = loggedInUser.teams.filter((team) => !!team.team.slug);if (!IS_USER_ADMIN && publishedTeams.length < ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE) {- throw new TRPCError({ code: "FORBIDDEN", message: "You need to have atleast two published teams." });+ throw new TRPCError({ code: "FORBIDDEN", message: "You need to have minimum published teams." });}- const orgOwner = await prisma.user.findUnique({+ let orgOwner = await prisma.user.findUnique({where: {email: orgOwnerEmail,},@@ -92,22 +101,11 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {if (hasAnOrgWithSameSlug || RESERVED_SUBDOMAINS.includes(slug))throw new TRPCError({ code: "BAD_REQUEST", message: "organization_url_taken" });- if (!orgOwner) {- // Create a new user and invite them as the owner of the organization- throw new Error("Inviting a new user to be the owner of the organization is not supported yet");- }-- // If we are making the loggedIn user the owner of the organization and he is already a part of an organization, we don't allow it because multi-org is not supported yet- const isLoggedInUserOrgOwner = orgOwner.id === loggedInUser.id;- if (ctx.user.profile.organizationId && isLoggedInUserOrgOwner) {- throw new TRPCError({ code: "FORBIDDEN", message: "User is part of an organization already" });- }-- const t = await getTranslation(ctx.user.locale ?? "en", "common");-const availability = getAvailabilityFromSchedule(DEFAULT_SCHEDULE);const isOrganizationConfigured = isPlatform ? true : await createDomain(slug);+ const loggedInUserTranslation = await getTranslation(ctx.user.locale, "common");+ const inputLanguageTranslation = await getTranslation(input.language ?? "en", "common");if (!isOrganizationConfigured) {// Otherwise, we proceed to send an administrative email to admins regarding@@ -124,7 +122,7 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {webappIPAddress: await getIPAddress(WEBAPP_URL.replace("https://", "")?.replace("http://", "").replace(/(:.*)/, "")),- t,+ t: loggedInUserTranslation,});} else {console.warn("Organization created: subdomain not configured and couldn't notify adminnistrators");@@ -132,54 +130,111 @@ export const createHandler = async ({ input, ctx }: CreateOptions) => {}const autoAcceptEmail = orgOwnerEmail.split("@")[1];- const nonOrgUsernameForOwner = orgOwner.username || "";- const { organization, ownerProfile } = await OrganizationRepository.createWithOwner({- orgData: {- name,- slug,- isOrganizationConfigured,- isOrganizationAdminReviewed: IS_USER_ADMIN,- autoAcceptEmail,- seats: seats ?? null,- pricePerSeat: pricePerSeat ?? null,- isPlatform,- },- owner: {- id: orgOwner.id,++ const orgData = {+ name,+ slug,+ isOrganizationConfigured,+ isOrganizationAdminReviewed: IS_USER_ADMIN,+ autoAcceptEmail,+ seats: seats ?? null,+ pricePerSeat: pricePerSeat ?? null,+ isPlatform,+ };++ // Create a new user and invite them as the owner of the organization+ if (!orgOwner) {+ const data = await OrganizationRepository.createWithNonExistentOwner({+ orgData,+ owner: {+ email: orgOwnerEmail,+ },+ });++ orgOwner = data.orgOwner;++ const { organization, ownerProfile } = data;++ const translation = await getTranslation(input.language ?? "en", "common");++ await sendEmailVerification({email: orgOwnerEmail,- nonOrgUsername: nonOrgUsernameForOwner,- },- });+ language: ctx.user.locale,+ username: ownerProfile.username || "",+ });- const translation = await getTranslation(input.language ?? "en", "common");-- await sendOrganizationCreationEmail({- language: translation,- from: ctx.user.name ?? `${organization.name}'s admin`,- to: orgOwnerEmail,- ownerNewUsername: ownerProfile.username,- ownerOldUsername: nonOrgUsernameForOwner,- orgDomain: getOrgFullOrigin(slug, { protocol: false }),- orgName: organization.name,- prevLink: `${getOrgFullOrigin("", { protocol: true })}/${nonOrgUsernameForOwner}`,- newLink: `${getOrgFullOrigin(slug, { protocol: true })}/${ownerProfile.username}`,- });+ await sendOrganizationCreationEmail({+ language: translation,+ from: ctx.user.name ?? `${organization.name}'s admin`,+ to: orgOwnerEmail,+ ownerNewUsername: ownerProfile.username,+ ownerOldUsername: null,+ orgDomain: getOrgFullOrigin(slug, { protocol: false }),+ orgName: organization.name,+ prevLink: null,+ newLink: `${getOrgFullOrigin(slug, { protocol: true })}/${ownerProfile.username}`,+ });- if (!organization.id) throw Error("User not created");- const user = await UserRepository.enrichUserWithItsProfile({- user: { ...orgOwner, organizationId: organization.id },- });+ const user = await UserRepository.enrichUserWithItsProfile({+ user: { ...orgOwner, organizationId: organization.id },+ });- await prisma.availability.createMany({- data: availability.map((schedule) => ({- days: schedule.days,- startTime: schedule.startTime,- endTime: schedule.endTime,+ return {userId: user.id,- })),- });+ email: user.email,+ organizationId: user.organizationId,+ upId: user.profile.upId,+ };+ } else {+ // If we are making the loggedIn user the owner of the organization and he is already a part of an organization, we don't allow it because multi-org is not supported yet+ const isLoggedInUserOrgOwner = orgOwner.id === loggedInUser.id;+ if (ctx.user.profile.organizationId && isLoggedInUserOrgOwner) {+ throw new TRPCError({ code: "FORBIDDEN", message: "User is part of an organization already" });+ }- return { userId: user.id, email: user.email, organizationId: user.organizationId, upId: user.profile.upId };+ const nonOrgUsernameForOwner = orgOwner.username || "";+ const { organization, ownerProfile } = await OrganizationRepository.createWithExistingUserAsOwner({+ orgData,+ owner: {+ id: orgOwner.id,+ email: orgOwnerEmail,+ nonOrgUsername: nonOrgUsernameForOwner,+ },+ });++ await sendOrganizationCreationEmail({+ language: inputLanguageTranslation,+ from: ctx.user.name ?? `${organization.name}'s admin`,+ to: orgOwnerEmail,+ ownerNewUsername: ownerProfile.username,+ ownerOldUsername: nonOrgUsernameForOwner,+ orgDomain: getOrgFullOrigin(slug, { protocol: false }),+ orgName: organization.name,+ prevLink: `${getOrgFullOrigin("", { protocol: true })}/${nonOrgUsernameForOwner}`,+ newLink: `${getOrgFullOrigin(slug, { protocol: true })}/${ownerProfile.username}`,+ });++ if (!organization.id) throw Error("User not created");+ const user = await UserRepository.enrichUserWithItsProfile({+ user: { ...orgOwner, organizationId: organization.id },+ });++ await prisma.availability.createMany({+ data: availability.map((schedule) => ({+ days: schedule.days,+ startTime: schedule.startTime,+ endTime: schedule.endTime,+ userId: user.id,+ })),+ });++ return {+ userId: user.id,+ email: user.email,+ organizationId: user.organizationId,+ upId: user.profile.upId,+ };+ }// Sync Services: Close.com//closeComUpsertOrganizationUser(createTeam, ctx.user, MembershipRole.OWNER);diff --git a/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler.ts b/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler.tsindex 17d3d563e29..1b8abe0c6da 100644--- a/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler.ts+++ b/packages/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler.ts@@ -23,7 +23,7 @@ import {getOrgConnectionInfo,getIsOrgVerified,sendSignupToOrganizationEmail,- getUsersToInvite,+ getExistingUsersToInvite,createNewUsersConnectToOrgIfExists,createMemberships,groupUsersByJoinability,@@ -41,6 +41,7 @@ type InviteMemberOptions = {};export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) => {+ const myLog = log.getSubLogger({ prefix: ["inviteMemberHandler"] });const translation = await getTranslation(input.language ?? "en", "common");await checkRateLimitAndThrowError({identifier: `invitedBy:${ctx.user.id}`,@@ -63,6 +64,10 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) =const { autoAcceptEmailDomain, orgVerified } = getIsOrgVerified(isOrg, team);const usernameOrEmailsToInvite = await getUsernameOrEmailsToInvite(input.usernameOrEmail);++ const isBulkInvite = usernameOrEmailsToInvite.length > 1;+ const beSilentAboutErrors = isBulkInvite;+const orgConnectInfoByUsernameOrEmail = usernameOrEmailsToInvite.reduce((acc, usernameOrEmail) => {return {...acc,@@ -75,12 +80,12 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) =}),};}, {} as Record<string, ReturnType<typeof getOrgConnectionInfo>>);- const existingUsersWithMemberships = await getUsersToInvite({+ const existingUsersWithMemberships = await getExistingUsersToInvite({usernamesOrEmails: usernameOrEmailsToInvite,- isInvitedToOrg: isOrg,team,});+ // Existing users have a criteria to be invitedconst existingUsersWithMembershipsThatNeedToBeInvited = existingUsersWithMemberships.filter((invitee) => invitee.canBeInvited);@@ -93,14 +98,26 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) ={ emails: [], usernames: [] } as { emails: string[]; usernames: string[] });+ // New Users can always be invitedconst newUsersEmailsOrUsernames = usernameOrEmailsToInvite.filter((usernameOrEmail) =>!existingUsersEmailsAndUsernames.emails.includes(usernameOrEmail) &&!existingUsersEmailsAndUsernames.usernames.includes(usernameOrEmail));- log.debug(- "inviteMemberHandler",+ 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({usernameOrEmailsToInvite,orgConnectInfoByUsernameOrEmail,@@ -137,7 +154,7 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) =const orgSlug = organization ? organization.slug || organization.requestedSlug : null;// deal with existing users invited to join the team/orgawait handleExistingUsersInvites({- existingUsersWithMembersips: existingUsersWithMembershipsThatNeedToBeInvited,+ existingUsersWithMemberships: existingUsersWithMembershipsThatNeedToBeInvited,team,orgConnectInfoByUsernameOrEmail,input,@@ -158,14 +175,14 @@ export const inviteMemberHandler = async ({ ctx, input }: InviteMemberOptions) =export default inviteMemberHandler;async function handleExistingUsersInvites({- existingUsersWithMembersips,+ existingUsersWithMemberships,team,orgConnectInfoByUsernameOrEmail,input,inviter,orgSlug,}: {- existingUsersWithMembersips: Awaited<ReturnType<typeof getUsersToInvite>>;+ existingUsersWithMemberships: Awaited<ReturnType<typeof getExistingUsersToInvite>>;team: TeamWithParent;orgConnectInfoByUsernameOrEmail: Record<string, { orgId: number | undefined; autoAccept: boolean }>;input: {@@ -180,14 +197,14 @@ async function handleExistingUsersInvites({};orgSlug: string | null;}) {- if (!existingUsersWithMembersips.length) {+ if (!existingUsersWithMemberships.length) {return;}const translation = await getTranslation(input.language ?? "en", "common");if (!team.isOrganization) {const [autoJoinUsers, regularUsers] = groupUsersByJoinability({- existingUsersWithMembersips: existingUsersWithMembersips.map((u) => {+ existingUsersWithMemberships: existingUsersWithMemberships.map((u) => {return {...u,profile: null,@@ -223,7 +240,7 @@ async function handleExistingUsersInvites({await sendExistingUserTeamInviteEmails({currentUserName: inviter.name,currentUserTeamName: team?.name,- existingUsersWithMembersips: autoJoinUsers,+ existingUsersWithMemberships: autoJoinUsers,language: translation,isOrg: input.isOrg,teamId: team.id,@@ -244,7 +261,7 @@ async function handleExistingUsersInvites({await sendExistingUserTeamInviteEmails({currentUserName: inviter.name,currentUserTeamName: team?.name,- existingUsersWithMembersips: regularUsers,+ existingUsersWithMemberships: regularUsers,language: translation,isOrg: input.isOrg,teamId: team.id,@@ -279,12 +296,12 @@ async function handleExistingUsersInvites({log.debug("Inviting existing users to an organization",safeStringify({- existingUsersWithMembersips,+ existingUsersWithMemberships,}));const existingUsersWithMembershipsNew = await Promise.all(- existingUsersWithMembersips.map(async (user) => {+ existingUsersWithMemberships.map(async (user) => {const shouldAutoAccept = orgConnectInfoByUsernameOrEmail[user.email].autoAccept;let profile = null;if (shouldAutoAccept) {@@ -325,7 +342,7 @@ async function handleExistingUsersInvites({await sendExistingUserTeamInviteEmails({currentUserName: inviter.name,currentUserTeamName: team?.name,- existingUsersWithMembersips: autoJoinUsers,+ existingUsersWithMemberships: autoJoinUsers,language: translation,isOrg: input.isOrg,teamId: team.id,@@ -338,7 +355,7 @@ async function handleExistingUsersInvites({await sendExistingUserTeamInviteEmails({currentUserName: inviter.name,currentUserTeamName: team?.name,- existingUsersWithMembersips: regularUsers,+ existingUsersWithMemberships: regularUsers,language: translation,isOrg: input.isOrg,teamId: team.id,diff --git a/packages/trpc/server/routers/viewer/teams/inviteMember/utils.ts b/packages/trpc/server/routers/viewer/teams/inviteMember/utils.tsindex 1bd5bd093d0..c77cc24b1f4 100644--- a/packages/trpc/server/routers/viewer/teams/inviteMember/utils.ts+++ b/packages/trpc/server/routers/viewer/teams/inviteMember/utils.ts@@ -101,6 +101,8 @@ export async function getUsernameOrEmailsToInvite(usernameOrEmail: string | stri}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;@@ -120,9 +122,9 @@ export function canBeInvited(invitee: UserWithMembership, team: TeamWithParent)return false;}- // user is invited to join a team in an organization where he isn't a memberif (!ENABLE_PROFILE_SWITCHER &&+ // Member of an organization is invited to join a team that is not a subteam of the organizationinvitee.profiles.find((profile) => profile.organizationId != team.parentId)) {return false;@@ -130,23 +132,13 @@ export function canBeInvited(invitee: UserWithMembership, team: TeamWithParent)return true;}-export async function getUsersToInvite({+export async function getExistingUsersToInvite({usernamesOrEmails,- isInvitedToOrg,team,}: {usernamesOrEmails: string[];- isInvitedToOrg: boolean;team: TeamWithParent;}) {- const memberships = [];- if (isInvitedToOrg) {- memberships.push({ teamId: team.id });- } else {- memberships.push({ teamId: team.id });- team.parentId && memberships.push({ teamId: team.parentId });- }-const invitees: UserWithMembership[] = await prisma.user.findMany({where: {OR: [@@ -513,12 +505,12 @@ export function getAutoJoinStatus({// split invited users between ones that can autojoin and the others who cannot autojoinexport const groupUsersByJoinability = ({- existingUsersWithMembersips,+ existingUsersWithMemberships,team,connectionInfoMap,}: {team: TeamWithParent;- existingUsersWithMembersips: (UserWithMembership & {+ existingUsersWithMemberships: (UserWithMembership & {profile: {username: string;} | null;@@ -528,8 +520,8 @@ export const groupUsersByJoinability = ({const usersToAutoJoin = [];const regularUsers = [];- for (let index = 0; index < existingUsersWithMembersips.length; index++) {- const existingUserWithMembersips = existingUsersWithMembersips[index];+ for (let index = 0; index < existingUsersWithMemberships.length; index++) {+ const existingUserWithMembersips = existingUsersWithMemberships[index];const autoJoinStatus = getAutoJoinStatus({invitee: existingUserWithMembersips,@@ -561,7 +553,7 @@ export const sendEmails = async (emailPromises: Promise<void>[]) => {};export const sendExistingUserTeamInviteEmails = async ({- existingUsersWithMembersips,+ existingUsersWithMemberships,language,currentUserTeamName,currentUserName,@@ -573,7 +565,7 @@ export const sendExistingUserTeamInviteEmails = async ({}: {language: TFunction;isAutoJoin: boolean;- existingUsersWithMembersips: (UserWithMembership & {+ existingUsersWithMemberships: (UserWithMembership & {profile: {username: string;} | null;@@ -585,7 +577,7 @@ export const sendExistingUserTeamInviteEmails = async ({teamId: number;orgSlug: string | null;}) => {- const sendEmailsPromises = existingUsersWithMembersips.map(async (user) => {+ const sendEmailsPromises = existingUsersWithMemberships.map(async (user) => {let sendTo = user.email;if (!isEmail(user.email)) {sendTo = user.email;