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:
29 files changed
+1249
-218
No files matched your search
@@ -55,13 +55,15 @@ export const EventTypeUpdateInput = _EventTypeModel
|
||||
userId: z.number(),
|
||||
profileId: z.number().or(z.null()).optional(),
|
||||
isFixed: z.boolean().optional(),
|
||||
priority: z.number().optional().nullable(),
|
||||
priority: z.number().min(0).max(4).optional().nullable(),
|
||||
weight: z.number().min(0).optional().nullable(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
schedule: z.number().nullable().optional(),
|
||||
hashedLink: z.string(),
|
||||
assignAllTeamMembers: z.boolean().optional(),
|
||||
isRRWeightsEnabled: z.boolean().optional(),
|
||||
})
|
||||
.partial()
|
||||
.extend({
|
||||
|
||||
@@ -20,7 +20,12 @@ import { TRPCError } from "@trpc/server";
|
||||
import type { TrpcSessionUser } from "../../../trpc";
|
||||
import { setDestinationCalendarHandler } from "../../loggedInViewer/setDestinationCalendar.handler";
|
||||
import type { TUpdateInputSchema } from "./update.schema";
|
||||
import { ensureUniqueBookingFields, handleCustomInputs, handlePeriodType } from "./util";
|
||||
import {
|
||||
addWeightAdjustmentToNewHosts,
|
||||
ensureUniqueBookingFields,
|
||||
handleCustomInputs,
|
||||
handlePeriodType,
|
||||
} from "./util";
|
||||
|
||||
type SessionUser = NonNullable<TrpcSessionUser>;
|
||||
type User = {
|
||||
@@ -67,6 +72,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
|
||||
offsetStart,
|
||||
secondaryEmailId,
|
||||
aiPhoneCallConfig,
|
||||
isRRWeightsEnabled,
|
||||
...rest
|
||||
} = input;
|
||||
|
||||
@@ -74,6 +80,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
|
||||
where: { id },
|
||||
select: {
|
||||
title: true,
|
||||
isRRWeightsEnabled: true,
|
||||
aiPhoneCallConfig: {
|
||||
select: {
|
||||
generalPrompt: true,
|
||||
@@ -137,6 +144,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
|
||||
const data: Prisma.EventTypeUpdateInput = {
|
||||
...rest,
|
||||
bookingFields,
|
||||
isRRWeightsEnabled,
|
||||
metadata: rest.metadata === null ? Prisma.DbNull : (rest.metadata as Prisma.InputJsonObject),
|
||||
eventTypeColor: eventTypeColor === null ? Prisma.DbNull : (eventTypeColor as Prisma.InputJsonObject),
|
||||
};
|
||||
@@ -248,14 +256,28 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
}
|
||||
|
||||
// weights were already enabled or are enabled now
|
||||
const isWeightsEnabled =
|
||||
isRRWeightsEnabled || (typeof isRRWeightsEnabled === "undefined" && eventType.isRRWeightsEnabled);
|
||||
|
||||
const hostsWithWeightAdjustment = await addWeightAdjustmentToNewHosts({
|
||||
hosts,
|
||||
isWeightsEnabled,
|
||||
eventTypeId: id,
|
||||
prisma: ctx.prisma,
|
||||
});
|
||||
|
||||
data.hosts = {
|
||||
deleteMany: {},
|
||||
create: hosts.map((host) => {
|
||||
create: hostsWithWeightAdjustment.map((host) => {
|
||||
const { ...rest } = host;
|
||||
return {
|
||||
...rest,
|
||||
isFixed: data.schedulingType === SchedulingType.COLLECTIVE || host.isFixed,
|
||||
priority: host.priority ?? 2, // default to medium priority
|
||||
weight: host.weight ?? 100,
|
||||
weightAdjustment: host.weightAdjustment,
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import type { EventTypeRepository } from "@calcom/lib/server/repository/eventType";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { MembershipRole, PeriodType } from "@calcom/prisma/enums";
|
||||
import type { CustomInputSchema } from "@calcom/prisma/zod-utils";
|
||||
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
@@ -152,6 +154,129 @@ export function ensureUniqueBookingFields(fields: z.infer<typeof EventTypeUpdate
|
||||
}, {} as Record<string, true>);
|
||||
}
|
||||
|
||||
type Host = {
|
||||
userId: number;
|
||||
isFixed?: boolean | undefined;
|
||||
priority?: number | null | undefined;
|
||||
weight?: number | null | undefined;
|
||||
};
|
||||
|
||||
type User = {
|
||||
id: number;
|
||||
email: string;
|
||||
};
|
||||
|
||||
export async function addWeightAdjustmentToNewHosts({
|
||||
hosts,
|
||||
isWeightsEnabled,
|
||||
eventTypeId,
|
||||
prisma,
|
||||
}: {
|
||||
hosts: Host[];
|
||||
isWeightsEnabled: boolean;
|
||||
eventTypeId: number;
|
||||
prisma: PrismaClient;
|
||||
}): Promise<(Host & { weightAdjustment?: number })[]> {
|
||||
if (!isWeightsEnabled) return hosts;
|
||||
|
||||
// to also have the user email to check for attendees
|
||||
const usersWithHostData = await prisma.user.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: hosts.map((host) => host.userId),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
email: true,
|
||||
id: true,
|
||||
hosts: {
|
||||
where: {
|
||||
eventTypeId,
|
||||
},
|
||||
select: {
|
||||
isFixed: true,
|
||||
weightAdjustment: true,
|
||||
priority: true,
|
||||
weight: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const hostsWithUserData = usersWithHostData.map((user) => {
|
||||
// user.hosts[0] is the previous host data from the db
|
||||
// hostData is the new host data
|
||||
const hostData = hosts.find((host) => host.userId === user.id);
|
||||
return {
|
||||
isNewRRHost: !hostData?.isFixed && (!user.hosts.length || user.hosts[0].isFixed),
|
||||
isFixed: hostData?.isFixed ?? false,
|
||||
weightAdjustment: hostData?.isFixed ? 0 : user.hosts[0]?.weightAdjustment ?? 0,
|
||||
priority: hostData?.priority ?? 2,
|
||||
weight: hostData?.weight ?? 100,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const ongoingRRHosts = hostsWithUserData.filter((host) => !host.isFixed && !host.isNewRRHost);
|
||||
const allRRHosts = hosts.filter((host) => !host.isFixed);
|
||||
|
||||
if (ongoingRRHosts.length === allRRHosts.length) {
|
||||
//no new RR host was added
|
||||
return hostsWithUserData.map((host) => ({
|
||||
userId: host.user.id,
|
||||
isFixed: host.isFixed,
|
||||
priority: host.priority,
|
||||
weight: host.weight,
|
||||
weightAdjustment: host.weightAdjustment,
|
||||
}));
|
||||
}
|
||||
|
||||
const ongoingHostBookings = await BookingRepository.getAllBookingsForRoundRobin({
|
||||
eventTypeId,
|
||||
users: ongoingRRHosts.map((host) => {
|
||||
return { id: host.user.id, email: host.user.email };
|
||||
}),
|
||||
});
|
||||
|
||||
const { ongoingHostsWeightAdjustment, ongoingHostsWeights } = ongoingRRHosts.reduce(
|
||||
(acc, host) => {
|
||||
acc.ongoingHostsWeightAdjustment += host.weightAdjustment ?? 0;
|
||||
acc.ongoingHostsWeights += host.weight ?? 0;
|
||||
return acc;
|
||||
},
|
||||
{ ongoingHostsWeightAdjustment: 0, ongoingHostsWeights: 0 }
|
||||
);
|
||||
|
||||
const hostsWithWeightAdjustments = await Promise.all(
|
||||
hostsWithUserData.map(async (host) => {
|
||||
let weightAdjustment = !host.isFixed ? host.weightAdjustment : 0;
|
||||
if (host.isNewRRHost) {
|
||||
// host can already have bookings, if they ever was assigned before
|
||||
const existingBookings = await BookingRepository.getAllBookingsForRoundRobin({
|
||||
eventTypeId,
|
||||
users: [{ id: host.user.id, email: host.user.email }],
|
||||
});
|
||||
|
||||
const proportionalNrOfBookings =
|
||||
((ongoingHostBookings.length + ongoingHostsWeightAdjustment) / ongoingHostsWeights) * host.weight;
|
||||
weightAdjustment = proportionalNrOfBookings - existingBookings.length;
|
||||
}
|
||||
|
||||
return {
|
||||
userId: host.user.id,
|
||||
isFixed: host.isFixed,
|
||||
priority: host.priority,
|
||||
weight: host.weight,
|
||||
weightAdjustment: weightAdjustment > 0 ? Math.floor(weightAdjustment) : 0,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return hostsWithWeightAdjustments;
|
||||
}
|
||||
export const mapEventType = async (eventType: EventType) => ({
|
||||
...eventType,
|
||||
safeDescription: eventType?.description ? markdownToSafeHTML(eventType.description) : undefined,
|
||||
|
||||
Reference in new issue
Block a user