Managed event-types (#6876)

* WIP

* Locked fields manager

* Leftovers

* Bad merge fix

* Type import fix

* Moving away from classes

* Progress refactoring locked logic

* Covering apps, webhooks and workflows

* Supporting webhooks and workflows (TBT)

* Restoring yarn.lock

* Progress

* Refactoring code, adding default values

* Fixing CRUD for children

* Connect app link and case-sensitive lib renaming

* Translation missing

* Locked indicators, empty screens, locations

* Member card and hidden status + missing i18n

* Missing existent children shown

* Showing preview for already created children

* Email notification almost in place

* Making progress over notif email

* Fixing nodemailer by mixed FE/BE mixup

* Delete dialog

* Adding tests

* New test

* Reverting unneeded change

* Removed console.log

* Tweaking email

* Reverting not applicable webhook changes

* Reverting dev email api

* Fixing last changes due to tests

* Changing user-evType relationship

* Availability and slug replacement tweaks

* Fixing event type delete

* Sometimes slug is not there...

* Removing old webhooks references
Changed slug hint

* Fixing types

* Fixing hiding event types actions

* Changing delete dialog text

* Removing unneeded code

* Applying feedback

* Update yarn.lock

* Making sure locked fields values are static

* Applying feedback

* Feedback + relying on children list, not users

* Removing console.log

* PR Feedback

* Telemetry for slug replacement action

* More unit tests

* Relying on schedule and editor tweaks

* Fixing conteiner classname

* PR Feedback

* PR Feedback

* Updating unit tests

* Moving stuff to ee, added feature flag

* type fix

* Including e2e

* Reverting unneeded changes in EmptyScreen

* Fixing some UI issues after merging tokens

* Fixing missing disabled locked fields

* Theme fixes + e2e potential fix

* Fixing e2e

* Fixing login relying on network

* Tweaking e2e

* Removing unneeded code

---------

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: zomars <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-04-12 23:10:23 -03:00
1 parent 7349fb9f6d
commit 5170fc2424
66 files changed
+2798 -655

No files matched your search

@@ -0,0 +1,58 @@
import { SchedulingType } from "@prisma/client";
import { get } from "lodash";
import React from "react";
import type z from "zod";
import type { Prisma } from "@calcom/prisma/client";
import type { _EventTypeModel } from "@calcom/prisma/zod/eventtype";
import { Tooltip } from "@calcom/ui";
import { Lock } from "@calcom/ui/components/icon";
const Indicator = (label: string) => (
<Tooltip content={<>{label}</>}>
<div className="bg ml-1 -mt-0.5 inline-flex h-4 w-4 rounded-sm p-0.5">
<Lock className="text-subtle hover:text-muted h-3 w-3" />
</div>
</Tooltip>
);
const useLockedFieldsManager = (
eventType: Pick<z.infer<typeof _EventTypeModel>, "schedulingType" | "userId" | "metadata">,
adminLabel: string,
memberLabel: string
) => {
const unlockedFields =
(eventType.metadata?.managedEventConfig?.unlockedFields !== undefined &&
eventType.metadata?.managedEventConfig?.unlockedFields) ||
{};
const isManagedEventType = eventType.schedulingType === SchedulingType.MANAGED;
const isChildrenManagedEventType =
eventType.metadata?.managedEventConfig !== undefined &&
eventType.schedulingType !== SchedulingType.MANAGED;
const shouldLockIndicator = (fieldName: string) => {
let locked = isManagedEventType || isChildrenManagedEventType;
// Supports "metadata.fieldName"
if (fieldName.includes(".")) {
locked = locked && get(unlockedFields, fieldName) === undefined;
} else {
locked = locked && unlockedFields[fieldName as keyof Omit<Prisma.EventTypeSelect, "id">] === undefined;
}
return locked && Indicator(isManagedEventType ? adminLabel : memberLabel);
};
const shouldLockDisableProps = (fieldName: string) => {
return {
disabled:
!isManagedEventType &&
eventType.metadata?.managedEventConfig !== undefined &&
unlockedFields[fieldName as keyof Omit<Prisma.EventTypeSelect, "id">] === undefined,
LockedIcon: shouldLockIndicator(fieldName),
};
};
return { shouldLockIndicator, shouldLockDisableProps, isManagedEventType, isChildrenManagedEventType };
};
export default useLockedFieldsManager;
@@ -0,0 +1,294 @@
import type { PrismaClient, Prisma } from "@prisma/client";
import { SchedulingType } from "@prisma/client";
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import { sendSlugReplacementEmail } from "@calcom/emails/email-manager";
import { getTranslation } from "@calcom/lib/server/i18n";
import { _EventTypeModel } from "@calcom/prisma/zod";
import { allManagedEventTypeProps, unlockedManagedEventTypeProps } from "@calcom/prisma/zod-utils";
const generateHashedLink = (id: number) => {
const translator = short();
const seed = `${id}:${new Date().getTime()}`;
const uid = translator.fromUUID(uuidv5(seed, uuidv5.URL));
return uid;
};
interface handleChildrenEventTypesProps {
eventTypeId: number;
updatedEventType: {
schedulingType: SchedulingType | null;
slug: string;
};
currentUserId: number;
oldEventType: {
children?: { userId: number | null }[] | null | undefined;
team: { name: string } | null;
} | null;
hashedLink: string | undefined;
connectedLink: { id: number } | null;
children:
| {
hidden: boolean;
owner: {
id: number;
name: string;
email: string;
eventTypeSlugs: string[];
};
}[]
| undefined;
prisma: PrismaClient<
Prisma.PrismaClientOptions,
never,
Prisma.RejectOnNotFound | Prisma.RejectPerOperation | undefined
>;
}
const sendAllSlugReplacementEmails = async (
persons: { email: string; name: string }[],
slug: string,
teamName: string | null
) => {
const t = await getTranslation("en", "common");
persons.map(
async (person) =>
await sendSlugReplacementEmail({ email: person.email, name: person.name, teamName, slug, t })
);
};
const checkExistentEventTypes = async ({
updatedEventType,
children,
prisma,
userIds,
teamName,
}: Pick<handleChildrenEventTypesProps, "updatedEventType" | "children" | "prisma"> & {
userIds: number[];
teamName: string | null;
}) => {
const replaceEventType = children?.filter(
(ch) => ch.owner.eventTypeSlugs.includes(updatedEventType.slug) && userIds.includes(ch.owner.id)
);
// If so, delete their event type with the same slug to proceed to create a managed one
if (replaceEventType?.length) {
const deletedReplacedEventTypes = await prisma.eventType.deleteMany({
where: {
slug: updatedEventType.slug,
userId: {
in: replaceEventType.map((evTy) => evTy.owner.id),
},
},
});
// Sending notification after deleting
await sendAllSlugReplacementEmails(
replaceEventType.map((evTy) => evTy.owner),
updatedEventType.slug,
teamName
);
return deletedReplacedEventTypes;
}
};
export default async function handleChildrenEventTypes({
eventTypeId: parentId,
oldEventType,
updatedEventType,
hashedLink,
connectedLink,
children,
prisma,
}: handleChildrenEventTypesProps) {
// Check we are dealing with a managed event type
if (updatedEventType?.schedulingType !== SchedulingType.MANAGED)
return {
message: "No managed event type",
};
// Retrieving the updated event type
const eventType = await prisma.eventType.findFirst({
where: { id: parentId },
select: allManagedEventTypeProps,
});
// Shortcircuit when no data for old and updated event types
if (!oldEventType || !eventType)
return {
message: "Missing event type",
};
// Define what values are expected to be changed from a managed event type
const allManagedEventTypePropsZod = _EventTypeModel.pick(allManagedEventTypeProps);
const managedEventTypeValues = allManagedEventTypePropsZod
.omit(unlockedManagedEventTypeProps)
.parse(eventType);
// Check we are certainly dealing with a managed event type through its metadata
if (!managedEventTypeValues.metadata?.managedEventConfig)
return {
message: "No managed event metadata",
};
// Define the values for unlocked properties to use on creation, not updation
const unlockedEventTypeValues = allManagedEventTypePropsZod
.pick(unlockedManagedEventTypeProps)
.parse(eventType);
// Calculate if there are new/existent/deleted children users for which the event type needs to be created/updated/deleted
const previousUserIds = oldEventType.children?.flatMap((ch) => ch.userId ?? []);
const currentUserIds = children?.map((ch) => ch.owner.id);
const deletedUserIds = previousUserIds?.filter((id) => !currentUserIds?.includes(id));
const newUserIds = currentUserIds?.filter((id) => !previousUserIds?.includes(id));
const oldUserIds = currentUserIds?.filter((id) => previousUserIds?.includes(id));
// Define hashedLink query input
const hashedLinkQuery = (userId: number) => {
return hashedLink
? !connectedLink
? { create: { link: generateHashedLink(userId) } }
: undefined
: connectedLink
? { delete: true }
: undefined;
};
// Store result for existent event types deletion process
let deletedExistentEventTypes = undefined;
// New users added
if (newUserIds?.length) {
// Check if there are children with existent homonym event types to send notifications
deletedExistentEventTypes = await checkExistentEventTypes({
updatedEventType,
children,
prisma,
userIds: newUserIds,
teamName: oldEventType.team?.name ?? null,
});
// Create event types for new users added
await prisma.$transaction(
newUserIds.map((userId) => {
return prisma.eventType.create({
data: {
...managedEventTypeValues,
...unlockedEventTypeValues,
bookingLimits:
(managedEventTypeValues.bookingLimits as unknown as Prisma.InputJsonObject) ?? undefined,
recurringEvent:
(managedEventTypeValues.recurringEvent as unknown as Prisma.InputJsonValue) ?? undefined,
metadata: (managedEventTypeValues.metadata as Prisma.InputJsonValue) ?? undefined,
bookingFields: (managedEventTypeValues.bookingFields as Prisma.InputJsonValue) ?? undefined,
durationLimits: (managedEventTypeValues.durationLimits as Prisma.InputJsonValue) ?? undefined,
userId,
users: {
connect: [{ id: userId }],
},
parentId,
hidden: children?.find((ch) => ch.owner.id === userId)?.hidden ?? false,
// Reserved for v2
/*
workflows: eventType.workflows && {
createMany: {
data: eventType.workflows?.map((wf) => ({ ...wf, eventTypeId: undefined })),
},
},
webhooks: eventType.webhooks && {
createMany: {
data: eventType.webhooks?.map((wh) => ({ ...wh, eventTypeId: undefined })),
},
},*/
hashedLink: hashedLinkQuery(userId),
},
});
})
);
}
// Old users updated
if (oldUserIds?.length) {
// Check if there are children with existent homonym event types to send notifications
deletedExistentEventTypes = await checkExistentEventTypes({
updatedEventType,
children,
prisma,
userIds: oldUserIds,
teamName: oldEventType.team?.name || null,
});
// Update event types for old users
await prisma.$transaction(
oldUserIds.map((userId) => {
return prisma.eventType.update({
where: {
userId_parentId: {
userId,
parentId,
},
},
data: {
...managedEventTypeValues,
hidden: children?.find((ch) => ch.owner.id === userId)?.hidden ?? false,
bookingLimits:
(managedEventTypeValues.bookingLimits as unknown as Prisma.InputJsonObject) ?? undefined,
recurringEvent:
(managedEventTypeValues.recurringEvent as unknown as Prisma.InputJsonValue) ?? undefined,
metadata: (managedEventTypeValues.metadata as Prisma.InputJsonValue) ?? undefined,
bookingFields: (managedEventTypeValues.bookingFields as Prisma.InputJsonValue) ?? undefined,
durationLimits: (managedEventTypeValues.durationLimits as Prisma.InputJsonValue) ?? undefined,
hashedLink: hashedLinkQuery(userId),
},
});
})
);
// Reserved for v2
/*const updatedOldWorkflows = await prisma.workflow.updateMany({
where: {
userId: {
in: oldUserIds,
},
},
data: {
...eventType.workflows,
},
});
console.log(
"handleChildrenEventTypes:updatedOldWorkflows",
JSON.stringify({ updatedOldWorkflows }, null, 2)
);
const updatedOldWebhooks = await prisma.webhook.updateMany({
where: {
userId: {
in: oldUserIds,
},
},
data: {
...eventType.webhooks,
},
});
console.log(
"handleChildrenEventTypes:updatedOldWebhooks",
JSON.stringify({ updatedOldWebhooks }, null, 2)
);*/
}
// Old users deleted
if (deletedUserIds?.length) {
// Delete event types for deleted users
await prisma.eventType.deleteMany({
where: {
userId: {
in: deletedUserIds,
},
parentId,
},
});
}
return { newUserIds, oldUserIds, deletedUserIds, deletedExistentEventTypes };
}
@@ -141,6 +141,7 @@ const PendingMemberItem = (props: { member: TeamMember; index: number; teamId: n
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
async onSuccess() {
await utils.viewer.teams.get.invalidate();
await utils.viewer.eventTypes.invalidate();
showToast("Member removed", "success");
},
async onError(err) {
@@ -56,6 +56,7 @@ export default function MemberListItem(props: Props) {
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
async onSuccess() {
await utils.viewer.teams.get.invalidate();
await utils.viewer.eventTypes.invalidate();
showToast(t("success"), "success");
},
async onError(err) {
@@ -153,6 +153,7 @@ export default function TeamListItem(props: Props) {
<Button
type="button"
color="secondary"
data-testid={`accept-invitation-${team.id}`}
StartIcon={Check}
className="ms-2 me-2"
onClick={acceptInvite}>
@@ -106,6 +106,7 @@ const ProfileView = () => {
async onSuccess() {
await utils.viewer.teams.get.invalidate();
await utils.viewer.teams.list.invalidate();
await utils.viewer.eventTypes.invalidate();
showToast(t("success"), "success");
},
async onError(err) {
@@ -3,12 +3,14 @@ import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import useLockedFieldsManager from "@calcom/features/ee/managed-event-types/hooks/useLockedFieldsManager";
import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { HttpError } from "@calcom/lib/http-error";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Button, EmptyScreen, showToast, Switch, Tooltip } from "@calcom/ui";
import { ExternalLink, Zap } from "@calcom/ui/components/icon";
import { Button, EmptyScreen, showToast, Switch, Tooltip, Alert } from "@calcom/ui";
import { ExternalLink, Zap, Lock } from "@calcom/ui/components/icon";
import LicenseRequired from "../../common/components/v2/LicenseRequired";
import { getActionIcon } from "../lib/getActionIcon";
@@ -151,15 +153,10 @@ const WorkflowListItem = (props: ItemProps) => {
);
};
type EventTypeSetup = RouterOutputs["viewer"]["eventTypes"]["get"]["eventType"];
type Props = {
eventType: {
id: number;
title: string;
userId: number | null;
team: {
id?: number;
} | null;
};
eventType: EventTypeSetup;
workflows: WorkflowType[];
};
@@ -207,33 +204,58 @@ function EventWorkflowsTab(props: Props) {
},
});
const { isManagedEventType, isChildrenManagedEventType } = useLockedFieldsManager(
eventType,
t("locked_fields_admin_description"),
t("locked_fields_member_description")
);
return (
<LicenseRequired>
{!isLoading ? (
data?.workflows && data?.workflows.length > 0 ? (
<div className="space-y-4">
{sortedWorkflows.map((workflow) => {
return <WorkflowListItem key={workflow.id} workflow={workflow} eventType={props.eventType} />;
})}
</div>
) : (
<div className="pt-4 before:border-0">
<EmptyScreen
Icon={Zap}
headline={t("workflows")}
description={t("no_workflows_description")}
buttonRaw={
<Button
target="_blank"
color="secondary"
onClick={() => createMutation.mutate({ teamId: eventType.team?.id })}
loading={createMutation.isLoading}>
{t("create_workflow")}
</Button>
}
<>
{isManagedEventType && (
<Alert
severity="neutral"
title={t("locked_for_members")}
message={t("locked_workflows_description")}
/>
</div>
)
)}
{data?.workflows && data?.workflows.length > 0 ? (
<div>
<div className="space-y-4">
{sortedWorkflows.map((workflow) => {
return (
<WorkflowListItem key={workflow.id} workflow={workflow} eventType={props.eventType} />
);
})}
</div>
</div>
) : (
<div className="pt-2 before:border-0">
<EmptyScreen
Icon={Zap}
headline={t("workflows")}
description={t("no_workflows_description")}
buttonRaw={
isChildrenManagedEventType && !isManagedEventType ? (
<Button StartIcon={Lock} color="secondary" disabled>
{t("locked_by_admin")}
</Button>
) : (
<Button
target="_blank"
color="secondary"
onClick={() => createMutation.mutate({ teamId: eventType.team?.id })}
loading={createMutation.isLoading}>
{t("create_workflow")}
</Button>
)
}
/>
</div>
)}
</>
) : (
<SkeletonLoader />
)}
@@ -1,5 +1,5 @@
import type { WorkflowActions } from "@prisma/client";
import { WorkflowTemplates } from "@prisma/client";
import { WorkflowTemplates, SchedulingType } from "@prisma/client";
import { useRouter } from "next/router";
import type { Dispatch, SetStateAction } from "react";
import { useMemo, useState } from "react";
@@ -48,10 +48,15 @@ export default function WorkflowDetailsPage(props: Props) {
if (teamId && teamId !== group.teamId) return options;
return [
...options,
...group.eventTypes.map((eventType) => ({
value: String(eventType.id),
label: eventType.title,
})),
...group.eventTypes
.filter(
(evType) =>
!evType.metadata?.managedEventConfig && evType.schedulingType !== SchedulingType.MANAGED
)
.map((eventType) => ({
value: String(eventType.id),
label: eventType.title,
})),
];
}, [] as Option[]) || [],
[data]
@@ -0,0 +1,81 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import type { Props } from "react-select";
import { CAL_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Avatar, EmptyScreen, Label, Select } from "@calcom/ui";
import { FiUserPlus, FiX } from "@calcom/ui/components/icon";
export type CheckedUserSelectOption = {
avatar: string;
label: string;
value: string;
disabled?: boolean;
};
export const CheckedUserSelect = ({
options = [],
value = [],
...props
}: Omit<Props<CheckedUserSelectOption, true>, "value" | "onChange"> & {
value?: readonly CheckedUserSelectOption[];
onChange: (value: readonly CheckedUserSelectOption[]) => void;
}) => {
const { t } = useLocale();
const [animationRef] = useAutoAnimate<HTMLUListElement>();
return (
<>
<Select
styles={{
option: (styles, { isDisabled }) => ({
...styles,
backgroundColor: isDisabled ? "#F5F5F5" : "inherit",
}),
}}
name={props.name}
placeholder={props.placeholder || t("select")}
isSearchable={false}
options={options}
value={value}
isMulti
{...props}
/>
{value.length > 0 ? (
<div className="mt-6">
<Label>{t("assigned_to")}</Label>
<div className="flex overflow-hidden rounded-md border border-gray-200 bg-white">
<ul className="w-full" data-testid="managed-event-types" ref={animationRef}>
{value.map((option, index) => {
const calLink = `${CAL_URL}/${option.value}`;
return (
<li
key={option.value}
className={`flex py-2 px-3 ${index === value.length - 1 ? "" : "border-b"}`}>
<Avatar size="sm" imageSrc={option.avatar} alt={option.label} />
<p className="my-auto ml-3 text-sm text-gray-900">{option.label}</p>
<FiX
onClick={() => props.onChange(value.filter((item) => item.value !== option.value))}
className="my-auto ml-auto"
/>
</li>
);
})}
</ul>
</div>
</div>
) : (
<div className="mt-6">
<EmptyScreen
Icon={FiUserPlus}
headline={t("no_assigned_members")}
description={t("start_assigning_members_above")}
/>
</div>
)}
</>
);
};
export default CheckedUserSelect;
@@ -0,0 +1,140 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { MembershipRole } from "@prisma/client";
import type { Props } from "react-select";
import { classNames } from "@calcom/lib";
import { CAL_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Avatar, Badge, Button, ButtonGroup, Select, Switch, Tooltip } from "@calcom/ui";
import { ExternalLink, X } from "@calcom/ui/components/icon";
export type ChildrenEventType = {
value: string;
label: string;
created: boolean;
owner: {
id: number;
email: string;
name: string;
username: string;
membership: MembershipRole;
eventTypeSlugs: string[];
};
slug: string;
hidden: boolean;
};
export const ChildrenEventTypeSelect = ({
options = [],
value = [],
...props
}: Omit<Props<ChildrenEventType, true>, "value" | "onChange"> & {
value?: ChildrenEventType[];
onChange: (value: readonly ChildrenEventType[]) => void;
}) => {
const { t } = useLocale();
const [animationRef] = useAutoAnimate<HTMLUListElement>();
return (
<>
<Select
styles={{
option: (styles, { isDisabled }) => ({
...styles,
backgroundColor: isDisabled ? "#F5F5F5" : "inherit",
}),
}}
name={props.name}
placeholder={t("select")}
isSearchable={false}
options={options}
value={value}
isMulti
{...props}
/>
{/* This class name conditional looks a bit odd but it allows a seemless transition when using autoanimate
- Slides down from the top instead of just teleporting in from nowhere*/}
<ul
className={classNames(
"border-subtle divide-subtle mt-3 divide-y rounded-md",
value.length >= 1 && "border"
)}
ref={animationRef}>
{value.map((children, index) => (
<li key={index}>
<div className="flex flex-row items-center gap-3 p-3">
<Avatar
size="mdLg"
imageSrc={`${CAL_URL}/${children.owner.username}/avatar.png`}
alt={children.owner.name || ""}
/>
<div className="flex w-full flex-row justify-between">
<div className="flex flex-col">
<span className="text text-sm font-semibold leading-none">
{children.owner.name}
{children.owner.membership === MembershipRole.OWNER ? (
<Badge className="ml-2" variant="gray">
{t("owner")}
</Badge>
) : (
<Badge className="ml-2" variant="gray">
{t("member")}
</Badge>
)}
</span>
<small className="text-subtle font-normal leading-normal">
{`/${children.owner.username}/${children.slug}`}
</small>
</div>
<div className="flex flex-row items-center gap-2">
{children.hidden && <Badge variant="gray">{t("hidden")}</Badge>}
<Tooltip content={t("show_eventtype_on_profile")}>
<div className="self-center rounded-md p-2">
<Switch
name="Hidden"
checked={!children.hidden}
onCheckedChange={(checked) => {
const newData = value.map((item) =>
item.owner.id === children.owner.id ? { ...item, hidden: !checked } : item
);
props.onChange(newData);
}}
/>
</div>
</Tooltip>
<ButtonGroup combined>
{children.created && (
<Tooltip content={t("preview")}>
<Button
color="secondary"
target="_blank"
variant="icon"
href={`${CAL_URL}/${children.owner?.username}/${children.slug}`}
StartIcon={ExternalLink}
/>
</Tooltip>
)}
<Tooltip content={t("delete")}>
<Button
color="secondary"
target="_blank"
variant="icon"
onClick={() =>
props.onChange(value.filter((item) => item.owner.id !== children.owner.id))
}
StartIcon={X}
/>
</Tooltip>
</ButtonGroup>
</div>
</div>
</div>
</li>
))}
</ul>
</>
);
};
export default ChildrenEventTypeSelect;
@@ -1,16 +1,21 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { SchedulingType } from "@prisma/client";
import { MembershipRole } from "@prisma/client";
import { isValidPhoneNumber } from "libphonenumber-js";
import { useRouter } from "next/router";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useFlagMap } from "@calcom/features/flags/context/provider";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useTypedQuery } from "@calcom/lib/hooks/useTypedQuery";
import { HttpError } from "@calcom/lib/http-error";
import { md } from "@calcom/lib/markdownIt";
import slugify from "@calcom/lib/slugify";
import turndown from "@calcom/lib/turndownService";
import { unlockedManagedEventTypeProps } from "@calcom/prisma/zod-utils";
import { createEventTypeInput } from "@calcom/prisma/zod/custom/eventtype";
import { trpc } from "@calcom/trpc/react";
import {
@@ -29,6 +34,7 @@ import {
// this describes the uniform data needed to create a new event type on Profile or Team
export interface EventTypeParent {
teamId: number | null | undefined; // if undefined, then it's a profile
membershipRole?: MembershipRole | null;
name?: string | null;
slug?: string | null;
image?: string | null;
@@ -61,13 +67,23 @@ const querySchema = z.object({
.optional(),
});
export default function CreateEventTypeDialog() {
export default function CreateEventTypeDialog({
profileOptions,
}: {
profileOptions: {
teamId: number | null | undefined;
label: string | null;
image: string | undefined;
membershipRole: MembershipRole | null | undefined;
}[];
}) {
const { t } = useLocale();
const router = useRouter();
const {
data: { teamId, eventPage: pageSlug },
} = useTypedQuery(querySchema);
const teamProfile = profileOptions.find((profile) => profile.teamId === teamId);
const form = useForm<z.infer<typeof createEventTypeInput>>({
defaultValues: {
@@ -76,8 +92,24 @@ export default function CreateEventTypeDialog() {
resolver: zodResolver(createEventTypeInput),
});
const schedulingTypeWatch = form.watch("schedulingType");
const isManagedEventType = schedulingTypeWatch === SchedulingType.MANAGED;
useEffect(() => {
if (isManagedEventType) {
form.setValue("metadata.managedEventConfig.unlockedFields", unlockedManagedEventTypeProps);
} else {
form.setValue("metadata", null);
}
}, [schedulingTypeWatch]);
const { register } = form;
const isAdmin =
teamId !== undefined &&
(teamProfile?.membershipRole === MembershipRole.OWNER ||
teamProfile?.membershipRole === MembershipRole.ADMIN);
const createMutation = trpc.viewer.eventTypes.create.useMutation({
onSuccess: async ({ eventType }) => {
await router.replace("/event-types/" + eventType.id);
@@ -101,6 +133,8 @@ export default function CreateEventTypeDialog() {
},
});
const flags = useFlagMap();
return (
<Dialog
name="new"
@@ -147,52 +181,67 @@ export default function CreateEventTypeDialog() {
{process.env.NEXT_PUBLIC_WEBSITE_URL !== undefined &&
process.env.NEXT_PUBLIC_WEBSITE_URL?.length >= 21 ? (
<TextField
label={`${t("url")}: ${process.env.NEXT_PUBLIC_WEBSITE_URL}`}
required
addOnLeading={<>/{pageSlug}/</>}
{...register("slug")}
onChange={(e) => {
form.setValue("slug", slugify(e?.target.value), { shouldTouch: true });
}}
/>
<div>
<TextField
label={`${t("url")}: ${process.env.NEXT_PUBLIC_WEBSITE_URL}`}
required
addOnLeading={<>/{!isManagedEventType ? pageSlug : t("username_placeholder")}/</>}
{...register("slug")}
onChange={(e) => {
form.setValue("slug", slugify(e?.target.value), { shouldTouch: true });
}}
/>
{isManagedEventType && (
<p className="mt-2 text-sm text-gray-600">{t("managed_event_url_clarification")}</p>
)}
</div>
) : (
<TextField
label={t("url")}
required
addOnLeading={
<>
{process.env.NEXT_PUBLIC_WEBSITE_URL}/{pageSlug}/
</>
}
{...register("slug")}
/>
<div>
<TextField
label={t("url")}
required
addOnLeading={
<>
{process.env.NEXT_PUBLIC_WEBSITE_URL}/
{!isManagedEventType ? pageSlug : t("username_placeholder")}/
</>
}
{...register("slug")}
/>
{isManagedEventType && (
<p className="mt-2 text-sm text-gray-600">{t("managed_event_url_clarification")}</p>
)}
</div>
)}
{!teamId && (
<>
<Editor
getText={() => md.render(form.getValues("description") || "")}
setText={(value: string) => form.setValue("description", turndown(value))}
excludedToolbarItems={["blockType", "link"]}
placeholder={t("quick_video_meeting")}
/>
<Editor
getText={() => md.render(form.getValues("description") || "")}
setText={(value: string) => form.setValue("description", turndown(value))}
excludedToolbarItems={["blockType", "link"]}
placeholder={t("quick_video_meeting")}
/>
<div className="relative">
<TextField
type="number"
required
min="10"
placeholder="15"
label={t("length")}
className="pr-4"
{...register("length", { valueAsNumber: true })}
addOnSuffix={t("minutes")}
/>
</div>
<div className="relative">
<TextField
type="number"
required
min="10"
placeholder="15"
label={t("length")}
className="pr-4"
{...register("length", { valueAsNumber: true })}
addOnSuffix={t("minutes")}
/>
</div>
</>
)}
{teamId && (
<div className="mb-4">
<label htmlFor="schedulingType" className="text-default block text-sm font-bold">
{t("scheduling_type")}
{t("assignment")}
</label>
{form.formState.errors.schedulingType && (
<Alert
@@ -201,21 +250,39 @@ export default function CreateEventTypeDialog() {
message={form.formState.errors.schedulingType.message}
/>
)}
<RadioArea.Group className="mt-1 flex space-x-4">
<RadioArea.Group
className={classNames(
"mt-1 flex gap-4",
isAdmin && flags["managed-event-types"] && "flex-col"
)}>
<RadioArea.Item
{...register("schedulingType")}
value={SchedulingType.COLLECTIVE}
className="w-1/2 text-sm">
className={classNames("w-full text-sm", !isAdmin && "w-1/2")}
classNames={{ container: classNames(isAdmin && "w-full") }}>
<strong className="mb-1 block">{t("collective")}</strong>
<p>{t("collective_description")}</p>
</RadioArea.Item>
<RadioArea.Item
{...register("schedulingType")}
value={SchedulingType.ROUND_ROBIN}
className="w-1/2 text-sm">
className={classNames("text-sm", !isAdmin && "w-1/2")}
classNames={{ container: classNames(isAdmin && "w-full") }}>
<strong className="mb-1 block">{t("round_robin")}</strong>
<p>{t("round_robin_description")}</p>
</RadioArea.Item>
<>
{isAdmin && flags["managed-event-types"] && (
<RadioArea.Item
{...register("schedulingType")}
value={SchedulingType.MANAGED}
className={classNames("text-sm", !isAdmin && "w-1/2")}
classNames={{ container: classNames(isAdmin && "w-full") }}>
<strong className="mb-1 block">{t("managed_event")}</strong>
<p>{t("managed_event_description")}</p>
</RadioArea.Item>
)}
</>
</RadioArea.Group>
</div>
)}
@@ -10,7 +10,7 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { baseEventTypeSelect } from "@calcom/prisma";
import type { EventTypeModel } from "@calcom/prisma/zod";
import { Badge } from "@calcom/ui";
import { Clock, Users, RefreshCw, CreditCard, Clipboard, Plus, User } from "@calcom/ui/components/icon";
import { Clock, Users, RefreshCw, CreditCard, Clipboard, Plus, User, Lock } from "@calcom/ui/components/icon";
export type EventTypeDescriptionProps = {
eventType: Pick<
@@ -23,12 +23,14 @@ export type EventTypeDescriptionProps = {
};
className?: string;
shortenDescription?: boolean;
isPublic?: boolean;
};
export const EventTypeDescription = ({
eventType,
className,
shortenDescription,
isPublic,
}: EventTypeDescriptionProps) => {
const { t } = useLocale();
@@ -69,7 +71,7 @@ export const EventTypeDescription = ({
</Badge>
</li>
)}
{eventType.schedulingType && (
{eventType.schedulingType && eventType.schedulingType !== SchedulingType.MANAGED && (
<li>
<Badge variant="gray" startIcon={Users}>
{eventType.schedulingType === SchedulingType.ROUND_ROBIN && t("round_robin")}
@@ -77,6 +79,11 @@ export const EventTypeDescription = ({
</Badge>
</li>
)}
{eventType.metadata?.managedEventConfig && !isPublic && (
<Badge variant="gray" startIcon={Lock}>
{t("managed")}
</Badge>
)}
{recurringEvent?.count && recurringEvent.count > 0 && (
<li className="hidden xl:block">
<Badge variant="gray" startIcon={RefreshCw}>
@@ -1,6 +1,6 @@
import { trpc } from "@calcom/trpc/react";
import type { RouterOutputs } from "@calcom/trpc/react";
import { Badge, List, ListItem, ListItemText, ListItemTitle, Switch } from "@calcom/ui";
import { Badge, List, ListItem, ListItemText, ListItemTitle, Switch, showToast } from "@calcom/ui";
export const FlagAdminList = () => {
const [data] = trpc.viewer.features.list.useSuspenseQuery();
@@ -12,7 +12,7 @@ export const FlagAdminList = () => {
<ListItemTitle component="h3">
{flag.slug}
&nbsp;&nbsp;
<Badge variant="green">{flag.type}</Badge>
<Badge variant="green">{flag.type?.replace("_", " ")}</Badge>
</ListItemTitle>
<ListItemText component="p">{flag.description}</ListItemText>
</div>
@@ -34,6 +34,7 @@ const FlagToggle = (props: { flag: Flag }) => {
const utils = trpc.useContext();
const mutation = trpc.viewer.features.toggle.useMutation({
onSuccess: () => {
showToast("Flags successfully updated", "success");
utils.viewer.features.list.invalidate();
utils.viewer.features.map.invalidate();
},
+1
View File
@@ -9,4 +9,5 @@ export type AppFlags = {
webhooks: boolean;
workflows: boolean;
"v2-booking-page": boolean;
"managed-event-types": boolean;
};
+3 -1
View File
@@ -1,6 +1,8 @@
import { trpc } from "@calcom/trpc/react";
export function useFlags() {
const query = trpc.viewer.features.map.useQuery(undefined, { initialData: {} });
const query = trpc.viewer.features.map.useQuery(undefined, {
initialData: process.env.NEXT_PUBLIC_IS_E2E ? { "managed-event-types": true, teams: true } : {},
});
return query.data;
}
+41 -22
View File
@@ -44,12 +44,16 @@ export const FormBuilder = function FormBuilder({
description,
addFieldLabel,
formProp,
disabled,
LockedIcon,
dataStore,
}: {
formProp: string;
title: string;
description: string;
addFieldLabel: string;
disabled: boolean;
LockedIcon: false | JSX.Element;
/**
* A readonly dataStore that is used to lookup the options for the fields. It works in conjunction with the field.getOptionAt property which acts as the key in options
*/
@@ -271,9 +275,12 @@ export const FormBuilder = function FormBuilder({
return (
<div>
<div>
<div className="text-default text-sm font-semibold ltr:mr-1 rtl:ml-1">{title}</div>
<div className="text-default text-sm font-semibold ltr:mr-1 rtl:ml-1">
{title}
{LockedIcon}
</div>
<p className="text-subtle max-w-[280px] break-words py-1 text-sm sm:max-w-[500px]">{description}</p>
<ul className="border-default divide-subtle mt-2 divide-y-2 rounded-md border ">
<ul className="border-default divide-subtle mt-2 divide-y rounded-md border">
{fields.map((field, index) => {
const options = field.options
? field.options
@@ -309,22 +316,27 @@ export const FormBuilder = function FormBuilder({
key={field.name}
data-testid={`field-${field.name}`}
className="hover:bg-muted group relative flex items-center justify-between p-4 ">
{index >= 1 && (
<button
type="button"
className="bg-default text-muted hover:text-emphasis disabled:hover:text-muted border-default hover:border-emphasis invisible absolute -left-[12px] -mt-4 mb-4 -ml-4 hidden h-6 w-6 scale-0 items-center justify-center rounded-md border p-1 transition-all hover:shadow disabled:hover:border-inherit disabled:hover:shadow-none group-hover:visible group-hover:scale-100 sm:ml-0 sm:flex"
onClick={() => swap(index, index - 1)}>
<ArrowUp className="h-5 w-5" />
</button>
)}
{index < fields.length - 1 && (
<button
type="button"
className="bg-default text-muted hover:border-emphasis border-default hover:text-emphasis disabled:hover:text-muted invisible absolute -left-[12px] mt-8 -ml-4 hidden h-6 w-6 scale-0 items-center justify-center rounded-md border p-1 transition-all hover:shadow disabled:hover:border-inherit disabled:hover:shadow-none group-hover:visible group-hover:scale-100 sm:ml-0 sm:flex"
onClick={() => swap(index, index + 1)}>
<ArrowDown className="h-5 w-5" />
</button>
{!disabled && (
<>
{index >= 1 && (
<button
type="button"
className="bg-default text-muted hover:text-emphasis disabled:hover:text-muted border-default hover:border-emphasis invisible absolute -left-[12px] -mt-4 mb-4 -ml-4 hidden h-6 w-6 scale-0 items-center justify-center rounded-md border p-1 transition-all hover:shadow disabled:hover:border-inherit disabled:hover:shadow-none group-hover:visible group-hover:scale-100 sm:ml-0 sm:flex"
onClick={() => swap(index, index - 1)}>
<ArrowUp className="h-5 w-5" />
</button>
)}
{index < fields.length - 1 && (
<button
type="button"
className="bg-default text-muted hover:border-emphasis border-default hover:text-emphasis disabled:hover:text-muted invisible absolute -left-[12px] mt-8 -ml-4 hidden h-6 w-6 scale-0 items-center justify-center rounded-md border p-1 transition-all hover:shadow disabled:hover:border-inherit disabled:hover:shadow-none group-hover:visible group-hover:scale-100 sm:ml-0 sm:flex"
onClick={() => swap(index, index + 1)}>
<ArrowDown className="h-5 w-5" />
</button>
)}
</>
)}
<div>
<div className="flex flex-col lg:flex-row lg:items-center">
<div className="text-default text-sm font-semibold ltr:mr-2 rtl:ml-2">
@@ -349,9 +361,9 @@ export const FormBuilder = function FormBuilder({
{fieldType.label}
</p>
</div>
{field.editable !== "user-readonly" && (
{field.editable !== "user-readonly" && !disabled && (
<div className="flex items-center space-x-2">
{!isFieldEditableSystem && (
{!isFieldEditableSystem && !disabled && (
<Switch
data-testid="toggle-field"
disabled={isFieldEditableSystem}
@@ -388,9 +400,16 @@ export const FormBuilder = function FormBuilder({
);
})}
</ul>
<Button color="minimal" data-testid="add-field" onClick={addField} className="mt-4" StartIcon={Plus}>
{addFieldLabel}
</Button>
{!disabled && (
<Button
color="minimal"
data-testid="add-field"
onClick={addField}
className="mt-4"
StartIcon={Plus}>
{addFieldLabel}
</Button>
)}
</div>
<Dialog
open={fieldDialog.isOpen}
@@ -30,6 +30,7 @@ type WebhookProps = {
export default function WebhookListItem(props: {
webhook: WebhookProps;
canEditWebhook?: boolean;
onEditWebhook: () => void;
lastItem: boolean;
}) {
@@ -81,6 +82,7 @@ export default function WebhookListItem(props: {
<div className="ml-2 flex items-center space-x-4">
<Switch
defaultChecked={webhook.active}
disabled={!props.canEditWebhook}
onCheckedChange={() =>
toggleWebhook.mutate({
id: webhook.id,