feat: Organizations (#8993)

* Initial commit

* Adding feature flag

* feat: Orgs Schema Changing `scopedMembers` to `orgUsers` (#9209)

* Change scopedMembers to orgMembers

* Change to orgUsers

* Letting duplicate slugs for teams to support orgs

* Covering null on unique clauses

* Supporting having the orgId in the session cookie

* feat: organization event type filter (#9253)

Signed-off-by: Udit Takkar <[email protected]>

* Missing changes to support orgs schema changes

* feat: Onboarding process to create an organization (#9184)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* feedback

* Making sure we check requestedSlug now

---------

Co-authored-by: sean-brydon <[email protected]>

* feat: [CAL-1816] Organization subdomain support (#9345)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* Covering users and subteams, excluding non-org users

* Unpublished teams shows correctly

* Create subdomain in Vercel

* feedback

* Renaming Vercel env vars

* Vercel domain check before creation

* Supporting cal-staging.com

* Change to have vercel detect it

* vercel domain check data message error

* Remove check domain

* Making sure we check requestedSlug now

* Feedback and unneeded code

* Reverting unneeded changes

* Unneeded changes

---------

Co-authored-by: sean-brydon <[email protected]>

* Vercel subdomain creation in PROD only

* Making sure we let localhost still work

* Feedback

* Type check fixes

* feat: Organization branding in side menu (#9279)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Org branding provider used in shell sidebar

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Using org avatar (temp)

* Not showing org logo if not set

* User onboarding with org branding (slug)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* feedback

* Feedback

* Org public profile

* Public profiles for team event types

* Added setup profile alert

* Using org avatar on subteams avatar

* Making sure we show the set up profile on org only

* Profile username availability rely on org hook

* Update apps/web/pages/team/[slug].tsx

Co-authored-by: sean-brydon <[email protected]>

* Update apps/web/pages/team/[slug].tsx

Co-authored-by: sean-brydon <[email protected]>

---------

Co-authored-by: sean-brydon <[email protected]>

* feat: Organization support for event types page (#9449)

* Desktop first banner, mobile pending

* Removing dead code and img

* WIP

* Adds Email verification template+translations for organizations (#9202)

* First step done

* Merge branch 'feat/organizations-onboarding' of github.com:calcom/cal.com into feat/organizations-onboarding

* Step 2 done, avatar not working

* Covering null on unique clauses

* Onboarding admins step

* Last step to create teams

* Moving change password handler, improving verifying code flow

* Clearing error before submitting

* Reverting email testing api changes

* Reverting having the banner for now

* Consistent exported components

* Remove unneeded files from banner

* Removing uneeded code

* Fixing avatar selector

* Org branding provider used in shell sidebar

* Using meta component for head/descr

* Missing i18n strings

* Feedback

* Making an org avatar (temp)

* Using org avatar (temp)

* Not showing org logo if not set

* User onboarding with org branding (slug)

* Check for subteams slug clashes with usernames

* Fixing create teams onsuccess

* feedback

* Feedback

* Org public profile

* Public profiles for team event types

* Added setup profile alert

* Using org avatar on subteams avatar

* Processing orgs and children as profile options

* Reverting change not belonging to this PR

* Making sure we show the set up profile on org only

* Removing console.log

* Comparing memberships to choose the highest one

---------

Co-authored-by: sean-brydon <[email protected]>

* Type errors

* Refactor and type fixes

* Update orgDomains.ts

* Feedback

* Reverting

* NIT

* fix issue getting org slug from domain

* Improving orgDomains util

* Host comes with port

* Update useRouterQuery.ts

* Feedback

* Feedback

* Feedback

* Feedback: SSR for user event-types to have org context

* chore: Cache node_modules (#9492)

* Adding check for cache hit

* Adding a separate install step first

* Put the restore cache steps back

* Revert the uses type for restoring cache

* Added step to restore nm cache

* Removed the cache-hit check

* Comments and naming

* Removed extra install command

* Updated the name of the linting step to be more clear

* Removes the need for useEffect here

* Feedback

* Feedback

* Cookie domain needs a dot

* Type fix

* Update apps/web/public/static/locales/en/common.json

Co-authored-by: Omar López <[email protected]>

* Update packages/emails/src/templates/OrganizationAccountVerifyEmail.tsx

* Feedback

---------

Signed-off-by: Udit Takkar <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: sean-brydon <[email protected]>
Co-authored-by: zomars <[email protected]>
Co-authored-by: Efraín Rochín <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-06-14 21:40:20 +00:00
1 parent 9db4a04cd9
commit c5483c81de
104 files changed
+3021 -404

No files matched your search

@@ -72,6 +72,7 @@ export async function getServerSession(options: {
image: `${CAL_URL}/${user.username}/avatar.png`,
impersonatedByUID: token.impersonatedByUID ?? undefined,
belongsToActiveTeam: token.belongsToActiveTeam,
organizationId: token.organizationId,
},
};
@@ -82,6 +82,7 @@ const providers: Provider[] = [
metadata: true,
identityProvider: true,
password: true,
organizationId: true,
twoFactorEnabled: true,
twoFactorSecret: true,
teams: {
@@ -172,6 +173,7 @@ const providers: Provider[] = [
name: user.name,
role: validateRole(user.role),
belongsToActiveTeam: hasActiveTeams,
organizationId: user.organizationId,
};
},
}),
@@ -353,6 +355,7 @@ export const AUTH_OPTIONS: AuthOptions = {
username: true,
name: true,
email: true,
organizationId: true,
role: true,
teams: {
include: {
@@ -397,6 +400,7 @@ export const AUTH_OPTIONS: AuthOptions = {
role: user.role,
impersonatedByUID: user?.impersonatedByUID,
belongsToActiveTeam: user?.belongsToActiveTeam,
organizationId: user?.organizationId,
};
}
@@ -434,6 +438,7 @@ export const AUTH_OPTIONS: AuthOptions = {
role: existingUser.role,
impersonatedByUID: token.impersonatedByUID as number,
belongsToActiveTeam: token?.belongsToActiveTeam as boolean,
organizationId: token?.organizationId,
};
}
@@ -452,6 +457,7 @@ export const AUTH_OPTIONS: AuthOptions = {
role: token.role as UserPermissionRole,
impersonatedByUID: token.impersonatedByUID as number,
belongsToActiveTeam: token?.belongsToActiveTeam as boolean,
organizationId: token?.organizationId,
},
};
return calendsoSession;
@@ -605,7 +611,12 @@ export const AUTH_OPTIONS: AuthOptions = {
!existingUserWithEmail.username
) {
await prisma.user.update({
where: { email: existingUserWithEmail.email },
where: {
email_username: {
email: existingUserWithEmail.email,
username: existingUserWithEmail.username!,
},
},
data: {
// update the email to the IdP email
email: user.email,
@@ -6,7 +6,7 @@ import { queryNumberArray, useTypedQuery } from "@calcom/lib/hooks/useTypedQuery
export const filterQuerySchema = z.object({
teamIds: queryNumberArray.optional(),
userIds: queryNumberArray.optional(),
status: z.enum(["upcoming", "recurring", "past", "cancelled", "unconfirmed"]),
status: z.enum(["upcoming", "recurring", "past", "cancelled", "unconfirmed"]).optional(),
eventTypeIds: queryNumberArray.optional(),
});
@@ -10,7 +10,7 @@ const teamIdschema = z.object({
});
const auditAndReturnNextUser = async (
impersonatedUser: Pick<User, "id" | "username" | "email" | "name" | "role">,
impersonatedUser: Pick<User, "id" | "username" | "email" | "name" | "role" | "organizationId">,
impersonatedByUID: number,
hasTeam?: boolean
) => {
@@ -38,6 +38,7 @@ const auditAndReturnNextUser = async (
role: impersonatedUser.role,
impersonatedByUID,
belongsToActiveTeam: hasTeam,
organizationId: impersonatedUser.organizationId,
};
return obj;
@@ -79,6 +80,7 @@ const ImpersonationProvider = CredentialsProvider({
role: true,
name: true,
email: true,
organizationId: true,
disableImpersonation: true,
teams: {
where: {
@@ -0,0 +1,36 @@
import type { NextApiRequest, NextApiResponse } from "next";
import z from "zod";
import { HttpError } from "@calcom/lib/http-error";
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
const querySchema = z.object({
org: z.string({ required_error: "org slug is required" }),
});
async function handler(req: NextApiRequest, res: NextApiResponse) {
const parsedQuery = querySchema.safeParse(req.query);
if (!parsedQuery.success) throw new HttpError({ statusCode: 400, message: parsedQuery.error.message });
const {
data: { org: slug },
} = parsedQuery;
if (!slug) return res.status(400).json({ message: "Org is needed" });
const org = await prisma.team.findFirst({ where: { slug }, select: { children: true, metadata: true } });
if (!org) return res.status(400).json({ message: "Org doesn't exist" });
const metadata = teamMetadataSchema.parse(org?.metadata);
if (!metadata?.isOrganization) return res.status(400).json({ message: "Team is not an org" });
return res.status(200).json({ slugs: org.children.map((ch) => ch.slug) });
}
export default defaultHandler({
GET: Promise.resolve({ default: defaultResponder(handler) }),
});
@@ -0,0 +1,122 @@
import { useRouter } from "next/router";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import z from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Avatar, Button, Form, ImageUploader, Alert, Label, TextAreaField } from "@calcom/ui";
import { ArrowRight, Plus } from "@calcom/ui/components/icon";
const querySchema = z.object({
id: z.string(),
});
export const AboutOrganizationForm = () => {
const { t } = useLocale();
const router = useRouter();
const { id: orgId } = querySchema.parse(router.query);
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
const [image, setImage] = useState("");
const aboutOrganizationFormMethods = useForm<{
logo: string;
bio: string;
}>();
const updateOrganizationMutation = trpc.viewer.organizations.update.useMutation({
onSuccess: (data) => {
if (data.update) {
router.push(`/settings/organizations/${orgId}/onboard-admins`);
}
},
onError: (err) => {
setServerErrorMessage(err.message);
},
});
return (
<>
<Form
form={aboutOrganizationFormMethods}
className="space-y-5"
handleSubmit={(v) => {
if (!updateOrganizationMutation.isLoading) {
setServerErrorMessage(null);
updateOrganizationMutation.mutate({ ...v, orgId });
}
}}>
{serverErrorMessage && (
<div>
<Alert severity="error" message={serverErrorMessage} />
</div>
)}
<div>
<Controller
control={aboutOrganizationFormMethods.control}
name="logo"
render={() => (
<>
<Label>{t("organization_logo")}</Label>
<div className="flex items-center">
<Avatar
alt=""
fallback={<Plus className="text-subtle h-6 w-6" />}
asChild
className="items-center"
size="lg"
/>
<div className="ms-4">
<ImageUploader
target="avatar"
id="avatar-upload"
buttonMsg={t("upload")}
handleAvatarChange={(newAvatar: string) => {
setImage(newAvatar);
aboutOrganizationFormMethods.setValue("logo", newAvatar);
}}
imageSrc={image}
/>
</div>
</div>
</>
)}
/>
</div>
<div>
<Controller
control={aboutOrganizationFormMethods.control}
name="bio"
render={({ field: { value } }) => (
<>
<TextAreaField
name="about"
defaultValue={value}
onChange={(e) => {
aboutOrganizationFormMethods.setValue("bio", e?.target.value);
}}
/>
<p className="text-subtle text-sm">{t("organization_about_description")}</p>
</>
)}
/>
</div>
<div className="flex">
<Button
disabled={
aboutOrganizationFormMethods.formState.isSubmitting || updateOrganizationMutation.isLoading
}
color="primary"
EndIcon={ArrowRight}
type="submit"
className="w-full justify-center">
{t("continue")}
</Button>
</div>
</Form>
</>
);
};
@@ -0,0 +1,99 @@
import { ArrowRight } from "lucide-react";
import { useRouter } from "next/router";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { MembershipRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { Button, showToast, TextAreaField, Form } from "@calcom/ui";
const querySchema = z.object({
id: z.string().transform((val) => parseInt(val)),
});
export const AddNewOrgAdminsForm = () => {
const { t, i18n } = useLocale();
const router = useRouter();
const { id: orgId } = querySchema.parse(router.query);
const newAdminsFormMethods = useForm<{
emails: string[];
}>();
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation({
async onSuccess(data) {
if (data.sendEmailInvitation) {
if (Array.isArray(data.usernameOrEmail)) {
showToast(
t("email_invite_team_bulk", {
userCount: data.usernameOrEmail.length,
}),
"success"
);
} else {
showToast(
t("email_invite_team", {
email: data.usernameOrEmail,
}),
"success"
);
}
}
router.push(`/settings/organizations/${orgId}/add-teams`);
},
onError: (error) => {
showToast(error.message, "error");
},
});
return (
<Form
form={newAdminsFormMethods}
handleSubmit={(values) => {
inviteMemberMutation.mutate({
teamId: orgId,
language: i18n.language,
role: MembershipRole.ADMIN,
usernameOrEmail: values.emails,
sendEmailInvitation: true,
isOrg: true,
});
}}>
<div className="flex flex-col rounded-md">
<Controller
name="emails"
control={newAdminsFormMethods.control}
rules={{
required: t("enter_email_or_username"),
}}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<>
<TextAreaField
name="emails"
label="Invite via email"
rows={4}
autoCorrect="off"
placeholder="[email protected], [email protected]"
required
value={value}
onChange={(e) => {
const emails = e.target.value.split(",").map((email) => email.trim().toLocaleLowerCase());
return onChange(emails);
}}
/>
{error && <span className="text-sm text-red-800">{error.message}</span>}
</>
)}
/>
<Button
EndIcon={ArrowRight}
color="primary"
type="submit"
className="mt-6 w-full justify-center"
disabled={inviteMemberMutation.isLoading}>
Continue
</Button>
</div>
</Form>
);
};
@@ -0,0 +1,107 @@
import { ArrowRight } from "lucide-react";
import { useRouter } from "next/router";
import { useState } from "react";
import { z } from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button, showToast, TextField } from "@calcom/ui";
import { Plus, X } from "@calcom/ui/components/icon";
const querySchema = z.object({
id: z.string().transform((val) => parseInt(val)),
});
export const AddNewTeamsForm = () => {
const { t } = useLocale();
const router = useRouter();
const { id: orgId } = querySchema.parse(router.query);
const [counter, setCounter] = useState(1);
const [inputValues, setInputValues] = useState<string[]>([""]);
const handleCounterIncrease = () => {
setCounter((prevCounter) => prevCounter + 1);
setInputValues((prevInputValues) => [...prevInputValues, ""]);
};
const handleInputChange = (index: number, value: string) => {
const newInputValues = [...inputValues];
newInputValues[index] = value;
setInputValues(newInputValues);
};
const handleRemoveInput = (index: number) => {
const newInputValues = [...inputValues];
newInputValues.splice(index, 1);
setInputValues(newInputValues);
setCounter((prevCounter) => prevCounter - 1);
};
const createTeamsMutation = trpc.viewer.organizations.createTeams.useMutation({
async onSuccess(data) {
if (data.duplicatedSlugs.length) {
showToast(t("duplicated_slugs_warning", { slugs: data.duplicatedSlugs.join(", ") }), "warning");
setTimeout(() => {
router.push(`/event-types`);
}, 3000);
} else {
router.push(`/event-types`);
}
},
onError: (error) => {
showToast(error.message, "error");
},
});
return (
<>
{Array.from({ length: counter }, (_, index) => (
<div className="relative" key={index}>
<TextField
key={index}
value={inputValues[index]}
onChange={(e) => handleInputChange(index, e.target.value)}
addOnClassname="bg-transparent p-0 border-l-0"
addOnSuffix={
index > 0 && (
<Button
color="minimal"
className="group/remove mx-2 px-0 hover:bg-transparent"
onClick={() => handleRemoveInput(index)}>
<X className="bg-subtle text group-hover/remove:text-inverted group-hover/remove:bg-inverted h-5 w-5 rounded-full p-1" />
</Button>
)
}
/>
</div>
))}
<Button
StartIcon={Plus}
color="secondary"
disabled={createTeamsMutation.isLoading}
onClick={handleCounterIncrease}>
{t("add_a_team")}
</Button>
<Button
EndIcon={ArrowRight}
color="primary"
className="mt-6 w-full justify-center"
disabled={createTeamsMutation.isLoading}
onClick={() => {
if (inputValues.includes("")) {
showToast(t("team_name_empty"), "error");
} else {
const duplicates = inputValues.filter((item, index) => inputValues.indexOf(item) !== index);
if (duplicates.length) {
showToast("team_names_repeated", "error");
} else {
createTeamsMutation.mutate({ orgId, teamNames: inputValues });
}
}
}}>
{t("continue")}
</Button>
</>
);
};
@@ -0,0 +1,318 @@
import { signIn } from "next-auth/react";
import { useRouter } from "next/router";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import useDigitInput from "react-digit-input";
import { Controller, useForm } from "react-hook-form";
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import slugify from "@calcom/lib/slugify";
import { telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";
import { trpc } from "@calcom/trpc/react";
import {
Button,
Form,
TextField,
Alert,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
Label,
Input,
} from "@calcom/ui";
import { ArrowRight, Info } from "@calcom/ui/components/icon";
function extractDomainFromEmail(email: string) {
let out = "";
try {
const match = email.match(/^(?:.*?:\/\/)?.*?(?<root>[\w\-]*(?:\.\w{2,}|\.\w{2,}\.\w{2}))(?:[\/?#:]|$)/);
out = (match && match.groups?.root) ?? "";
} catch (ignore) {}
return out.split(".")[0];
}
export const VerifyCodeDialog = ({
isOpenDialog,
setIsOpenDialog,
email,
onSuccess,
}: {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
email: string;
onSuccess: (isVerified: boolean) => void;
}) => {
const { t } = useLocale();
// Not using the mutation isLoading flag because after verifying we submit the underlying org creation form
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const [value, onChange] = useState("");
const digits = useDigitInput({
acceptedCharacters: /^[0-9]$/,
length: 6,
value,
onChange,
});
const verifyCodeMutation = trpc.viewer.organizations.verifyCode.useMutation({
onSuccess: (data) => {
setIsLoading(false);
onSuccess(data);
},
onError: (err) => {
setIsLoading(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
}
},
});
const digitClassName = "h-12 w-12 !text-xl text-center";
return (
<Dialog
open={isOpenDialog}
onOpenChange={(open) => {
onChange("");
setError("");
setIsOpenDialog(open);
}}>
<DialogContent className="sm:max-w-md">
<div className="flex flex-row">
<div className="w-full">
<DialogHeader title={t("verify_your_email")} subtitle={t("enter_digit_code", { email })} />
<Label htmlFor="code">{t("code")}</Label>
<div className="flex flex-row justify-between">
<Input
className={digitClassName}
name="2fa1"
inputMode="decimal"
{...digits[0]}
autoFocus
autoComplete="one-time-code"
/>
<Input className={digitClassName} name="2fa2" inputMode="decimal" {...digits[1]} />
<Input className={digitClassName} name="2fa3" inputMode="decimal" {...digits[2]} />
<Input className={digitClassName} name="2fa4" inputMode="decimal" {...digits[3]} />
<Input className={digitClassName} name="2fa5" inputMode="decimal" {...digits[4]} />
<Input className={digitClassName} name="2fa6" inputMode="decimal" {...digits[5]} />
</div>
{error && (
<div className="mt-2 flex items-center gap-x-2 text-sm text-red-700">
<div>
<Info className="h-3 w-3" />
</div>
<p>{error}</p>
</div>
)}
<DialogFooter>
<DialogClose />
<Button
disabled={isLoading}
onClick={() => {
setError("");
if (value === "") {
setError("The code is a required field");
} else {
setIsLoading(true);
verifyCodeMutation.mutate({
code: value,
email,
});
}
}}>
{t("verify")}
</Button>
</DialogFooter>
</div>
</div>
</DialogContent>
</Dialog>
);
};
export const CreateANewOrganizationForm = () => {
const { t, i18n } = useLocale();
const router = useRouter();
const telemetry = useTelemetry();
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
const [showVerifyCode, setShowVerifyCode] = useState(false);
const newOrganizationFormMethods = useForm<{
name: string;
slug: string;
adminEmail: string;
adminUsername: string;
}>();
const watchAdminEmail = newOrganizationFormMethods.watch("adminEmail");
const createOrganizationMutation = trpc.viewer.organizations.create.useMutation({
onSuccess: async (data) => {
if (data.checked) {
setShowVerifyCode(true);
} else if (data.user) {
telemetry.event(telemetryEventTypes.org_created);
await signIn("credentials", {
redirect: false,
callbackUrl: "/",
email: data.user.email,
password: data.user.password,
});
router.push(`/settings/organizations/${data.user.organizationId}/set-password`);
}
},
onError: (err) => {
if (err.message === "admin_email_taken") {
newOrganizationFormMethods.setError("adminEmail", {
type: "custom",
message: t("email_already_used"),
});
} else if (err.message === "organization_url_taken") {
newOrganizationFormMethods.setError("slug", { type: "custom", message: t("organization_url_taken") });
} else {
setServerErrorMessage(err.message);
}
},
});
return (
<>
<Form
form={newOrganizationFormMethods}
id="createOrg"
handleSubmit={(v) => {
if (!createOrganizationMutation.isLoading) {
setServerErrorMessage(null);
createOrganizationMutation.mutate(v);
}
}}>
<div className="mb-5">
{serverErrorMessage && (
<div className="mb-4">
<Alert severity="error" message={serverErrorMessage} />
</div>
)}
<Controller
name="adminEmail"
control={newOrganizationFormMethods.control}
defaultValue=""
rules={{
required: t("must_enter_organization_admin_email"),
}}
render={({ field: { value } }) => (
<div className="flex">
<TextField
containerClassName="w-full"
placeholder="[email protected]"
name="adminEmail"
label={t("admin_email")}
defaultValue={value}
onChange={(e) => {
const domain = extractDomainFromEmail(e?.target.value);
newOrganizationFormMethods.setValue("adminEmail", e?.target.value);
newOrganizationFormMethods.setValue("adminUsername", e?.target.value.split("@")[0]);
newOrganizationFormMethods.setValue("slug", domain);
newOrganizationFormMethods.setValue(
"name",
domain.charAt(0).toUpperCase() + domain.slice(1)
);
}}
autoComplete="off"
/>
</div>
)}
/>
</div>
<div className="mb-5">
<Controller
name="name"
control={newOrganizationFormMethods.control}
defaultValue=""
rules={{
required: t("must_enter_organization_name"),
}}
render={({ field: { value } }) => (
<>
<TextField
className="mt-2"
placeholder="Acme"
name="name"
label={t("organization_name")}
defaultValue={value}
onChange={(e) => {
newOrganizationFormMethods.setValue("name", e?.target.value);
if (newOrganizationFormMethods.formState.touchedFields["slug"] === undefined) {
newOrganizationFormMethods.setValue("slug", slugify(e?.target.value));
}
}}
autoComplete="off"
/>
</>
)}
/>
</div>
<div className="mb-5">
<Controller
name="slug"
control={newOrganizationFormMethods.control}
rules={{
required: "Must enter organization slug",
}}
render={({ field: { value } }) => (
<TextField
className="mt-2"
name="slug"
label={t("organization_url")}
placeholder="acme"
addOnSuffix={`.${subdomainSuffix()}`}
defaultValue={value}
onChange={(e) => {
newOrganizationFormMethods.setValue("slug", slugify(e?.target.value), {
shouldTouch: true,
});
newOrganizationFormMethods.clearErrors("slug");
}}
/>
)}
/>
</div>
<input hidden {...newOrganizationFormMethods.register("adminUsername")} />
<div className="flex space-x-2 rtl:space-x-reverse">
<Button
disabled={
newOrganizationFormMethods.formState.isSubmitting || createOrganizationMutation.isLoading
}
color="primary"
EndIcon={ArrowRight}
type="submit"
form="createOrg"
className="w-full justify-center">
{t("continue")}
</Button>
</div>
</Form>
<VerifyCodeDialog
isOpenDialog={showVerifyCode}
setIsOpenDialog={setShowVerifyCode}
email={watchAdminEmail}
onSuccess={(isVerified) => {
if (isVerified) {
createOrganizationMutation.mutate({
...newOrganizationFormMethods.getValues(),
language: i18n.language,
check: false,
});
}
}}
/>
</>
);
};
@@ -0,0 +1,109 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/router";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { isPasswordValid } from "@calcom/features/auth/lib/isPasswordValid";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button, Form, Alert, PasswordField } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";
const querySchema = z.object({
id: z.string(),
});
const formSchema = z.object({
password: z.string().superRefine((data, ctx) => {
const isStrict = true;
const result = isPasswordValid(data, true, isStrict);
Object.keys(result).map((key: string) => {
if (!result[key as keyof typeof result]) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [key],
message: key,
});
}
});
}),
});
export const SetPasswordForm = () => {
const { t } = useLocale();
const router = useRouter();
const { id: orgId } = querySchema.parse(router.query);
const [serverErrorMessage, setServerErrorMessage] = useState<string | null>(null);
const setPasswordFormMethods = useForm<{
password: string;
}>({
resolver: zodResolver(formSchema),
});
const setPasswordMutation = trpc.viewer.organizations.setPassword.useMutation({
onSuccess: (data) => {
if (data.update) {
router.push(`/settings/organizations/${orgId}/about`);
}
},
onError: (err) => {
setServerErrorMessage(err.message);
},
});
return (
<>
<Form
form={setPasswordFormMethods}
handleSubmit={(v) => {
if (!setPasswordMutation.isLoading) {
setServerErrorMessage(null);
setPasswordMutation.mutate({ newPassword: v.password });
}
}}>
<div>
{serverErrorMessage && (
<div className="mb-4">
<Alert severity="error" message={serverErrorMessage} />
</div>
)}
</div>
<div className="mb-5">
<Controller
name="password"
control={setPasswordFormMethods.control}
render={({ field: { onBlur, onChange, value } }) => (
<PasswordField
value={value || ""}
onBlur={onBlur}
onChange={async (e) => {
onChange(e.target.value);
setPasswordFormMethods.setValue("password", e.target.value);
await setPasswordFormMethods.trigger("password");
}}
hintErrors={["caplow", "admin_min", "num"]}
name="password"
autoComplete="off"
/>
)}
/>
</div>
<div className="flex">
<Button
disabled={setPasswordFormMethods.formState.isSubmitting || setPasswordMutation.isLoading}
color="primary"
EndIcon={ArrowRight}
type="submit"
className="w-full justify-center">
{t("continue")}
</Button>
</div>
</Form>
</>
);
};
@@ -0,0 +1,5 @@
export { CreateANewOrganizationForm } from "./CreateANewOrganizationForm";
export { AboutOrganizationForm } from "./AboutOrganizationForm";
export { SetPasswordForm } from "./SetPasswordForm";
export { AddNewOrgAdminsForm } from "./AddNewOrgAdminsForm";
export { AddNewTeamsForm } from "./AddNewTeamsForm";
@@ -0,0 +1,66 @@
import { createContext, useContext, createElement } from "react";
import type z from "zod";
import type { teamMetadataSchema } from "@calcom/prisma/zod-utils";
/**
* Organization branding
*
* Entries consist of the different properties that constitues a brand for an organization.
*/
export type OrganizationBranding =
| ({
logo?: string | null | undefined;
name?: string;
slug?: string;
} & z.infer<typeof teamMetadataSchema>)
| null
| undefined;
/**
* Allows you to access the flags from context
*/
const OrganizationBrandingContext = createContext<OrganizationBranding | null>(null);
/**
* Accesses the branding for an organization from context.
*
* You need to render a <OrgBrandingProvider /> further up to be able to use
* this component.
*/
export function useOrgBranding() {
const orgBrandingContext = useContext(OrganizationBrandingContext);
if (orgBrandingContext === null)
throw new Error("Error: useOrganizationBranding was used outside of OrgBrandingProvider.");
return orgBrandingContext as OrganizationBranding;
}
/**
* If you want to be able to access the flags from context using `useOrganizationBranding()`,
* you can render the OrgBrandingProvider at the top of your Next.js pages, like so:
*
* ```ts
* import { useOrgBrandingValues } from "@calcom/features/flags/hooks/useFlag"
* import { OrgBrandingProvider, useOrgBranding } from @calcom/features/flags/context/provider"
*
* export default function YourPage () {
* const orgBrand = useOrgBrandingValues()
*
* return (
* <OrgBrandingProvider value={orgBrand}>
* <YourOwnComponent />
* </OrgBrandingProvider>
* )
* }
* ```
*
* You can then call `useOrgBrandingValues()` to access your `OrgBranding` from within
* `YourOwnComponent` or further down.
*
*/
export function OrgBrandingProvider<F extends OrganizationBranding>(props: {
value: F;
children: React.ReactNode;
}) {
return createElement(OrganizationBrandingContext.Provider, { value: props.value }, props.children);
}
@@ -0,0 +1,5 @@
import { trpc } from "@calcom/trpc/react";
export function useOrgBrandingValues() {
return trpc.viewer.organizations.getBrand.useQuery().data;
}
@@ -0,0 +1,45 @@
import { WEBAPP_URL } from "@calcom/lib/constants";
// Define which hostnames are expected for the app
export const appHostnames = [
"cal.com",
"cal.dev",
"cal-staging.com",
"cal.community",
"cal.local:3000",
// ⬇️ Prevents 404 error for normal localhost development, makes it backwards compatible
"localhost:3000",
];
/**
* return the org slug
* @param hostname
*/
export function getOrgDomain(hostname: string) {
// Find which hostname is being currently used
const currentHostname = appHostnames.find((ahn) => {
const url = new URL(WEBAPP_URL);
const testHostname = `${url.hostname}${url.port ? `:${url.port}` : ""}`;
return testHostname.endsWith(`.${ahn}`);
});
if (currentHostname) {
// Define which is the current domain/subdomain
const slug = hostname.replace(`.${currentHostname}` ?? "", "");
return slug.indexOf(".") === -1 ? slug : null;
}
return null;
}
export function orgDomainConfig(hostname: string) {
const currentOrgDomain = getOrgDomain(hostname);
return {
currentOrgDomain,
isValidOrgDomain:
currentOrgDomain !== null && currentOrgDomain !== "app" && !appHostnames.includes(currentOrgDomain),
};
}
export function subdomainSuffix() {
const urlSplit = WEBAPP_URL.replace("https://", "")?.replace("http://", "").split(".");
return urlSplit.length === 3 ? urlSplit.slice(1).join(".") : urlSplit.join(".");
}
@@ -0,0 +1,6 @@
export interface NewOrganizationFormValues {
name: string;
slug: string;
logo: string;
adminEmail: string;
}
@@ -6,6 +6,8 @@ import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useOrgBrandingValues } from "@calcom/features/ee/organizations/hooks";
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
import { useFlagMap } from "@calcom/features/flags/context/provider";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -81,6 +83,7 @@ export default function CreateEventTypeDialog({
const { t } = useLocale();
const router = useRouter();
const [firstRender, setFirstRender] = useState(true);
const orgBranding = useOrgBrandingValues();
const {
data: { teamId, eventPage: pageSlug },
@@ -136,6 +139,9 @@ export default function CreateEventTypeDialog({
});
const flags = useFlagMap();
const urlPrefix = orgBranding
? `${orgBranding.slug}.${subdomainSuffix()}`
: process.env.NEXT_PUBLIC_WEBSITE_URL;
return (
<Dialog
@@ -181,11 +187,10 @@ export default function CreateEventTypeDialog({
}}
/>
{process.env.NEXT_PUBLIC_WEBSITE_URL !== undefined &&
process.env.NEXT_PUBLIC_WEBSITE_URL?.length >= 21 ? (
{urlPrefix && urlPrefix.length >= 21 ? (
<div>
<TextField
label={`${t("url")}: ${process.env.NEXT_PUBLIC_WEBSITE_URL}`}
label={`${t("url")}: ${urlPrefix}`}
required
addOnLeading={<>/{!isManagedEventType ? pageSlug : t("username_placeholder")}/</>}
{...register("slug")}
@@ -205,8 +210,7 @@ export default function CreateEventTypeDialog({
required
addOnLeading={
<>
{process.env.NEXT_PUBLIC_WEBSITE_URL}/
{!isManagedEventType ? pageSlug : t("username_placeholder")}/
{urlPrefix}/{!isManagedEventType ? pageSlug : t("username_placeholder")}/
</>
}
{...register("slug")}
@@ -0,0 +1,118 @@
import { useSession } from "next-auth/react";
import type { ReactNode, InputHTMLAttributes } from "react";
import { useState, forwardRef, Fragment } from "react";
import { useFilterQuery } from "@calcom/features/bookings/lib/useFilterQuery";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { AnimatedPopover, Avatar } from "@calcom/ui";
import { Layers, User } from "@calcom/ui/components/icon";
export type IEventTypesFilters = RouterOutputs["viewer"]["eventTypes"]["listWithTeam"];
export type IEventTypeFilter = IEventTypesFilters[0];
export const OrganizationEventTypeFilter = () => {
const { t } = useLocale();
const session = useSession();
const { data: query, pushItemToKey, removeItemByKeyAndValue, removeAllQueryParams } = useFilterQuery();
const [dropdownTitle, setDropdownTitle] = useState<string>(t("all_apps"));
const { data: teams, status } = trpc.viewer.teams.list.useQuery();
const isNotEmpty = !!teams?.length;
return status === "success" ? (
<AnimatedPopover text={dropdownTitle} popoverTriggerClassNames="!mb-0">
<CheckboxFieldContainer>
<CheckboxField
id="all-eventtypes-checkbox"
icon={<Layers className="h-4 w-4" />}
checked={dropdownTitle === t("all_apps")}
onChange={(e) => {
removeAllQueryParams();
setDropdownTitle(t("all_apps"));
// TODO: What to do when all event types is unchecked
}}
label={t("all_apps")}
/>
</CheckboxFieldContainer>
<CheckboxFieldContainer>
<CheckboxField
id="all-eventtypes-checkbox"
icon={<User className="h-4 w-4" />}
checked={query.userIds?.includes(session.data?.user.id || 0)}
onChange={(e) => {
setDropdownTitle(t("yours"));
if (e.target.checked) {
pushItemToKey("userIds", session.data?.user.id || 0);
} else if (!e.target.checked) {
removeItemByKeyAndValue("userIds", session.data?.user.id || 0);
}
}}
label={t("yours")}
/>
</CheckboxFieldContainer>
{isNotEmpty && (
<Fragment>
<div className="text-subtle px-4 py-2.5 text-xs font-medium uppercase leading-none">TEAMS</div>
{teams?.map((team) => (
<CheckboxFieldContainer key={team.id}>
<CheckboxField
id={team.name}
label={team.name}
icon={
<Avatar
alt={team?.name}
imageSrc={getPlaceholderAvatar(team.logo, team?.name as string)}
size="xs"
/>
}
checked={query.teamIds?.includes(team.id)}
onChange={(e) => {
setDropdownTitle(team.name);
if (e.target.checked) {
pushItemToKey("teamIds", team.id);
} else if (!e.target.checked) {
removeItemByKeyAndValue("teamIds", team.id);
}
}}
/>
</CheckboxFieldContainer>
))}
</Fragment>
)}
</AnimatedPopover>
) : null;
};
type Props = InputHTMLAttributes<HTMLInputElement> & {
label: string;
icon: ReactNode;
};
const CheckboxField = forwardRef<HTMLInputElement, Props>(({ label, icon, ...rest }, ref) => {
return (
<label className="flex w-full items-center justify-between">
<div className="flex items-center">
<div className="text-default flex h-6 w-6 items-center justify-center ltr:mr-2 rtl:ml-2">{icon}</div>
<span className="text-sm">{label}</span>
</div>
<div className="flex h-5 items-center">
<input
{...rest}
ref={ref}
type="checkbox"
className="text-primary-600 focus:ring-primary-500 border-default bg-default h-4 w-4 rounded hover:cursor-pointer"
/>
</div>
</label>
);
});
const CheckboxFieldContainer = ({ children }: { children: ReactNode }) => {
return <div className="flex items-center px-3 py-2">{children}</div>;
};
CheckboxField.displayName = "CheckboxField";
+1
View File
@@ -9,6 +9,7 @@ export type AppFlags = {
webhooks: boolean;
workflows: boolean;
"managed-event-types": boolean;
organizations: boolean;
"email-verification": boolean;
"booker-layouts": boolean;
"google-workspace-directory": boolean;
+3 -1
View File
@@ -2,7 +2,9 @@ import { trpc } from "@calcom/trpc/react";
export function useFlags() {
const query = trpc.viewer.features.map.useQuery(undefined, {
initialData: process.env.NEXT_PUBLIC_IS_E2E ? { "managed-event-types": true, teams: true } : {},
initialData: process.env.NEXT_PUBLIC_IS_E2E
? { "managed-event-types": true, organizations: true, teams: true }
: {},
});
return query.data;
}
+26 -5
View File
@@ -12,6 +12,7 @@ import dayjs from "@calcom/dayjs";
import { useIsEmbed } from "@calcom/embed-core/embed-iframe";
import UnconfirmedBookingBadge from "@calcom/features/bookings/UnconfirmedBookingBadge";
import ImpersonatingBanner from "@calcom/features/ee/impersonation/components/ImpersonatingBanner";
import { useOrgBrandingValues } from "@calcom/features/ee/organizations/hooks";
import HelpMenuItem from "@calcom/features/ee/support/components/HelpMenuItem";
import { TeamsUpgradeBanner } from "@calcom/features/ee/teams/components";
import { useFlagMap } from "@calcom/features/flags/context/provider";
@@ -31,6 +32,7 @@ import useEmailVerifyCheck from "@calcom/trpc/react/hooks/useEmailVerifyCheck";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import type { SVGComponent } from "@calcom/types/SVGComponent";
import {
Avatar,
Button,
Credits,
Dropdown,
@@ -90,8 +92,14 @@ export const ONBOARDING_NEXT_REDIRECT = {
},
} as const;
export const shouldShowOnboarding = (user: Pick<User, "createdDate" | "completedOnboarding">) => {
return !user.completedOnboarding && dayjs(user.createdDate).isAfter(ONBOARDING_INTRODUCED_AT);
export const shouldShowOnboarding = (
user: Pick<User, "createdDate" | "completedOnboarding" | "organizationId">
) => {
return (
!user.completedOnboarding &&
!user.organizationId &&
dayjs(user.createdDate).isAfter(ONBOARDING_INTRODUCED_AT)
);
};
function useRedirectToLoginIfUnauthenticated(isPublic = false) {
@@ -228,6 +236,8 @@ type LayoutProps = {
withoutSeo?: boolean;
// Gives the ability to include actions to the right of the heading
actions?: JSX.Element;
beforeCTAactions?: JSX.Element;
afterHeading?: ReactNode;
smallHeading?: boolean;
hideHeadingOnMobile?: boolean;
};
@@ -281,6 +291,7 @@ function UserDropdown({ small }: { small?: boolean }) {
const { t } = useLocale();
const { data: user } = useMeQuery();
const { data: avatar } = useAvatarQuery();
const orgBranding = useOrgBrandingValues();
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@@ -348,8 +359,8 @@ function UserDropdown({ small }: { small?: boolean }) {
<span className="text-default truncate pb-1 font-normal">
{user.username
? process.env.NEXT_PUBLIC_WEBSITE_URL === "https://cal.com"
? `cal.com/${user.username}`
: `/${user.username}`
? `${orgBranding && orgBranding.slug}cal.com/${user.username}`
: `${orgBranding && orgBranding.slug}/${user.username}`
: "No public page"}
</span>
</span>
@@ -789,6 +800,7 @@ function SideBarContainer({ bannersHeight }: SideBarContainerProps) {
}
function SideBar({ bannersHeight }: SideBarProps) {
const orgBranding = useOrgBrandingValues();
return (
<div className="relative">
<aside
@@ -797,7 +809,14 @@ function SideBar({ bannersHeight }: SideBarProps) {
<div className="flex h-full flex-col justify-between py-3 lg:pt-6 ">
<header className="items-center justify-between md:hidden lg:flex">
<Link href="/event-types" className="px-2">
<Logo small />
{orgBranding ? (
<div className="flex items-center gap-2 font-medium">
{orgBranding.logo && <Avatar alt="" imageSrc={orgBranding.logo} size="sm" />}
<p className="text text-sm">{orgBranding.name}</p>
</div>
) : (
<Logo small />
)}
</Link>
<div className="flex space-x-2 rtl:space-x-reverse">
<button
@@ -889,6 +908,7 @@ export function ShellMain(props: LayoutProps) {
</p>
)}
</div>
{props.beforeCTAactions}
{props.CTA && (
<div
className={classNames(
@@ -904,6 +924,7 @@ export function ShellMain(props: LayoutProps) {
</header>
)}
</div>
{props.afterHeading && <>{props.afterHeading}</>}
<div className={classNames(props.flexChildrenContainer && "flex flex-1 flex-col")}>
{props.children}
</div>
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { orgDomainConfig, getOrgDomain } from "@calcom/features/ee/organizations/lib/orgDomains";
import * as constants from "@calcom/lib/constants";
describe("Org Domains Utils", () => {
describe("orgDomainConfig", () => {
it("should return a valid org domain", () => {
Object.defineProperty(constants, 'WEBAPP_URL', {value:"https://app.cal.com"});
expect(orgDomainConfig("acme.cal.com")).toEqual({
currentOrgDomain: "acme",
isValidOrgDomain: true
});
});
it("should return a non valid org domain", () => {
Object.defineProperty(constants, 'WEBAPP_URL', {value:"https://app.cal.com"});
expect(orgDomainConfig("app.cal.com")).toEqual({
currentOrgDomain: "app",
isValidOrgDomain: false
});
});
});
describe("getOrgDomain", () => {
it("should handle a prod web app url with a prod subdomain hostname", () => {
Object.defineProperty(constants, 'WEBAPP_URL', {value:"https://app.cal.com"});
expect(getOrgDomain("acme.cal.com")).toEqual("acme");
});
it("should handle a prod web app url with a staging subdomain hostname", () => {
Object.defineProperty(constants, 'WEBAPP_URL', {value:"https://app.cal.com"});
expect(getOrgDomain("acme.cal.dev")).toEqual(null);
});
it("should handle a local web app with port url with a local subdomain hostname", () => {
Object.defineProperty(constants, 'WEBAPP_URL', {value:"http://app.cal.local:3000"});
expect(getOrgDomain("acme.cal.local:3000")).toEqual("acme");
});
it("should handle a local web app with port url with a non-local subdomain hostname", () => {
Object.defineProperty(constants, 'WEBAPP_URL', {value:"http://app.cal.local:3000"});
expect(getOrgDomain("acme.cal.com:3000")).toEqual(null);
});
})
});