feat: round-robin priority ranking (#13566)

* improve design of assignment tab

* design fix

* add prioity dialog

* implement UI

* add backend to save priorities

* add priorty to rr algorithm + tests

* fix defaulValue for select + added translations

* add toggle for round robin fixed hosts

* don't show priorities for fixed hosts

* type fixes

* code clean up and type fixes

* clean up getValues and setValue

* code clean up

* fix tests

* code clean up

* fix undefined check

* allow null for priority

---------

Co-authored-by: CarinaWolli <[email protected]>
This commit is contained in:
Carina WollendorferandCarinaWolli authored and GitHub committed 2024-02-09 12:12:06 +00:00
1 parent 1ff2d51ee5
commit 296a367955
16 files changed
+601 -169

No files matched your search

+257 -139
View File
@@ -1,6 +1,6 @@
import { Trans } from "next-i18next";
import Link from "next/link";
import type { EventTypeSetupProps, FormValues } from "pages/event-types/[type]";
import type { EventTypeSetupProps, FormValues, Host } from "pages/event-types/[type]";
import { useEffect, useRef, useState } from "react";
import type { ComponentProps, Dispatch, SetStateAction } from "react";
import { Controller, useFormContext, useWatch } from "react-hook-form";
@@ -21,6 +21,13 @@ interface IUserToValue {
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})` : ""}`,
@@ -109,7 +116,7 @@ const AssignAllTeamMembers = ({
onInactive?: () => void;
}) => {
const { t } = useLocale();
const formMethods = useFormContext<FormValues>();
const { setValue } = useFormContext<FormValues>();
return (
<Controller<FormValues>
@@ -117,10 +124,10 @@ const AssignAllTeamMembers = ({
render={() => (
<SettingsToggle
title={t("automatically_add_all_team_members")}
description={t("including_people_who_join_in_future")}
labelClassName="mt-0.5 font-normal"
checked={assignAllTeamMembers}
onCheckedChange={(active) => {
formMethods.setValue("assignAllTeamMembers", active);
setValue("assignAllTeamMembers", active);
setAssignAllTeamMembers(active);
if (active) {
onActive();
@@ -128,7 +135,6 @@ const AssignAllTeamMembers = ({
onInactive();
}
}}
toggleSwitchAtTheEnd
/>
)}
/>
@@ -148,13 +154,13 @@ const CheckedHostField = ({
labelText?: string;
placeholder: string;
isFixed: boolean;
value: { isFixed: boolean; userId: number }[];
onChange?: (options: { isFixed: boolean; userId: number }[]) => void;
value: Host[];
onChange?: (options: Host[]) => void;
options?: Options<CheckedSelectOption>;
helperText?: React.ReactNode | string;
} & Omit<Partial<ComponentProps<typeof CheckedTeamSelect>>, "onChange" | "value">) => {
return (
<div className="bg-muted flex flex-col space-y-5 p-4">
<div className="flex flex-col rounded-md">
<div>
{labelText ? <Label>{labelText}</Label> : <></>}
<CheckedTeamSelect
@@ -165,23 +171,22 @@ const CheckedHostField = ({
options.map((option) => ({
isFixed,
userId: parseInt(option.value, 10),
priority: option.priority ?? 2,
}))
);
}}
value={(value || [])
.filter(({ isFixed: _isFixed }) => isFixed === _isFixed)
.map(
(host) =>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
options.find((member) => member.value === host.userId.toString())!
)
.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}
/>
{helperText && <p className="text-subtle text-sm">{helperText}</p>}
</div>
</div>
);
@@ -199,6 +204,156 @@ const FixedHostHelper = (
</Trans>
);
const FixedHosts = ({
teamMembers,
value,
onChange,
assignAllTeamMembers,
setAssignAllTeamMembers,
isRoundRobinEvent = false,
}: {
value: Host[];
onChange: (hosts: Host[]) => void;
teamMembers: TeamMember[];
assignAllTeamMembers: boolean;
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
isRoundRobinEvent?: boolean;
}) => {
const { t } = useLocale();
const { getValues, setValue } = useFormContext<FormValues>();
const hasActiveFixedHosts = isRoundRobinEvent && getValues("hosts").some((host) => host.isFixed);
const [isDisabled, setIsDisabled] = useState(hasActiveFixedHosts);
return (
<div className="mt-5 rounded-lg">
{!isRoundRobinEvent ? (
<>
<div className="border-subtle mt-5 rounded-t-md border p-6 pb-5">
<Label className="mb-1 text-sm font-semibold">{t("fixed_hosts")}</Label>
<p className="text-subtle max-w-full break-words text-sm leading-tight">{FixedHostHelper}</p>
</div>
<div className="border-subtle rounded-b-md border border-t-0">
<AddMembersWithSwitch
teamMembers={teamMembers}
value={value}
onChange={onChange}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
automaticAddAllEnabled={!isRoundRobinEvent}
isFixed={true}
onActive={() =>
setValue(
"hosts",
teamMembers.map((teamMember) => ({
isFixed: true,
userId: parseInt(teamMember.value, 10),
priority: 2,
}))
)
}
/>
</div>
</>
) : (
<SettingsToggle
toggleSwitchAtTheEnd={true}
title={t("fixed_hosts")}
description={FixedHostHelper}
checked={isDisabled}
labelClassName="text-sm"
descriptionClassName=" text-sm text-subtle"
onCheckedChange={(checked) => {
if (!checked) {
const rrHosts = getValues("hosts")
.filter((host) => !host.isFixed)
.sort((a, b) => (b.priority ?? 2) - (a.priority ?? 2));
setValue("hosts", rrHosts);
}
setIsDisabled(checked);
}}
childrenClassName="lg:ml-0">
<div className="border-subtle flex flex-col gap-6 rounded-bl-md rounded-br-md border border-t-0">
<AddMembersWithSwitch
teamMembers={teamMembers}
value={value}
onChange={onChange}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
automaticAddAllEnabled={!isRoundRobinEvent}
isFixed={true}
onActive={() =>
setValue(
"hosts",
teamMembers.map((teamMember) => ({
isFixed: true,
userId: parseInt(teamMember.value, 10),
priority: 2,
}))
)
}
/>
</div>
</SettingsToggle>
)}
</div>
);
};
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", [])}
/>
</div>
) : (
<></>
)}
{!assignAllTeamMembers || !automaticAddAllEnabled ? (
<CheckedHostField
value={value}
onChange={onChange}
isFixed={isFixed}
options={teamMembers.sort(sortByLabel)}
placeholder={t("add_attendees")}
/>
) : (
<></>
)}
</div>
</div>
);
};
const RoundRobinHosts = ({
teamMembers,
value,
@@ -206,68 +361,44 @@ const RoundRobinHosts = ({
assignAllTeamMembers,
setAssignAllTeamMembers,
}: {
value: { isFixed: boolean; userId: number }[];
onChange: (hosts: { isFixed: boolean; userId: number }[]) => void;
teamMembers: {
value: string;
label: string;
avatar: string;
email: string;
}[];
value: Host[];
onChange: (hosts: Host[]) => void;
teamMembers: TeamMember[];
assignAllTeamMembers: boolean;
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
}) => {
const { t } = useLocale();
const formMethods = useFormContext<FormValues>();
const { setValue } = useFormContext<FormValues>();
return (
<div className="border-subtle mt-6 space-y-5 rounded-lg border px-4 py-6 sm:px-6">
<div className="flex flex-col gap-8">
<CheckedHostField
options={teamMembers.sort(sortByLabel)}
isFixed={true}
onChange={(changeValue) => {
onChange([...value.filter(({ isFixed }) => !isFixed), ...changeValue]);
}}
<div className="rounded-lg ">
<div className="border-subtle mt-5 rounded-t-md border p-6 pb-5">
<Label className="mb-1 text-sm font-semibold">{t("round_robin_hosts")}</Label>
<p className="text-subtle max-w-full break-words text-sm leading-tight">{t("round_robin_helper")}</p>
</div>
<div className="border-subtle rounded-b-md border border-t-0">
<AddMembersWithSwitch
teamMembers={teamMembers}
value={value}
placeholder={t("add_fixed_hosts")}
labelText={t("fixed_hosts")}
helperText={FixedHostHelper}
onChange={onChange}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
automaticAddAllEnabled={true}
isFixed={false}
onActive={() =>
setValue(
"hosts",
teamMembers
.map((teamMember) => ({
isFixed: false,
userId: parseInt(teamMember.value, 10),
priority: 2,
}))
.sort((a, b) => b.priority - a.priority)
)
}
/>
<div className="bg-muted flex flex-col">
<Label className="p-4">{t("round_robin_hosts")}</Label>
<div className="px-4 pb-2">
<AssignAllTeamMembers
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
onActive={() =>
formMethods.setValue(
"hosts",
teamMembers.map((teamMember) => ({
isFixed: false,
userId: parseInt(teamMember.value, 10),
}))
)
}
onInactive={() => formMethods.setValue("hosts", [])}
/>
</div>
{assignAllTeamMembers ? (
<div className="mb-4" />
) : (
<CheckedHostField
options={teamMembers.sort(sortByLabel)}
onChange={(changeValue) =>
onChange([...value.filter(({ isFixed }) => isFixed), ...changeValue])
}
value={value}
isFixed={false}
placeholder={t("add_attendees")}
helperText={t("round_robin_helper")}
/>
)}
</div>
</div>
</div>
);
@@ -282,14 +413,14 @@ const ChildrenEventTypes = ({
assignAllTeamMembers: boolean;
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
}) => {
const formMethods = useFormContext<FormValues>();
const { setValue } = useFormContext<FormValues>();
return (
<div className="border-subtle mt-6 space-y-5 rounded-lg border px-4 py-6 sm:px-6">
<div className="flex flex-col gap-4">
<AssignAllTeamMembers
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
onActive={() => formMethods.setValue("children", childrenEventTypeOptions)}
onActive={() => setValue("children", childrenEventTypeOptions)}
/>
{!assignAllTeamMembers ? (
<Controller<FormValues>
@@ -311,12 +442,7 @@ const Hosts = ({
assignAllTeamMembers,
setAssignAllTeamMembers,
}: {
teamMembers: {
value: string;
label: string;
avatar: string;
email: string;
}[];
teamMembers: TeamMember[];
assignAllTeamMembers: boolean;
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
}) => {
@@ -348,61 +474,45 @@ const Hosts = ({
});
}, [schedulingType, resetField, getValues, submitCount]);
const formMethods = useFormContext<FormValues>();
return (
<Controller<FormValues>
name="hosts"
render={({ field: { onChange, value } }) => {
const schedulingTypeRender = {
COLLECTIVE: (
<div className="border-subtle mt-6 space-y-5 rounded-lg border px-4 py-6 sm:px-6">
<div className="flex flex-col gap-4">
<AssignAllTeamMembers
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
onActive={() =>
formMethods.setValue(
"hosts",
teamMembers.map((teamMember) => ({
isFixed: true,
userId: parseInt(teamMember.value, 10),
}))
)
}
onInactive={() => formMethods.setValue("hosts", [])}
/>
{assignAllTeamMembers ? (
<></>
) : (
<CheckedHostField
value={value}
onChange={onChange}
isFixed={true}
options={teamMembers.sort(sortByLabel)}
placeholder={t("add_attendees")}
labelText={t("team")}
/>
)}
</div>
</div>
<FixedHosts
teamMembers={teamMembers}
value={value}
onChange={onChange}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
/>
),
ROUND_ROBIN: (
<>
<FixedHosts
teamMembers={teamMembers}
value={value}
onChange={(changeValue) => {
onChange([...value.filter((host: Host) => !host.isFixed), ...changeValue]);
}}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
isRoundRobinEvent={true}
/>
<RoundRobinHosts
teamMembers={teamMembers}
value={value}
onChange={(changeValue) => {
onChange(
[...value.filter((host: Host) => host.isFixed), ...changeValue].sort(
(a, b) => b.priority - a.priority
)
);
}}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
teamMembers={teamMembers}
onChange={onChange}
value={value}
/>
{/*<TextField
required
type="number"
label={t("minimum_round_robin_hosts_count")}
defaultValue={1}
{...formMethods.register("minimumHostCount")}
addOnSuffix={<>{t("hosts")}</>}
/>*/}
</>
),
MANAGED: <></>,
@@ -449,39 +559,47 @@ export const EventTeamTab = ({
);
});
const isManagedEventType = eventType.schedulingType === SchedulingType.MANAGED;
const formMethods = useFormContext<FormValues>();
const { getValues, setValue } = useFormContext<FormValues>();
const [assignAllTeamMembers, setAssignAllTeamMembers] = useState<boolean>(
formMethods.getValues("assignAllTeamMembers") ?? false
getValues("assignAllTeamMembers") ?? false
);
return (
<div>
{team && !isManagedEventType && (
<div className="space-y-5">
<div className="flex flex-col">
<Label>{t("scheduling_type")}</Label>
<Controller<FormValues>
name="schedulingType"
render={({ field: { value, onChange } }) => (
<Select
options={schedulingTypeOptions}
value={schedulingTypeOptions.find((opt) => opt.value === value)}
className="w-full"
onChange={(val) => {
onChange(val?.value);
formMethods.setValue("assignAllTeamMembers", false);
setAssignAllTeamMembers(false);
}}
/>
)}
/>
<>
<div className="border-subtle flex flex-col rounded-md">
<div className="border-subtle rounded-t-md border p-6 pb-5">
<Label className="mb-1 text-sm font-semibold">{t("assignment")}</Label>
<p className="text-subtle max-w-full break-words text-sm leading-tight">
{t("assignment_description")}
</p>
</div>
<div className="border-subtle rounded-b-md border border-t-0 p-6">
<Label>{t("scheduling_type")}</Label>
<Controller<FormValues>
name="schedulingType"
render={({ field: { value, onChange } }) => (
<Select
options={schedulingTypeOptions}
value={schedulingTypeOptions.find((opt) => opt.value === value)}
className="w-full"
onChange={(val) => {
onChange(val?.value);
setValue("assignAllTeamMembers", false);
setAssignAllTeamMembers(false);
}}
/>
)}
/>
</div>
</div>
<Hosts
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
teamMembers={teamMembersOptions}
/>
</div>
</>
)}
{team && isManagedEventType && (
<ChildrenEventTypes
@@ -82,6 +82,8 @@ const EventWebhooksTab = dynamic(() =>
const ManagedEventTypeDialog = dynamic(() => import("@components/eventtype/ManagedEventDialog"));
export type Host = { isFixed: boolean; userId: number; priority: number };
export type FormValues = {
id: number;
title: string;
@@ -139,7 +141,7 @@ export type FormValues = {
bookingLimits?: IntervalLimit;
onlyShowFirstAvailableSlot: boolean;
children: ChildrenEventType[];
hosts: { userId: number; isFixed: boolean }[];
hosts: Host[];
bookingFields: z.infer<typeof eventTypeBookingFields>;
availability?: AvailabilityOption;
bookerLayouts: BookerLayoutSettings;
@@ -424,7 +426,6 @@ const EventTypePage = (props: EventTypeSetupProps) => {
const permalink = `${CAL_URL}/${team ? `team/${team.slug}` : eventType.users[0].username}/${
eventType.slug
}`;
const tabMap = {
setup: (
<EventSetupTab
@@ -8,6 +8,7 @@ export type {
EventTypeSetup,
EventTypeSetupProps,
FormValues,
Host,
} from "~/event-types/views/event-types-single-view";
EventTypePageWrapper.PageWrapper = PageWrapper;
+10 -2
View File
@@ -2244,12 +2244,20 @@
"add_a_redirect": "Add a redirect",
"create_entry": "Create entry",
"time_range": "Time range",
"automatically_add_all_team_members": "Automatically add all team members",
"including_people_who_join_in_future": "Including people who join the team in the future",
"automatically_add_all_team_members": "Add all team members, including future members",
"redirect_to": "Redirect to",
"having_trouble_finding_time": "Having trouble finding a time?",
"show_more": "Show more",
"assignment_description":"Schedule meetings when everyone is available or rotate through members on your team",
"lowest": "lowest",
"low": "low",
"medium": "medium",
"high": "high",
"Highest": "highest",
"send_booker_to": "Send Booker to",
"set_priority": "Set Priority",
"priority_for_user": "Priority for {{userName}}",
"change_priority": "change priority",
"account_already_linked": "Account is already linked",
"ADD_NEW_STRINGS_ABOVE_THIS_LINE_TO_PREVENT_MERGE_CONFLICTS": "↑↑↑↑↑↑↑↑↑↑↑↑↑ Add your new strings above here ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑"
}
@@ -2244,8 +2244,6 @@
"add_a_redirect": "הוספת הפנייה",
"create_entry": "יצירת רשומה",
"time_range": "טווח זמן",
"automatically_add_all_team_members": "הוספת כל חברי הצוות אוטומטית",
"including_people_who_join_in_future": "כולל אנשים שיצטרפו לצוות בעתיד",
"redirect_to": "הפניה אל",
"having_trouble_finding_time": "לא הצלחת למצוא חלון זמן פנוי?",
"show_more": "הצג עוד",
+150 -2
View File
@@ -8,8 +8,8 @@ import { buildUser } from "@calcom/lib/test/builder";
it("can find lucky user with maximize availability", async () => {
const user1 = buildUser({
id: 1,
username: "test",
name: "Test User",
username: "test1",
name: "Test User 1",
email: "[email protected]",
bookings: [
{
@@ -43,3 +43,151 @@ it("can find lucky user with maximize availability", async () => {
})
).resolves.toStrictEqual(users[1]);
});
it("can find lucky user with maximize availability and priority ranking", async () => {
const user1 = buildUser({
id: 1,
username: "test1",
name: "Test User 1",
email: "[email protected]",
priority: 2,
bookings: [
{
createdAt: new Date("2022-01-25T05:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T06:30:00.000Z"),
},
],
});
const user2 = buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
bookings: [
{
createdAt: new Date("2022-01-25T04:30:00.000Z"),
},
],
});
const users = [user1, user2];
// TODO: we may be able to use native prisma generics somehow?
prismaMock.user.findMany.mockResolvedValue(users);
prismaMock.booking.findMany.mockResolvedValue([]);
const test = await getLuckyUser("MAXIMIZE_AVAILABILITY", {
availableUsers: users,
eventTypeId: 1,
});
// both users have medium priority (one user has no priority set, default to medium) so pick least recently booked
await expect(
getLuckyUser("MAXIMIZE_AVAILABILITY", {
availableUsers: users,
eventTypeId: 1,
})
).resolves.toStrictEqual(users[1]);
const userLowest = buildUser({
id: 1,
username: "test1",
name: "Test User 1",
email: "[email protected]",
priority: 0,
bookings: [
{
createdAt: new Date("2022-01-25T03:30:00.000Z"),
},
],
});
const userMedium = buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
priority: 2,
bookings: [
{
createdAt: new Date("2022-01-25T04:30:00.000Z"),
},
],
});
const userHighest = buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
priority: 4,
bookings: [
{
createdAt: new Date("2022-01-25T05:30:00.000Z"),
},
],
});
const usersWithPriorities = [userLowest, userMedium, userHighest];
// TODO: we may be able to use native prisma generics somehow?
prismaMock.user.findMany.mockResolvedValue(usersWithPriorities);
prismaMock.booking.findMany.mockResolvedValue([]);
// pick the user with the highest priority
await expect(
getLuckyUser("MAXIMIZE_AVAILABILITY", {
availableUsers: usersWithPriorities,
eventTypeId: 1,
})
).resolves.toStrictEqual(usersWithPriorities[2]);
const userLow = buildUser({
id: 1,
username: "test1",
name: "Test User 1",
email: "[email protected]",
priority: 0,
bookings: [
{
createdAt: new Date("2022-01-25T02:30:00.000Z"),
},
],
});
const userHighLeastRecentBooking = buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
priority: 3,
bookings: [
{
createdAt: new Date("2022-01-25T03:30:00.000Z"),
},
],
});
const userHighRecentBooking = buildUser({
id: 3,
username: "test3",
name: "Test User 3",
email: "[email protected]",
priority: 3,
bookings: [
{
createdAt: new Date("2022-01-25T04:30:00.000Z"),
},
],
});
const usersWithSamePriorities = [userLow, userHighLeastRecentBooking, userHighRecentBooking];
// TODO: we may be able to use native prisma generics somehow?
prismaMock.user.findMany.mockResolvedValue(usersWithSamePriorities);
prismaMock.booking.findMany.mockResolvedValue([]);
// pick the least recently booked user of the two with the highest priority
await expect(
getLuckyUser("MAXIMIZE_AVAILABILITY", {
availableUsers: usersWithSamePriorities,
eventTypeId: 1,
})
).resolves.toStrictEqual(usersWithSamePriorities[1]);
});
@@ -367,6 +367,7 @@ export const getEventTypesFromDB = async (eventTypeId: number) => {
hosts: {
select: {
isFixed: true,
priority: true,
user: {
select: {
credentials: {
@@ -403,6 +404,7 @@ type IsFixedAwareUser = User & {
isFixed: boolean;
credentials: CredentialPayload[];
organization: { slug: string };
priority?: number;
};
const loadUsers = async (eventType: NewBookingEventType, dynamicUserList: string[], req: IncomingMessage) => {
@@ -425,9 +427,10 @@ const loadUsers = async (eventType: NewBookingEventType, dynamicUserList: string
throw new Error("eventType.hosts is not properly defined.");
}
const users = hosts.map(({ user, isFixed }) => ({
const users = hosts.map(({ user, isFixed, priority }) => ({
...user,
isFixed,
priority,
}));
return users.length ? users : eventType.users;
@@ -448,7 +451,6 @@ export async function ensureAvailableUsers(
) {
const availableUsers: IsFixedAwareUser[] = [];
const duration = dayjs(input.dateTo).diff(input.dateFrom, "minute");
const originalBookingDuration = input.originalRescheduledBooking
? dayjs(input.originalRescheduledBooking.endTime).diff(
dayjs(input.originalRescheduledBooking.startTime),
@@ -1325,7 +1327,6 @@ async function handler(
},
loggerWithEventDetails
);
const luckyUsers: typeof users = [];
const luckyUserPool = availableUsers.filter((user) => !user.isFixed);
const notAvailableLuckyUsers: typeof users = [];
@@ -1,15 +1,31 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { useState } from "react";
import type { Dispatch, SetStateAction } from "react";
import { useFormContext } from "react-hook-form";
import type { Props } from "react-select";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Avatar, Select } from "@calcom/ui";
import {
Avatar,
Button,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
Label,
Select,
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;
label: string;
value: string;
priority?: number;
isFixed?: boolean;
disabled?: boolean;
};
@@ -21,8 +37,10 @@ export const CheckedTeamSelect = ({
value?: readonly CheckedSelectOption[];
onChange: (value: readonly CheckedSelectOption[]) => void;
}) => {
const { t } = useLocale();
const [priorityDialogOpen, setPriorityDialogOpen] = useState(false);
const [currentOption, setCurrentOption] = useState(value[0] ?? null);
const { t } = useLocale();
const [animationRef] = useAutoAnimate<HTMLUListElement>();
return (
@@ -39,23 +57,134 @@ export const CheckedTeamSelect = ({
{/* 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("mb-1 mt-3 rounded-md", value.length >= 1 && "border-subtle border")}
className={classNames("mb-4 mt-3 rounded-md", value.length >= 1 && "border-subtle border")}
ref={animationRef}>
{value.map((option, index) => (
<li
key={option.value}
className={`flex px-3 py-2 ${index === value.length - 1 ? "" : "border-subtle border-b"}`}>
<Avatar size="sm" imageSrc={option.avatar} alt={option.label} />
<p className="text-emphasis my-auto ms-3 text-sm">{option.label}</p>
<X
onClick={() => props.onChange(value.filter((item) => item.value !== option.value))}
className="my-auto ml-auto h-4 w-4"
/>
</li>
<>
<li
key={option.value}
className={`flex px-3 py-2 ${index === value.length - 1 ? "" : "border-subtle border-b"}`}>
<Avatar size="sm" imageSrc={option.avatar} alt={option.label} />
<p className="text-emphasis my-auto ms-3 text-sm">{option.label}</p>
<div className="ml-auto flex items-center">
{option && !option.isFixed ? (
<Tooltip content={t("change_priority")}>
<Button
color="minimal"
onClick={() => {
setPriorityDialogOpen(true);
setCurrentOption(option);
}}
className={classNames(
"mr-6 h-2 p-0 text-sm hover:bg-transparent",
getPriorityTextAndColor(option.priority).color
)}>
{t(getPriorityTextAndColor(option.priority).text)}
</Button>
</Tooltip>
) : (
<></>
)}
<X
onClick={() => props.onChange(value.filter((item) => item.value !== option.value))}
className="my-auto h-4 w-4"
/>
</div>
</li>
</>
))}
</ul>
{currentOption && !currentOption.isFixed ? (
<PriorityDialog
isOpenDialog={priorityDialogOpen}
setIsOpenDialog={setPriorityDialogOpen}
option={currentOption}
onChange={props.onChange}
/>
) : (
<></>
)}
</>
);
};
interface IPriiorityDialog {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
option: CheckedSelectOption;
onChange: (value: readonly CheckedSelectOption[]) => void;
}
const PriorityDialog = (props: IPriiorityDialog) => {
const { t } = useLocale();
const { isOpenDialog, setIsOpenDialog, option, onChange } = props;
const { getValues } = useFormContext<FormValues>();
const priorityOptions = [
{ label: t("lowest"), value: 0 },
{ label: t("low"), value: 1 },
{ label: t("medium"), value: 2 },
{ label: t("high"), value: 3 },
{ label: t("highest"), value: 4 },
];
const [newPriority, setNewPriority] = useState<{ label: string; value: number }>();
const setPriority = () => {
if (!!newPriority) {
const hosts: Host[] = getValues("hosts");
const updatedHosts = hosts
.filter((host) => !host.isFixed)
.map((host) => {
return {
...option,
value: host.userId.toString(),
priority: host.userId === parseInt(option.value, 10) ? newPriority.value : host.priority,
isFixed: false,
};
})
.sort((a, b) => b.priority ?? 2 - a.priority ?? 2);
onChange(updatedHosts);
}
setIsOpenDialog(false);
};
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
<DialogContent title={t("set_priority")}>
<div className="mb-4">
<Label>{t("priority_for_user", { userName: option.label })}</Label>
<Select
defaultValue={priorityOptions[option.priority ?? 2]}
value={newPriority}
onChange={(value) => setNewPriority(value ?? priorityOptions[2])}
options={priorityOptions}
/>
</div>
<DialogFooter>
<DialogClose />
<Button onClick={setPriority}>{t("confirm")}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
const getPriorityTextAndColor = (priority?: number) => {
switch (priority) {
case 0:
return { text: "lowest", color: "text-gray-300" };
case 1:
return { text: "low", color: "text-gray-400" };
case 2:
return { text: "medium", color: "text-gray-500" };
case 3:
return { text: "high", color: "text-gray-600" };
case 4:
return { text: "highest", color: "text-gray-700" };
default:
return { text: "medium", color: "text-gray-500" };
}
};
export default CheckedTeamSelect;
+1
View File
@@ -166,6 +166,7 @@ export default async function getEventTypeById({
select: {
isFixed: true,
userId: true,
priority: true,
},
},
userId: true,
+15 -2
View File
@@ -102,9 +102,21 @@ async function leastRecentlyBookedUser<T extends Pick<User, "id" | "email">>({
return leastRecentlyBookedUser;
}
function getUsersWithHighestPriority<T extends Pick<User, "id" | "email"> & { priority?: number | null }>({
availableUsers,
}: {
availableUsers: T[];
}) {
const highestPriority = Math.max(...availableUsers.map((user) => user.priority ?? 2));
return availableUsers.filter(
(user) => user.priority === highestPriority || (user.priority == null && highestPriority === 2)
);
}
// TODO: Configure distributionAlgorithm from the event type configuration
// TODO: Add 'MAXIMIZE_FAIRNESS' algorithm.
export async function getLuckyUser<T extends Pick<User, "id" | "email">>(
export async function getLuckyUser<T extends Pick<User, "id" | "email"> & { priority?: number | null }>(
distributionAlgorithm: "MAXIMIZE_AVAILABILITY" = "MAXIMIZE_AVAILABILITY",
{ availableUsers, eventTypeId }: { availableUsers: T[]; eventTypeId: number }
) {
@@ -113,6 +125,7 @@ export async function getLuckyUser<T extends Pick<User, "id" | "email">>(
}
switch (distributionAlgorithm) {
case "MAXIMIZE_AVAILABILITY":
return leastRecentlyBookedUser<T>({ availableUsers, eventTypeId });
const highestPriorityUsers = getUsersWithHighestPriority({ availableUsers });
return leastRecentlyBookedUser<T>({ availableUsers: highestPriorityUsers, eventTypeId });
}
}
+4 -1
View File
@@ -190,7 +190,9 @@ type UserPayload = Prisma.UserGetPayload<{
schedules: true;
};
}>;
export const buildUser = <T extends Partial<UserPayload>>(user?: T): UserPayload => {
export const buildUser = <T extends Partial<UserPayload>>(
user?: T & { priority?: number }
): UserPayload & { priority: number | null } => {
return {
locked: false,
name: faker.name.firstName(),
@@ -238,6 +240,7 @@ export const buildUser = <T extends Partial<UserPayload>>(user?: T): UserPayload
allowSEOIndexing: null,
receiveMonthlyDigestEmail: null,
movedToProfileId: null,
priority: user?.priority ?? null,
...user,
};
};
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Host" ADD COLUMN "priority" INTEGER;
+1
View File
@@ -41,6 +41,7 @@ model Host {
eventType EventType @relation(fields: [eventTypeId], references: [id], onDelete: Cascade)
eventTypeId Int
isFixed Boolean @default(false)
priority Int?
@@id([userId, eventTypeId])
@@index([userId])
@@ -35,6 +35,7 @@ export const EventTypeUpdateInput = _EventTypeModel
userId: z.number(),
profileId: z.number().or(z.null()).optional(),
isFixed: z.boolean().optional(),
priority: z.number().optional().nullable(),
})
)
.optional(),
@@ -226,6 +226,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
return {
...rest,
isFixed: data.schedulingType === SchedulingType.COLLECTIVE || host.isFixed,
priority: host.priority ?? 2, // default to medium priority
};
}),
};
@@ -9,7 +9,7 @@ import Switch from "./Switch";
type Props = {
children?: ReactNode;
title: string;
description?: string;
description?: string | React.ReactNode;
checked: boolean;
disabled?: boolean;
LockedIcon?: React.ReactNode;
@@ -21,6 +21,7 @@ type Props = {
childrenClassName?: string;
switchContainerClassName?: string;
labelClassName?: string;
descriptionClassName?: string;
};
function SettingsToggle({
@@ -37,6 +38,7 @@ function SettingsToggle({
childrenClassName,
switchContainerClassName,
labelClassName,
descriptionClassName,
...rest
}: Props) {
const [animateRef] = useAutoAnimate<HTMLDivElement>();
@@ -63,7 +65,10 @@ function SettingsToggle({
</div>
{description && (
<p
className="text-default -mt-1.5 text-sm leading-normal"
className={classNames(
"text-default -mt-1.5 text-sm leading-normal",
descriptionClassName
)}
data-testid={`${rest["data-testid"]}-description`}>
{description}
</p>
@@ -92,7 +97,8 @@ function SettingsToggle({
/>
<div>
<Label className="text-emphasis text-sm font-semibold leading-none">
<Label
className={classNames("text-emphasis text-sm font-semibold leading-none", labelClassName)}>
{title}
{LockedIcon}
</Label>