From 296a3679558646946c55756eb616fd48fcf041c0 Mon Sep 17 00:00:00 2001 From: Carina Wollendorfer <30310907+CarinaWolli@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:12:06 -0500 Subject: [PATCH] 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 --- .../web/components/eventtype/EventTeamTab.tsx | 396 ++++++++++++------ .../views/event-types-single-view.tsx | 5 +- apps/web/pages/event-types/[type]/index.tsx | 1 + apps/web/public/static/locales/en/common.json | 12 +- apps/web/public/static/locales/he/common.json | 2 - apps/web/test/lib/team-event-types.test.ts | 152 ++++++- .../features/bookings/lib/handleNewBooking.ts | 7 +- .../components/CheckedTeamSelect.tsx | 155 ++++++- packages/lib/getEventTypeById.ts | 1 + packages/lib/server/getLuckyUser.ts | 17 +- packages/lib/test/builder.ts | 5 +- .../migration.sql | 2 + packages/prisma/schema.prisma | 1 + .../server/routers/viewer/eventTypes/types.ts | 1 + .../viewer/eventTypes/update.handler.ts | 1 + .../components/form/switch/SettingsToggle.tsx | 12 +- 16 files changed, 601 insertions(+), 169 deletions(-) create mode 100644 packages/prisma/migrations/20240206162624_add_priority_field_to_host/migration.sql diff --git a/apps/web/components/eventtype/EventTeamTab.tsx b/apps/web/components/eventtype/EventTeamTab.tsx index 74959c6d58..fd5568eec7 100644 --- a/apps/web/components/eventtype/EventTeamTab.tsx +++ b/apps/web/components/eventtype/EventTeamTab.tsx @@ -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(); + const { setValue } = useFormContext(); return ( @@ -117,10 +124,10 @@ const AssignAllTeamMembers = ({ render={() => ( { - 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; helperText?: React.ReactNode | string; } & Omit>, "onChange" | "value">) => { return ( -
+
{labelText ? : <>} ({ 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 &&

{helperText}

}
); @@ -199,6 +204,156 @@ const FixedHostHelper = ( ); +const FixedHosts = ({ + teamMembers, + value, + onChange, + assignAllTeamMembers, + setAssignAllTeamMembers, + isRoundRobinEvent = false, +}: { + value: Host[]; + onChange: (hosts: Host[]) => void; + teamMembers: TeamMember[]; + assignAllTeamMembers: boolean; + setAssignAllTeamMembers: Dispatch>; + isRoundRobinEvent?: boolean; +}) => { + const { t } = useLocale(); + const { getValues, setValue } = useFormContext(); + + const hasActiveFixedHosts = isRoundRobinEvent && getValues("hosts").some((host) => host.isFixed); + + const [isDisabled, setIsDisabled] = useState(hasActiveFixedHosts); + + return ( +
+ {!isRoundRobinEvent ? ( + <> +
+ +

{FixedHostHelper}

+
+
+ + setValue( + "hosts", + teamMembers.map((teamMember) => ({ + isFixed: true, + userId: parseInt(teamMember.value, 10), + priority: 2, + })) + ) + } + /> +
+ + ) : ( + { + 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"> +
+ + setValue( + "hosts", + teamMembers.map((teamMember) => ({ + isFixed: true, + userId: parseInt(teamMember.value, 10), + priority: 2, + })) + ) + } + /> +
+
+ )} +
+ ); +}; + +const AddMembersWithSwitch = ({ + teamMembers, + value, + onChange, + assignAllTeamMembers, + setAssignAllTeamMembers, + automaticAddAllEnabled, + onActive, + isFixed, +}: { + value: Host[]; + onChange: (hosts: Host[]) => void; + teamMembers: TeamMember[]; + assignAllTeamMembers: boolean; + setAssignAllTeamMembers: Dispatch>; + automaticAddAllEnabled: boolean; + onActive: () => void; + isFixed: boolean; +}) => { + const { t } = useLocale(); + const { setValue } = useFormContext(); + + return ( +
+
+ {automaticAddAllEnabled ? ( +
+ setValue("hosts", [])} + /> +
+ ) : ( + <> + )} + {!assignAllTeamMembers || !automaticAddAllEnabled ? ( + + ) : ( + <> + )} +
+
+ ); +}; + 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>; }) => { const { t } = useLocale(); - const formMethods = useFormContext(); + + const { setValue } = useFormContext(); return ( -
-
- { - onChange([...value.filter(({ isFixed }) => !isFixed), ...changeValue]); - }} +
+
+ +

{t("round_robin_helper")}

+
+
+ + setValue( + "hosts", + teamMembers + .map((teamMember) => ({ + isFixed: false, + userId: parseInt(teamMember.value, 10), + priority: 2, + })) + .sort((a, b) => b.priority - a.priority) + ) + } /> - -
- -
- - formMethods.setValue( - "hosts", - teamMembers.map((teamMember) => ({ - isFixed: false, - userId: parseInt(teamMember.value, 10), - })) - ) - } - onInactive={() => formMethods.setValue("hosts", [])} - /> -
- {assignAllTeamMembers ? ( -
- ) : ( - - onChange([...value.filter(({ isFixed }) => isFixed), ...changeValue]) - } - value={value} - isFixed={false} - placeholder={t("add_attendees")} - helperText={t("round_robin_helper")} - /> - )} -
); @@ -282,14 +413,14 @@ const ChildrenEventTypes = ({ assignAllTeamMembers: boolean; setAssignAllTeamMembers: Dispatch>; }) => { - const formMethods = useFormContext(); + const { setValue } = useFormContext(); return (
formMethods.setValue("children", childrenEventTypeOptions)} + onActive={() => setValue("children", childrenEventTypeOptions)} /> {!assignAllTeamMembers ? ( @@ -311,12 +442,7 @@ const Hosts = ({ assignAllTeamMembers, setAssignAllTeamMembers, }: { - teamMembers: { - value: string; - label: string; - avatar: string; - email: string; - }[]; + teamMembers: TeamMember[]; assignAllTeamMembers: boolean; setAssignAllTeamMembers: Dispatch>; }) => { @@ -348,61 +474,45 @@ const Hosts = ({ }); }, [schedulingType, resetField, getValues, submitCount]); - const formMethods = useFormContext(); return ( name="hosts" render={({ field: { onChange, value } }) => { const schedulingTypeRender = { COLLECTIVE: ( -
-
- - formMethods.setValue( - "hosts", - teamMembers.map((teamMember) => ({ - isFixed: true, - userId: parseInt(teamMember.value, 10), - })) - ) - } - onInactive={() => formMethods.setValue("hosts", [])} - /> - {assignAllTeamMembers ? ( - <> - ) : ( - - )} -
-
+ ), ROUND_ROBIN: ( <> + { + onChange([...value.filter((host: Host) => !host.isFixed), ...changeValue]); + }} + assignAllTeamMembers={assignAllTeamMembers} + setAssignAllTeamMembers={setAssignAllTeamMembers} + isRoundRobinEvent={true} + /> { + 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} /> - {/*{t("hosts")}} - />*/} ), MANAGED: <>, @@ -449,39 +559,47 @@ export const EventTeamTab = ({ ); }); const isManagedEventType = eventType.schedulingType === SchedulingType.MANAGED; - const formMethods = useFormContext(); + const { getValues, setValue } = useFormContext(); const [assignAllTeamMembers, setAssignAllTeamMembers] = useState( - formMethods.getValues("assignAllTeamMembers") ?? false + getValues("assignAllTeamMembers") ?? false ); return (
{team && !isManagedEventType && ( -
-
- - - name="schedulingType" - render={({ field: { value, onChange } }) => ( - opt.value === value)} + className="w-full" + onChange={(val) => { + onChange(val?.value); + setValue("assignAllTeamMembers", false); + setAssignAllTeamMembers(false); + }} + /> + )} + /> +
-
+ )} {team && isManagedEventType && ( 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; 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: ( { const user1 = buildUser({ id: 1, - username: "test", - name: "Test User", + username: "test1", + name: "Test User 1", email: "test@example.com", 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: "test@example.com", + 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: "tes2t@example.com", + 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: "test@example.com", + priority: 0, + bookings: [ + { + createdAt: new Date("2022-01-25T03:30:00.000Z"), + }, + ], + }); + const userMedium = buildUser({ + id: 2, + username: "test2", + name: "Test User 2", + email: "tes2t@example.com", + priority: 2, + bookings: [ + { + createdAt: new Date("2022-01-25T04:30:00.000Z"), + }, + ], + }); + + const userHighest = buildUser({ + id: 2, + username: "test2", + name: "Test User 2", + email: "tes2t@example.com", + 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: "test@example.com", + priority: 0, + bookings: [ + { + createdAt: new Date("2022-01-25T02:30:00.000Z"), + }, + ], + }); + const userHighLeastRecentBooking = buildUser({ + id: 2, + username: "test2", + name: "Test User 2", + email: "tes2t@example.com", + priority: 3, + bookings: [ + { + createdAt: new Date("2022-01-25T03:30:00.000Z"), + }, + ], + }); + + const userHighRecentBooking = buildUser({ + id: 3, + username: "test3", + name: "Test User 3", + email: "test3t@example.com", + 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]); +}); diff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/handleNewBooking.ts index d61684655a..0b1a10473e 100644 --- a/packages/features/bookings/lib/handleNewBooking.ts +++ b/packages/features/bookings/lib/handleNewBooking.ts @@ -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 = []; diff --git a/packages/features/eventtypes/components/CheckedTeamSelect.tsx b/packages/features/eventtypes/components/CheckedTeamSelect.tsx index 930b3f466e..f1bdebb943 100644 --- a/packages/features/eventtypes/components/CheckedTeamSelect.tsx +++ b/packages/features/eventtypes/components/CheckedTeamSelect.tsx @@ -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(); 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*/}
    = 1 && "border-subtle border")} + className={classNames("mb-4 mt-3 rounded-md", value.length >= 1 && "border-subtle border")} ref={animationRef}> {value.map((option, index) => ( -
  • - -

    {option.label}

    - props.onChange(value.filter((item) => item.value !== option.value))} - className="my-auto ml-auto h-4 w-4" - /> -
  • + <> +
  • + +

    {option.label}

    +
    + {option && !option.isFixed ? ( + + + + ) : ( + <> + )} + + props.onChange(value.filter((item) => item.value !== option.value))} + className="my-auto h-4 w-4" + /> +
    +
  • + ))}
+ {currentOption && !currentOption.isFixed ? ( + + ) : ( + <> + )} ); }; +interface IPriiorityDialog { + isOpenDialog: boolean; + setIsOpenDialog: Dispatch>; + option: CheckedSelectOption; + onChange: (value: readonly CheckedSelectOption[]) => void; +} + +const PriorityDialog = (props: IPriiorityDialog) => { + const { t } = useLocale(); + const { isOpenDialog, setIsOpenDialog, option, onChange } = props; + const { getValues } = useFormContext(); + + 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 ( + + +
+ +