feat: Round Robin Weights (#15558)

* WIP

* add frontend

* backend to update weight

* UI improvements

* WIP weight algorithm

* enable weights switch + algorithm improvements

* fix weightDescription

* clean up code

* remove OOOEntryHost from schema.prisma

* implement logic (not yet tested)

* add tests for weight algorithm

* add test with weight adjustment

* finish unit tests

* fix type error

* fix type error

* add migration

* fix type error

* fix event type update handler

* fix failing test

* UI fixes for saving hosts

* make sure weightAdjustment is not lost on host changes

* fix weightadjustment for new hosts

* add weightAdjustment to availableUsers

* fix type errors

* fix default value for weight

* make weight and weightAdjustment optional

* fix type errors from schema changes

* type fix

* clean up code

* improve comments

* remove comment

* clean up code

* add tests & weight adjustment improvments

* better variable naming

* fixes for weight adjustments

* make weightAdjustments proportional to weights

* fix previous host weight adjustments

* improved tests for weight adjustments

* save weight and priority + sort hosts correctly

* fix type error

* code clean up

* remove console.log

* use BookingRepository to fetch bookings of users

* use BookingRepository to fetch bookings in getLuckyUser

* fix type errors

* fix weightAdjustment if changed from fixed to rr host

* disable weights when 'assign all' is enabled

* typo

* allow 0 weight

* set min (and max) for weight and priority

* use useWatch

* code clean up

* fix type error

* only count accepted bookings for RR

* fix type error

* improve data fetching of bookings

* only filter bookings of availableUsers

* code clean up form feedback

* fix tests

* don't count no show bookings

* code clean up

* choose user with highest weight

* use one reduce instead of two

* use reduce instead of filter and map

* don't show weights toggle when 'assign all' is enabled

* design fixes

* fix type errors

* fix: type check

* Update packages/features/eventtypes/components/AddMembersWithSwitch.tsx

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-08-15 15:01:15 +01:00
1 parent d60f165223
commit cd311f076c
29 files changed
+1249 -218

No files matched your search

@@ -46,6 +46,7 @@ const CheckedHostField = ({
value,
onChange,
helperText,
isRRWeightsEnabled,
...rest
}: {
labelText?: string;
@@ -55,6 +56,7 @@ const CheckedHostField = ({
onChange?: (options: Host[]) => void;
options?: Options<CheckedSelectOption>;
helperText?: React.ReactNode | string;
isRRWeightsEnabled?: boolean;
} & Omit<Partial<ComponentProps<typeof CheckedTeamSelect>>, "onChange" | "value">) => {
return (
<div className="flex flex-col rounded-md">
@@ -69,6 +71,8 @@ const CheckedHostField = ({
isFixed,
userId: parseInt(option.value, 10),
priority: option.priority ?? 2,
weight: option.weight ?? 100,
weightAdjustment: option.weightAdjustment ?? 0,
}))
);
}}
@@ -78,12 +82,14 @@ const CheckedHostField = ({
const option = options.find((member) => member.value === host.userId.toString());
if (!option) return acc;
acc.push({ ...option, priority: host.priority ?? 2, isFixed });
acc.push({ ...option, priority: host.priority ?? 2, isFixed, weight: host.weight ?? 100 });
return acc;
}, [] as CheckedSelectOption[])}
controlShouldRenderValue={false}
options={options}
placeholder={placeholder}
isRRWeightsEnabled={isRRWeightsEnabled}
{...rest}
/>
</div>
@@ -102,6 +108,7 @@ const AddMembersWithSwitch = ({
isFixed,
placeholder = "",
containerClassName = "",
isRRWeightsEnabled,
}: {
value: Host[];
onChange: (hosts: Host[]) => void;
@@ -113,13 +120,14 @@ const AddMembersWithSwitch = ({
isFixed: boolean;
placeholder?: string;
containerClassName?: string;
isRRWeightsEnabled?: 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 ${containerClassName}`}>
<div className={`flex flex-col rounded-md pb-2 pt-6 ${containerClassName}`}>
{automaticAddAllEnabled ? (
<div className="mb-2">
<AssignAllTeamMembers
@@ -139,6 +147,7 @@ const AddMembersWithSwitch = ({
isFixed={isFixed}
options={teamMembers.sort(sortByLabel)}
placeholder={placeholder ?? t("add_attendees")}
isRRWeightsEnabled={isRRWeightsEnabled}
/>
) : (
<></>
@@ -1,30 +1,20 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import { useFormContext } from "react-hook-form";
import type { Props } from "react-select";
import type { FormValues, Host } from "@calcom/features/eventtypes/lib/types";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import {
Avatar,
Button,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
Icon,
Label,
Select,
Tooltip,
} from "@calcom/ui";
import { Avatar, Button, Icon, Select, Tooltip } from "@calcom/ui";
import { PriorityDialog, WeightDialog } from "./HostEditDialogs";
export type CheckedSelectOption = {
avatar: string;
label: string;
value: string;
priority?: number;
weight?: number;
weightAdjustment?: number;
isFixed?: boolean;
disabled?: boolean;
};
@@ -32,12 +22,16 @@ export type CheckedSelectOption = {
export const CheckedTeamSelect = ({
options = [],
value = [],
isRRWeightsEnabled,
...props
}: Omit<Props<CheckedSelectOption, true>, "value" | "onChange"> & {
value?: readonly CheckedSelectOption[];
onChange: (value: readonly CheckedSelectOption[]) => void;
isRRWeightsEnabled?: boolean;
}) => {
const [priorityDialogOpen, setPriorityDialogOpen] = useState(false);
const [weightDialogOpen, setWeightDialogOpen] = useState(false);
const [currentOption, setCurrentOption] = useState(value[0] ?? null);
const { t } = useLocale();
@@ -68,20 +62,35 @@ export const CheckedTeamSelect = ({
<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>
<>
<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>
{isRRWeightsEnabled ? (
<Button
color="minimal"
className="mr-6 h-2 w-4 p-0 text-sm hover:bg-transparent"
onClick={() => {
setWeightDialogOpen(true);
setCurrentOption(option);
}}>
{option.weight ?? 100}%
</Button>
) : (
<></>
)}
</>
) : (
<></>
)}
@@ -89,7 +98,7 @@ export const CheckedTeamSelect = ({
<Icon
name="x"
onClick={() => props.onChange(value.filter((item) => item.value !== option.value))}
className="my-auto h-4 w-4"
className="my-auto ml-2 h-4 w-4"
/>
</div>
</li>
@@ -97,12 +106,20 @@ export const CheckedTeamSelect = ({
))}
</ul>
{currentOption && !currentOption.isFixed ? (
<PriorityDialog
isOpenDialog={priorityDialogOpen}
setIsOpenDialog={setPriorityDialogOpen}
option={currentOption}
onChange={props.onChange}
/>
<>
<PriorityDialog
isOpenDialog={priorityDialogOpen}
setIsOpenDialog={setPriorityDialogOpen}
option={currentOption}
onChange={props.onChange}
/>
<WeightDialog
isOpenDialog={weightDialogOpen}
setIsOpenDialog={setWeightDialogOpen}
option={currentOption}
onChange={props.onChange}
/>
</>
) : (
<></>
)}
@@ -110,67 +127,6 @@ export const CheckedTeamSelect = ({
);
};
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:
@@ -0,0 +1,172 @@
import { Trans } from "next-i18next";
import Link from "next/link";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import { useFormContext } from "react-hook-form";
import type { FormValues, Host } from "@calcom/features/eventtypes/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import {
Dialog,
DialogContent,
DialogFooter,
DialogClose,
Button,
Label,
Select,
TextField,
} from "@calcom/ui";
import type { CheckedSelectOption } from "./CheckedTeamSelect";
interface IDialog {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
option: CheckedSelectOption;
onChange: (value: readonly CheckedSelectOption[]) => void;
}
export const PriorityDialog = (props: IDialog) => {
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 isRRWeightsEnabled = getValues("isRRWeightsEnabled");
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,
weight: host.weight,
weightAdjustment: host.weightAdjustment,
};
});
const sortedHosts = updatedHosts.sort((a, b) => sortHosts(a, b, isRRWeightsEnabled));
onChange(sortedHosts);
}
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>
);
};
export const weightDescription = (
<Trans i18nKey="weights_description">
Weights determine how meetings are distributed among hosts.
<Link
className="underline underline-offset-2"
target="_blank"
href="https://cal.com/docs/enterprise-features/teams/round-robin-scheduling#weights">
Learn more
</Link>
</Trans>
);
export function sortHosts(
hostA: { priority: number | null; weight: number | null },
hostB: { priority: number | null; weight: number | null },
isRRWeightsEnabled: boolean
) {
const weightA = hostA.weight ?? 100;
const priorityA = hostA.priority ?? 2;
const weightB = hostB.weight ?? 100;
const priorityB = hostB.priority ?? 2;
if (isRRWeightsEnabled) {
if (weightA === weightB) {
return priorityB - priorityA;
} else {
return weightB - weightA;
}
} else {
return priorityB - priorityA;
}
}
export const WeightDialog = (props: IDialog) => {
const { t } = useLocale();
const { isOpenDialog, setIsOpenDialog, option, onChange } = props;
const { getValues } = useFormContext<FormValues>();
const [newWeight, setNewWeight] = useState<number>(100);
const setWeight = () => {
const hosts: Host[] = getValues("hosts");
const updatedHosts = hosts
.filter((host) => !host.isFixed)
.map((host) => {
return {
...option,
value: host.userId.toString(),
priority: host.priority,
weight: host.userId === parseInt(option.value, 10) ? newWeight : host.weight,
isFixed: false,
weightAdjustment: host.weightAdjustment,
};
});
const sortedHosts = updatedHosts.sort((a, b) => sortHosts(a, b, true));
onChange(sortedHosts);
setIsOpenDialog(false);
};
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
<DialogContent title={t("set_weight")} description={weightDescription}>
<div className="mb-4 mt-2">
<Label>{t("weight_for_user", { userName: option.label })}</Label>
<div className="w-36">
<TextField
required
min={0}
label={t("Weight")}
value={newWeight}
type="number"
onChange={(e) => setNewWeight(parseInt(e.target.value))}
addOnSuffix={<>%</>}
/>
</div>
</div>
<DialogFooter>
<DialogClose />
<Button onClick={setWeight}>{t("confirm")}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
+8 -1
View File
@@ -20,7 +20,13 @@ 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 Host = {
isFixed: boolean;
userId: number;
priority: number;
weight: number;
weightAdjustment: number;
};
export type TeamMember = {
value: string;
label: string;
@@ -122,6 +128,7 @@ export type FormValues = {
useEventTypeDestinationCalendarEmail: boolean;
forwardParamsSuccessRedirect: boolean | null;
secondaryEmailId?: number;
isRRWeightsEnabled: boolean;
};
export type LocationFormValues = Pick<FormValues, "id" | "locations" | "bookingFields" | "seatsPerTimeSlot">;