feat: select team members to receive emails (#13957)
* Add UI to select members to receive emails in routing form * Add backend changes to support frontend to select team members to get routing form updates to * Fix type error * Fix all the members of all the teams the user is part of shown instead of only the current team where the routing form is created * Fix type error * Refactor components to a shared folder * fix type error * Fix review comment: only include emails * Remove listMembers trpc call in frontend and get the data in formQuery.handler * Address review comments * Remove unrelated changes * Update SingleForm.tsx --------- Co-authored-by: Carina Wollendorfer <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
13 files changed
+376
-206
No files matched your search
@@ -6,36 +6,16 @@ import type { ComponentProps, Dispatch, SetStateAction } from "react";
|
||||
import { Controller, useFormContext, useWatch } from "react-hook-form";
|
||||
import type { Options } from "react-select";
|
||||
|
||||
import type { CheckedSelectOption } from "@calcom/features/eventtypes/components/CheckedTeamSelect";
|
||||
import CheckedTeamSelect from "@calcom/features/eventtypes/components/CheckedTeamSelect";
|
||||
import AddMembersWithSwitch, {
|
||||
mapUserToValue,
|
||||
} from "@calcom/features/eventtypes/components/AddMembersWithSwitch";
|
||||
import AssignAllTeamMembers from "@calcom/features/eventtypes/components/AssignAllTeamMembers";
|
||||
import ChildrenEventTypeSelect from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import type { FormValues, TeamMember } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { Label, Select, SettingsToggle } from "@calcom/ui";
|
||||
|
||||
interface IUserToValue {
|
||||
id: number | null;
|
||||
name: string | null;
|
||||
username: string | null;
|
||||
avatar: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
type TeamMember = {
|
||||
value: string;
|
||||
label: string;
|
||||
avatar: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
const mapUserToValue = ({ id, name, username, avatar, email }: IUserToValue, pendingString: string) => ({
|
||||
value: `${id || ""}`,
|
||||
label: `${name || email || ""}${!username ? ` (${pendingString})` : ""}`,
|
||||
avatar,
|
||||
email,
|
||||
});
|
||||
|
||||
export const mapMemberToChildrenOption = (
|
||||
member: EventTypeSetupProps["teamMembers"][number],
|
||||
slug: string,
|
||||
@@ -59,16 +39,6 @@ export const mapMemberToChildrenOption = (
|
||||
};
|
||||
};
|
||||
|
||||
const sortByLabel = (a: ReturnType<typeof mapUserToValue>, b: ReturnType<typeof mapUserToValue>) => {
|
||||
if (a.label < b.label) {
|
||||
return -1;
|
||||
}
|
||||
if (a.label > b.label) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
const ChildrenEventTypesList = ({
|
||||
options = [],
|
||||
value,
|
||||
@@ -105,94 +75,6 @@ const ChildrenEventTypesList = ({
|
||||
);
|
||||
};
|
||||
|
||||
const AssignAllTeamMembers = ({
|
||||
assignAllTeamMembers,
|
||||
setAssignAllTeamMembers,
|
||||
onActive,
|
||||
onInactive,
|
||||
}: {
|
||||
assignAllTeamMembers: boolean;
|
||||
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
|
||||
onActive: () => void;
|
||||
onInactive?: () => void;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const { setValue } = useFormContext<FormValues>();
|
||||
|
||||
return (
|
||||
<Controller<FormValues>
|
||||
name="assignAllTeamMembers"
|
||||
render={() => (
|
||||
<SettingsToggle
|
||||
title={t("automatically_add_all_team_members")}
|
||||
labelClassName="mt-0.5 font-normal"
|
||||
checked={assignAllTeamMembers}
|
||||
onCheckedChange={(active) => {
|
||||
setValue("assignAllTeamMembers", active, { shouldDirty: true });
|
||||
setAssignAllTeamMembers(active);
|
||||
if (active) {
|
||||
onActive();
|
||||
} else if (!!onInactive) {
|
||||
onInactive();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const CheckedHostField = ({
|
||||
labelText,
|
||||
placeholder,
|
||||
options = [],
|
||||
isFixed,
|
||||
value,
|
||||
onChange,
|
||||
helperText,
|
||||
...rest
|
||||
}: {
|
||||
labelText?: string;
|
||||
placeholder: string;
|
||||
isFixed: boolean;
|
||||
value: Host[];
|
||||
onChange?: (options: Host[]) => void;
|
||||
options?: Options<CheckedSelectOption>;
|
||||
helperText?: React.ReactNode | string;
|
||||
} & Omit<Partial<ComponentProps<typeof CheckedTeamSelect>>, "onChange" | "value">) => {
|
||||
return (
|
||||
<div className="flex flex-col rounded-md">
|
||||
<div>
|
||||
{labelText ? <Label>{labelText}</Label> : <></>}
|
||||
<CheckedTeamSelect
|
||||
isOptionDisabled={(option) => !!value.find((host) => host.userId.toString() === option.value)}
|
||||
onChange={(options) => {
|
||||
onChange &&
|
||||
onChange(
|
||||
options.map((option) => ({
|
||||
isFixed,
|
||||
userId: parseInt(option.value, 10),
|
||||
priority: option.priority ?? 2,
|
||||
}))
|
||||
);
|
||||
}}
|
||||
value={(value || [])
|
||||
.filter(({ isFixed: _isFixed }) => isFixed === _isFixed)
|
||||
.map((host) => {
|
||||
const option = options.find((member) => member.value === host.userId.toString());
|
||||
return option ? { ...option, priority: host.priority ?? 2, isFixed } : options[0];
|
||||
})
|
||||
.filter(Boolean)}
|
||||
controlShouldRenderValue={false}
|
||||
options={options}
|
||||
placeholder={placeholder}
|
||||
{...rest}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const FixedHostHelper = (
|
||||
<Trans i18nKey="fixed_host_helper">
|
||||
Add anyone who needs to attend the event.
|
||||
@@ -304,59 +186,6 @@ const FixedHosts = ({
|
||||
);
|
||||
};
|
||||
|
||||
const AddMembersWithSwitch = ({
|
||||
teamMembers,
|
||||
value,
|
||||
onChange,
|
||||
assignAllTeamMembers,
|
||||
setAssignAllTeamMembers,
|
||||
automaticAddAllEnabled,
|
||||
onActive,
|
||||
isFixed,
|
||||
}: {
|
||||
value: Host[];
|
||||
onChange: (hosts: Host[]) => void;
|
||||
teamMembers: TeamMember[];
|
||||
assignAllTeamMembers: boolean;
|
||||
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
|
||||
automaticAddAllEnabled: boolean;
|
||||
onActive: () => void;
|
||||
isFixed: boolean;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const { setValue } = useFormContext<FormValues>();
|
||||
|
||||
return (
|
||||
<div className="rounded-md ">
|
||||
<div className="flex flex-col rounded-md px-6 pb-2 pt-6">
|
||||
{automaticAddAllEnabled ? (
|
||||
<div className="mb-2">
|
||||
<AssignAllTeamMembers
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
onActive={onActive}
|
||||
onInactive={() => setValue("hosts", [], { shouldDirty: true })}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
{!assignAllTeamMembers || !automaticAddAllEnabled ? (
|
||||
<CheckedHostField
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
isFixed={isFixed}
|
||||
options={teamMembers.sort(sortByLabel)}
|
||||
placeholder={t("add_attendees")}
|
||||
/>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const RoundRobinHosts = ({
|
||||
teamMembers,
|
||||
value,
|
||||
|
||||
@@ -1087,7 +1087,7 @@
|
||||
"make_team_private": "Make team private",
|
||||
"make_team_private_description": "Your team members won't be able to see other team members when this is turned on.",
|
||||
"you_cannot_see_team_members": "You cannot see all the team members of a private team.",
|
||||
"you_cannot_see_teams_of_org":"You cannot see teams of a private organization.",
|
||||
"you_cannot_see_teams_of_org": "You cannot see teams of a private organization.",
|
||||
"allow_booker_to_select_duration": "Allow booker to select duration",
|
||||
"impersonate_user_tip": "All uses of this feature is audited.",
|
||||
"impersonating_user_warning": "Impersonating username \"{{user}}\".",
|
||||
@@ -1475,6 +1475,7 @@
|
||||
"routing_forms_description": "Create forms to direct attendees to the correct destinations",
|
||||
"routing_forms_send_email_owner": "Send Email to Owner",
|
||||
"routing_forms_send_email_owner_description": "Sends an email to the owner when the form is submitted",
|
||||
"routing_forms_send_email_to": "Send Email to",
|
||||
"add_new_form": "Add new form",
|
||||
"add_new_team_form": "Add new form to your team",
|
||||
"create_your_first_route": "Create your first route",
|
||||
@@ -2318,12 +2319,13 @@
|
||||
"confirm_email": "Confirm your email",
|
||||
"confirm_email_description": "We sent an email to <strong>{{email}}</strong>. Click the link in the email to verify this address.",
|
||||
"send_event_details_to": "Send event details to",
|
||||
"lock_event_types_modal_header":"What should we do with your member's existing event types?",
|
||||
"org_delete_event_types_org_admin":"All of your members individual event types (except managed ones) will be permanently deleted. They will not be able to create new ones",
|
||||
"org_hide_event_types_org_admin":"Your members individual event types will be hidden (except managed ones) from profiles but the links will still be active. They will not be able to create new ones. ",
|
||||
"hide_org_eventtypes":"Hide individual event types",
|
||||
"delete_org_eventtypes":"Delete individual event types",
|
||||
"lock_org_users_eventtypes":"Lock individual event type creation",
|
||||
"lock_org_users_eventtypes_description":"Prevent members from creating their own event types.",
|
||||
"select_members": "Select members",
|
||||
"lock_event_types_modal_header": "What should we do with your member's existing event types?",
|
||||
"org_delete_event_types_org_admin": "All of your members individual event types (except managed ones) will be permanently deleted. They will not be able to create new ones",
|
||||
"org_hide_event_types_org_admin": "Your members individual event types will be hidden (except managed ones) from profiles but the links will still be active. They will not be able to create new ones. ",
|
||||
"hide_org_eventtypes": "Hide individual event types",
|
||||
"delete_org_eventtypes": "Delete individual event types",
|
||||
"lock_org_users_eventtypes": "Lock individual event type creation",
|
||||
"lock_org_users_eventtypes_description": "Prevent members from creating their own event types.",
|
||||
"ADD_NEW_STRINGS_ABOVE_THIS_LINE_TO_PREVENT_MERGE_CONFLICTS": "↑↑↑↑↑↑↑↑↑↑↑↑↑ Add your new strings above here ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑"
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import type { UseFormReturn } from "react-hook-form";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
|
||||
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
|
||||
import AddMembersWithSwitch from "@calcom/features/eventtypes/components/AddMembersWithSwitch";
|
||||
import { ShellMain } from "@calcom/features/shell/Shell";
|
||||
import useApp from "@calcom/lib/hooks/useApp";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
@@ -293,6 +294,9 @@ function SingleForm({ form, appUrl, Page, enrichedWithUserProfileForm }: SingleF
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [form]);
|
||||
|
||||
const sendUpdatesTo = hookForm.watch("settings.sendUpdatesTo", []) as number[];
|
||||
const sendToAll = hookForm.watch("settings.sendToAll", false) as boolean;
|
||||
|
||||
const mutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
|
||||
onSuccess() {
|
||||
showToast(t("form_updated_successfully"), "success");
|
||||
@@ -356,20 +360,73 @@ function SingleForm({ form, appUrl, Page, enrichedWithUserProfileForm }: SingleF
|
||||
/>
|
||||
|
||||
<div className="mt-6">
|
||||
<Controller
|
||||
name="settings.emailOwnerOnSubmission"
|
||||
control={hookForm.control}
|
||||
render={({ field: { value, onChange } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("routing_forms_send_email_owner")}
|
||||
description={t("routing_forms_send_email_owner_description")}
|
||||
checked={value}
|
||||
onCheckedChange={(val) => onChange(val)}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{form.teamId ? (
|
||||
<div className="flex flex-col">
|
||||
<span className="text-emphasis mb-3 block text-sm font-medium leading-none">
|
||||
{t("routing_forms_send_email_to")}
|
||||
</span>
|
||||
<AddMembersWithSwitch
|
||||
teamMembers={form.teamMembers.map((member) => ({
|
||||
value: member.id.toString(),
|
||||
label: member.name || "",
|
||||
avatar: member.avatarUrl || "",
|
||||
email: member.email,
|
||||
isFixed: true,
|
||||
}))}
|
||||
value={sendUpdatesTo.map((userId) => ({
|
||||
isFixed: true,
|
||||
userId: userId,
|
||||
priority: 1,
|
||||
}))}
|
||||
onChange={(value) => {
|
||||
hookForm.setValue(
|
||||
"settings.sendUpdatesTo",
|
||||
value.map((teamMember) => teamMember.userId),
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
hookForm.setValue("settings.emailOwnerOnSubmission", false, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
assignAllTeamMembers={sendToAll}
|
||||
setAssignAllTeamMembers={(value) => {
|
||||
hookForm.setValue("settings.sendToAll", !!value, { shouldDirty: true });
|
||||
}}
|
||||
automaticAddAllEnabled={true}
|
||||
isFixed={true}
|
||||
onActive={() => {
|
||||
hookForm.setValue(
|
||||
"settings.sendUpdatesTo",
|
||||
form.teamMembers.map((teamMember) => teamMember.id),
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
hookForm.setValue("settings.emailOwnerOnSubmission", false, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
placeholder={t("select_members")}
|
||||
containerClassName="!px-0 !pb-0 !pt-0"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Controller
|
||||
name="settings.emailOwnerOnSubmission"
|
||||
control={hookForm.control}
|
||||
render={({ field: { value, onChange } }) => {
|
||||
return (
|
||||
<SettingsToggle
|
||||
title={t("routing_forms_send_email_owner")}
|
||||
description={t("routing_forms_send_email_owner_description")}
|
||||
checked={value}
|
||||
onCheckedChange={(val) => {
|
||||
onChange(val);
|
||||
hookForm.unregister("settings.sendUpdatesTo");
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{form.routers.length ? (
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { z } from "zod";
|
||||
import { entityPrismaWhereClause } from "@calcom/lib/entityPermissionUtils";
|
||||
import { RoutingFormSettings } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import type { SerializableForm } from "../types/types";
|
||||
import type { SerializableForm, SerializableFormTeamMembers } from "../types/types";
|
||||
import type { zodRoutesView, zodFieldsView } from "../zod";
|
||||
import { zodFields, zodRoutes } from "../zod";
|
||||
import getConnectedForms from "./getConnectedForms";
|
||||
@@ -58,6 +58,25 @@ export async function getSerializableForm<TForm extends App_RoutingForms_Form>({
|
||||
description: f.description,
|
||||
}));
|
||||
const finalFields = fields;
|
||||
let teamMembers: SerializableFormTeamMembers[] = [];
|
||||
if (form.teamId) {
|
||||
teamMembers = await prisma.user.findMany({
|
||||
where: {
|
||||
teams: {
|
||||
some: {
|
||||
teamId: form.teamId,
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
avatarUrl: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Ideally we should't have needed to explicitly type it but due to some reason it's not working reliably with VSCode TypeCheck
|
||||
const serializableForm: SerializableForm<TForm> = {
|
||||
@@ -67,6 +86,7 @@ export async function getSerializableForm<TForm extends App_RoutingForms_Form>({
|
||||
routes,
|
||||
routers,
|
||||
connectedForms,
|
||||
teamMembers,
|
||||
createdAt: form.createdAt.toString(),
|
||||
updatedAt: form.updatedAt.toString(),
|
||||
};
|
||||
|
||||
@@ -25,8 +25,9 @@ interface FormMutationHandlerOptions {
|
||||
}
|
||||
export const formMutationHandler = async ({ ctx, input }: FormMutationHandlerOptions) => {
|
||||
const { user, prisma } = ctx;
|
||||
const { name, id, description, settings, disabled, addFallback, duplicateFrom, shouldConnect } = input;
|
||||
const { name, id, description, disabled, addFallback, duplicateFrom, shouldConnect } = input;
|
||||
let teamId = input.teamId;
|
||||
const settings = input.settings;
|
||||
if (!(await isFormCreateEditAllowed({ userId: user.id, formId: id, targetTeamId: teamId }))) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
@@ -90,6 +91,25 @@ export const formMutationHandler = async ({ ctx, input }: FormMutationHandlerOpt
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the users passed
|
||||
if (teamId && settings?.sendUpdatesTo?.length) {
|
||||
const sendUpdatesTo = await prisma.membership.findMany({
|
||||
where: {
|
||||
teamId,
|
||||
userId: {
|
||||
in: settings.sendUpdatesTo,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
settings.sendUpdatesTo = sendUpdatesTo.map((member) => member.userId);
|
||||
// If its not a team, the user is sending the value, we will just ignore it
|
||||
} else if (!teamId && settings?.sendUpdatesTo) {
|
||||
delete settings.sendUpdatesTo;
|
||||
}
|
||||
|
||||
return await prisma.app_RoutingForms_Form.upsert({
|
||||
where: {
|
||||
id: id,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Prisma } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { RoutingFormSettings } from "@calcom/prisma/zod-utils";
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
|
||||
import { getSerializableForm } from "../lib/getSerializableForm";
|
||||
@@ -93,7 +94,31 @@ export const responseHandler = async ({ ctx, input }: ResponseHandlerOptions) =>
|
||||
data: input,
|
||||
});
|
||||
|
||||
await onFormSubmission(serializableFormWithFields, dbFormResponse.response as Response);
|
||||
const settings = RoutingFormSettings.parse(form.settings);
|
||||
let userWithEmails: string[] = [];
|
||||
if (form.teamId && settings?.sendUpdatesTo?.length) {
|
||||
const userEmails = await prisma.membership.findMany({
|
||||
where: {
|
||||
teamId: form.teamId,
|
||||
userId: {
|
||||
in: settings.sendUpdatesTo,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
userWithEmails = userEmails.map((userEmail) => userEmail.user.email);
|
||||
}
|
||||
|
||||
await onFormSubmission(
|
||||
{ ...serializableFormWithFields, userWithEmails },
|
||||
dbFormResponse.response as Response
|
||||
);
|
||||
return dbFormResponse;
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
|
||||
@@ -10,7 +10,10 @@ import type { OrderedResponses } from "../types/types";
|
||||
import type { Response, SerializableForm } from "../types/types";
|
||||
|
||||
export async function onFormSubmission(
|
||||
form: Ensure<SerializableForm<App_RoutingForms_Form> & { user: Pick<User, "id" | "email"> }, "fields">,
|
||||
form: Ensure<
|
||||
SerializableForm<App_RoutingForms_Form> & { user: Pick<User, "id" | "email">; userWithEmails?: string[] },
|
||||
"fields"
|
||||
>,
|
||||
response: Response
|
||||
) {
|
||||
const fieldResponsesByName: Record<
|
||||
@@ -71,19 +74,24 @@ export async function onFormSubmission(
|
||||
logger.debug(
|
||||
`Preparing to send Form Response email for Form:${form.id} to form owner: ${form.user.email}`
|
||||
);
|
||||
await sendResponseEmail(form, orderedResponses, form.user.email);
|
||||
await sendResponseEmail(form, orderedResponses, [form.user.email]);
|
||||
} else if (form.userWithEmails?.length) {
|
||||
logger.debug(
|
||||
`Preparing to send Form Response email for Form:${form.id} to users: ${form.userWithEmails.join(",")}`
|
||||
);
|
||||
await sendResponseEmail(form, orderedResponses, form.userWithEmails);
|
||||
}
|
||||
}
|
||||
|
||||
export const sendResponseEmail = async (
|
||||
form: Pick<App_RoutingForms_Form, "id" | "name">,
|
||||
orderedResponses: OrderedResponses,
|
||||
ownerEmail: string
|
||||
toAddresses: string[]
|
||||
) => {
|
||||
try {
|
||||
if (typeof window === "undefined") {
|
||||
const { default: ResponseEmail } = await import("../emails/templates/response-email");
|
||||
const email = new ResponseEmail({ form: form, toAddresses: [ownerEmail], orderedResponses });
|
||||
const email = new ResponseEmail({ form: form, toAddresses, orderedResponses });
|
||||
await email.sendEmail();
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -23,6 +23,12 @@ export type Fields = z.infer<typeof zodFieldsView>;
|
||||
export type Field = Fields[number];
|
||||
export type Routes = z.infer<typeof zodRoutesView>;
|
||||
export type Route = Routes[0];
|
||||
export type SerializableFormTeamMembers = {
|
||||
id: number;
|
||||
name: string | null;
|
||||
email: string;
|
||||
avatarUrl: string | null;
|
||||
};
|
||||
export type SerializableForm<T extends App_RoutingForms_Form> = Omit<
|
||||
T,
|
||||
"fields" | "routes" | "createdAt" | "updatedAt" | "settings"
|
||||
@@ -34,6 +40,7 @@ export type SerializableForm<T extends App_RoutingForms_Form> = Omit<
|
||||
updatedAt: string;
|
||||
connectedForms: { name: string; description: string | null; id: string }[];
|
||||
routers: { name: string; description: string | null; id: string }[];
|
||||
teamMembers: SerializableFormTeamMembers[];
|
||||
};
|
||||
|
||||
export type LocalRoute = z.infer<typeof zodNonRouterRoute>;
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { ComponentProps, Dispatch, SetStateAction } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import type { Options } from "react-select";
|
||||
|
||||
import type { FormValues, Host, TeamMember } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Label } from "@calcom/ui";
|
||||
|
||||
import AssignAllTeamMembers from "./AssignAllTeamMembers";
|
||||
import CheckedTeamSelect from "./CheckedTeamSelect";
|
||||
import type { CheckedSelectOption } from "./CheckedTeamSelect";
|
||||
|
||||
interface IUserToValue {
|
||||
id: number | null;
|
||||
name: string | null;
|
||||
username: string | null;
|
||||
avatar: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export const mapUserToValue = (
|
||||
{ id, name, username, avatar, email }: IUserToValue,
|
||||
pendingString: string
|
||||
) => ({
|
||||
value: `${id || ""}`,
|
||||
label: `${name || email || ""}${!username ? ` (${pendingString})` : ""}`,
|
||||
avatar,
|
||||
email,
|
||||
});
|
||||
|
||||
const sortByLabel = (a: ReturnType<typeof mapUserToValue>, b: ReturnType<typeof mapUserToValue>) => {
|
||||
if (a.label < b.label) {
|
||||
return -1;
|
||||
}
|
||||
if (a.label > b.label) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
const CheckedHostField = ({
|
||||
labelText,
|
||||
placeholder,
|
||||
options = [],
|
||||
isFixed,
|
||||
value,
|
||||
onChange,
|
||||
helperText,
|
||||
...rest
|
||||
}: {
|
||||
labelText?: string;
|
||||
placeholder: string;
|
||||
isFixed: boolean;
|
||||
value: Host[];
|
||||
onChange?: (options: Host[]) => void;
|
||||
options?: Options<CheckedSelectOption>;
|
||||
helperText?: React.ReactNode | string;
|
||||
} & Omit<Partial<ComponentProps<typeof CheckedTeamSelect>>, "onChange" | "value">) => {
|
||||
return (
|
||||
<div className="flex flex-col rounded-md">
|
||||
<div>
|
||||
{labelText ? <Label>{labelText}</Label> : <></>}
|
||||
<CheckedTeamSelect
|
||||
isOptionDisabled={(option) => !!value.find((host) => host.userId.toString() === option.value)}
|
||||
onChange={(options) => {
|
||||
onChange &&
|
||||
onChange(
|
||||
options.map((option) => ({
|
||||
isFixed,
|
||||
userId: parseInt(option.value, 10),
|
||||
priority: option.priority ?? 2,
|
||||
}))
|
||||
);
|
||||
}}
|
||||
value={(value || [])
|
||||
.filter(({ isFixed: _isFixed }) => isFixed === _isFixed)
|
||||
.map((host) => {
|
||||
const option = options.find((member) => member.value === host.userId.toString());
|
||||
return option ? { ...option, priority: host.priority ?? 2, isFixed } : options[0];
|
||||
})
|
||||
.filter(Boolean)}
|
||||
controlShouldRenderValue={false}
|
||||
options={options}
|
||||
placeholder={placeholder}
|
||||
{...rest}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const AddMembersWithSwitch = ({
|
||||
teamMembers,
|
||||
value,
|
||||
onChange,
|
||||
assignAllTeamMembers,
|
||||
setAssignAllTeamMembers,
|
||||
automaticAddAllEnabled,
|
||||
onActive,
|
||||
isFixed,
|
||||
placeholder = "",
|
||||
containerClassName = "",
|
||||
}: {
|
||||
value: Host[];
|
||||
onChange: (hosts: Host[]) => void;
|
||||
teamMembers: TeamMember[];
|
||||
assignAllTeamMembers: boolean;
|
||||
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
|
||||
automaticAddAllEnabled: boolean;
|
||||
onActive: () => void;
|
||||
isFixed: boolean;
|
||||
placeholder?: string;
|
||||
containerClassName?: string;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const { setValue } = useFormContext<FormValues>();
|
||||
|
||||
return (
|
||||
<div className="rounded-md ">
|
||||
<div className={`flex flex-col rounded-md px-6 pb-2 pt-6 ${containerClassName}`}>
|
||||
{automaticAddAllEnabled ? (
|
||||
<div className="mb-2">
|
||||
<AssignAllTeamMembers
|
||||
assignAllTeamMembers={assignAllTeamMembers}
|
||||
setAssignAllTeamMembers={setAssignAllTeamMembers}
|
||||
onActive={onActive}
|
||||
onInactive={() => setValue("hosts", [], { shouldDirty: true })}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
{!assignAllTeamMembers || !automaticAddAllEnabled ? (
|
||||
<CheckedHostField
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
isFixed={isFixed}
|
||||
options={teamMembers.sort(sortByLabel)}
|
||||
placeholder={placeholder ?? t("add_attendees")}
|
||||
/>
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddMembersWithSwitch;
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { SettingsToggle } from "@calcom/ui";
|
||||
|
||||
const AssignAllTeamMembers = ({
|
||||
assignAllTeamMembers,
|
||||
setAssignAllTeamMembers,
|
||||
onActive,
|
||||
onInactive,
|
||||
}: {
|
||||
assignAllTeamMembers: boolean;
|
||||
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
|
||||
onActive: () => void;
|
||||
onInactive?: () => void;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const { setValue } = useFormContext<FormValues>();
|
||||
|
||||
return (
|
||||
<Controller<FormValues>
|
||||
name="assignAllTeamMembers"
|
||||
render={() => (
|
||||
<SettingsToggle
|
||||
title={t("automatically_add_all_team_members")}
|
||||
labelClassName="mt-0.5 font-normal"
|
||||
checked={assignAllTeamMembers}
|
||||
onCheckedChange={(active) => {
|
||||
setValue("assignAllTeamMembers", active, { shouldDirty: true });
|
||||
setAssignAllTeamMembers(active);
|
||||
if (active) {
|
||||
onActive();
|
||||
} else if (!!onInactive) {
|
||||
onInactive();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default AssignAllTeamMembers;
|
||||
@@ -4,6 +4,7 @@ import type { Dispatch, SetStateAction } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import type { Props } from "react-select";
|
||||
|
||||
import type { Host, FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import {
|
||||
@@ -18,7 +19,6 @@ import {
|
||||
Tooltip,
|
||||
} from "@calcom/ui";
|
||||
import { X } from "@calcom/ui/components/icon";
|
||||
import type { FormValues, Host } from "@calcom/web/pages/event-types/[type]";
|
||||
|
||||
export type CheckedSelectOption = {
|
||||
avatar: string;
|
||||
|
||||
@@ -20,6 +20,12 @@ export type AvailabilityOption = {
|
||||
export type EventTypeSetupProps = RouterOutputs["viewer"]["eventTypes"]["get"];
|
||||
export type EventTypeSetup = RouterOutputs["viewer"]["eventTypes"]["get"]["eventType"];
|
||||
export type Host = { isFixed: boolean; userId: number; priority: number };
|
||||
export type TeamMember = {
|
||||
value: string;
|
||||
label: string;
|
||||
avatar: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
export type FormValues = {
|
||||
id: number;
|
||||
|
||||
@@ -443,6 +443,8 @@ export const successRedirectUrl = z
|
||||
export const RoutingFormSettings = z
|
||||
.object({
|
||||
emailOwnerOnSubmission: z.boolean(),
|
||||
sendUpdatesTo: z.array(z.number()).optional(),
|
||||
sendToAll: z.boolean().optional(),
|
||||
})
|
||||
.nullable();
|
||||
|
||||
|
||||
Reference in new issue
Block a user