feat: reset RR every month (#17472)

* only fetch bookings of this month for weighted rr

* test set up

* only get bookings of current month

* reverts test setup

* first changes for weight adjustments

* reset booking count + adjust calibration

* depreciate weightAdjustment

* get only bookings created this month

* fix typo

* make sure createdAt for hosts is correct

* use earliest possibel date as fallback

* add missing createdAt date to tests

* fix typo

* clean up changes in tests

* fix typo

* change end date to current date

* fix: Fall back to empty host array when no hosts are found

* fix: Restructure code a little

* fixed test, incorrectly used now outdated var

* perf: remove Dayjs from getLuckyUser

* Refactor getHostsWithCalibration for optimised performance, intentionally break test as findMany is always an array

* Better mock for host.findMany

* Remove team-event-types.test.ts, move to appropriate package

* TypeScript cannot auto-infer that an array is non-empty when assigning to a var

* fix: Type Fixes and DistributionMethod enum add

* Optimise tests

* Added test to show that bookings made before a newHost was added affect the lucky user result

* Throw error when the usersWithHighestPriority is empty, which should never happen

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-11-07 10:24:23 +00:00
1 parent 52093862ce
commit 9873e373dc
26 files changed
+808 -876

No files matched your search

@@ -2,9 +2,9 @@ import { describe, it, expect, afterEach, beforeAll, afterAll } from "vitest";
import prisma from "@calcom/prisma";
import { getLuckyUser } from "./getLuckyUser";
import { DistributionMethod, getLuckyUser } from "./getLuckyUser";
describe("getLuckyUser tests", () => {
describe("getLuckyUser Integration tests", () => {
describe("should not consider no show bookings for round robin: ", () => {
let userIds: number[] = [];
let eventTypeId: number;
@@ -102,7 +102,7 @@ describe("getLuckyUser tests", () => {
userIds.push(organizerThatShowedUp.id, organizerThatDidntShowUp.id);
expect(
getLuckyUser("MAXIMIZE_AVAILABILITY", {
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: [organizerThatShowedUp, organizerThatDidntShowUp],
eventType: {
id: eventTypeId,
@@ -172,7 +172,7 @@ describe("getLuckyUser tests", () => {
userIds.push(organizerWhoseAttendeeShowedUp.id, organizerWhoseAttendeeDidntShowUp.id);
expect(
getLuckyUser("MAXIMIZE_AVAILABILITY", {
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: [organizerWhoseAttendeeShowedUp, organizerWhoseAttendeeDidntShowUp],
eventType: {
id: eventTypeId,
@@ -291,7 +291,7 @@ describe("getLuckyUser tests", () => {
);
expect(
getLuckyUser("MAXIMIZE_AVAILABILITY", {
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: [
organizerWhoseAttendeeShowedUp,
fixedHostOrganizerWhoseAttendeeDidNotShowUp,
@@ -366,7 +366,7 @@ describe("getLuckyUser tests", () => {
userIds.push(user1.id, user2.id);
expect(
getLuckyUser("MAXIMIZE_AVAILABILITY", {
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: [user1, user2],
eventType: {
id: eventTypeId,
+596
View File
@@ -0,0 +1,596 @@
import prismaMock from "../../../tests/libs/__mocks__/prismaMock";
import { expect, it, describe } from "vitest";
import dayjs from "@calcom/dayjs";
import { buildUser, buildBooking } from "@calcom/lib/test/builder";
import { DistributionMethod, getLuckyUser } from "./getLuckyUser";
type NonEmptyArray<T> = [T, ...T[]];
type GetLuckyUserAvailableUsersType = NonEmptyArray<ReturnType<typeof buildUser>>;
it("can find lucky user with maximize availability", async () => {
const users: GetLuckyUserAvailableUsersType = [
buildUser({
id: 1,
username: "test1",
name: "Test User 1",
email: "[email protected]",
bookings: [
{
createdAt: new Date("2022-01-25T05:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T06:30:00.000Z"),
},
],
}),
buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
bookings: [
{
createdAt: new Date("2022-01-25T04:30:00.000Z"),
},
],
}),
];
// TODO: we may be able to use native prisma generics somehow?
prismaMock.user.findMany.mockResolvedValue(users);
prismaMock.host.findMany.mockResolvedValue([]);
prismaMock.booking.findMany.mockResolvedValue([]);
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: users,
eventType: {
id: 1,
isRRWeightsEnabled: false,
},
allRRHosts: [],
})
).resolves.toStrictEqual(users[1]);
});
it("can find lucky user with maximize availability and priority ranking", async () => {
const users: GetLuckyUserAvailableUsersType = [
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"),
},
],
}),
buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
bookings: [
{
createdAt: new Date("2022-01-25T04:30:00.000Z"),
},
],
}),
];
// TODO: we may be able to use native prisma generics somehow?
prismaMock.user.findMany.mockResolvedValue(users);
prismaMock.host.findMany.mockResolvedValue([]);
prismaMock.booking.findMany.mockResolvedValue([]);
// both users have medium priority (one user has no priority set, default to medium) so pick least recently booked
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: users,
eventType: {
id: 1,
isRRWeightsEnabled: false,
},
allRRHosts: [],
})
).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: GetLuckyUserAvailableUsersType = [userLowest, userMedium, userHighest];
// TODO: we may be able to use native prisma generics somehow?
prismaMock.user.findMany.mockResolvedValue(usersWithPriorities);
prismaMock.booking.findMany.mockResolvedValue([]);
prismaMock.host.findMany.mockResolvedValue([]);
// pick the user with the highest priority
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: usersWithPriorities,
eventType: {
id: 1,
isRRWeightsEnabled: false,
},
allRRHosts: [],
})
).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: GetLuckyUserAvailableUsersType = [
userLow,
userHighLeastRecentBooking,
userHighRecentBooking,
];
// TODO: we may be able to use native prisma generics somehow?
prismaMock.user.findMany.mockResolvedValue(usersWithSamePriorities);
prismaMock.booking.findMany.mockResolvedValue([]);
prismaMock.host.findMany.mockResolvedValue([]);
// pick the least recently booked user of the two with the highest priority
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: usersWithSamePriorities,
eventType: {
id: 1,
isRRWeightsEnabled: false,
},
allRRHosts: [],
})
).resolves.toStrictEqual(usersWithSamePriorities[1]);
});
describe("maximize availability and weights", () => {
it("can find lucky user if hosts have same weights", async () => {
const users: GetLuckyUserAvailableUsersType = [
buildUser({
id: 1,
username: "test1",
name: "Test User 1",
email: "[email protected]",
priority: 3,
weight: 100,
bookings: [
{
createdAt: new Date("2022-01-25T06:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T03:30:00.000Z"),
},
],
}),
buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
priority: 3,
weight: 100,
bookings: [
{
createdAt: new Date("2022-01-25T05:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T04:30:00.000Z"),
},
],
}),
];
prismaMock.user.findMany.mockResolvedValue(users);
prismaMock.host.findMany.mockResolvedValue([]);
prismaMock.booking.findMany.mockResolvedValue([
buildBooking({
id: 1,
userId: 1,
createdAt: new Date("2022-01-25T06:30:00.000Z"),
}),
buildBooking({
id: 2,
userId: 1,
createdAt: new Date("2022-01-25T03:30:00.000Z"),
}),
buildBooking({
id: 3,
userId: 2,
createdAt: new Date("2022-01-25T05:30:00.000Z"),
}),
buildBooking({
id: 4,
userId: 2,
createdAt: new Date("2022-01-25T04:30:00.000Z"),
}),
]);
const allRRHosts = [
{
user: { id: users[0].id, email: users[0].email },
weight: users[0].weight,
createdAt: new Date(0),
},
{
user: { id: users[1].id, email: users[1].email },
weight: users[1].weight,
createdAt: new Date(0),
},
];
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: users,
eventType: {
id: 1,
isRRWeightsEnabled: true,
},
allRRHosts,
})
).resolves.toStrictEqual(users[1]);
});
it("can find lucky user if hosts have different weights", async () => {
const users: GetLuckyUserAvailableUsersType = [
buildUser({
id: 1,
username: "test1",
name: "Test User 1",
email: "[email protected]",
priority: 3,
weight: 200,
bookings: [
{
createdAt: new Date("2022-01-25T08:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T07:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T05:30:00.000Z"),
},
],
}),
buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
priority: 3,
weight: 100,
bookings: [
{
createdAt: new Date("2022-01-25T06:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T03:30:00.000Z"),
},
],
}),
];
prismaMock.user.findMany.mockResolvedValue(users);
prismaMock.host.findMany.mockResolvedValue([]);
prismaMock.booking.findMany.mockResolvedValue([
buildBooking({
id: 1,
userId: 1,
createdAt: new Date("2022-01-25T08:30:00.000Z"),
}),
buildBooking({
id: 2,
userId: 1,
createdAt: new Date("2022-01-25T07:30:00.000Z"),
}),
buildBooking({
id: 3,
userId: 1,
createdAt: new Date("2022-01-25T05:30:00.000Z"),
}),
buildBooking({
id: 4,
userId: 2,
createdAt: new Date("2022-01-25T06:30:00.000Z"),
}),
buildBooking({
id: 4,
userId: 2,
createdAt: new Date("2022-01-25T03:30:00.000Z"),
}),
]);
const allRRHosts = [
{
user: { id: users[0].id, email: users[0].email },
weight: users[0].weight,
createdAt: new Date(0),
},
{
user: { id: users[1].id, email: users[1].email },
weight: users[1].weight,
createdAt: new Date(0),
},
];
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: users,
eventType: {
id: 1,
isRRWeightsEnabled: true,
},
allRRHosts,
})
).resolves.toStrictEqual(users[0]);
});
it("can find lucky user with weights and adjusted weights", async () => {
const users: GetLuckyUserAvailableUsersType = [
buildUser({
id: 1,
username: "test1",
name: "Test User 1",
email: "[email protected]",
priority: 3,
weight: 150,
bookings: [
{
createdAt: new Date("2022-01-25T07:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T05:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T03:30:00.000Z"),
},
],
}),
buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
priority: 3,
weight: 100,
bookings: [
{
createdAt: new Date("2022-01-25T06:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T03:30:00.000Z"),
},
],
}),
];
prismaMock.user.findMany.mockResolvedValue(users);
prismaMock.host.findMany.mockResolvedValue([]);
prismaMock.booking.findMany.mockResolvedValue([
buildBooking({
id: 1,
userId: 1,
createdAt: new Date("2022-01-25T05:30:00.000Z"),
}),
buildBooking({
id: 2,
userId: 1,
createdAt: new Date("2022-01-25T03:30:00.000Z"),
}),
buildBooking({
id: 3,
userId: 1,
createdAt: new Date("2022-01-25T07:30:00.000Z"),
}),
buildBooking({
id: 4,
userId: 2,
createdAt: new Date("2022-01-25T06:30:00.000Z"),
}),
buildBooking({
id: 4,
userId: 2,
createdAt: new Date("2022-01-25T03:30:00.000Z"),
}),
]);
const allRRHosts = [
{
user: { id: users[0].id, email: users[0].email },
weight: users[0].weight,
createdAt: new Date(0),
},
{
user: { id: users[1].id, email: users[1].email },
weight: users[1].weight,
createdAt: new Date(0),
},
];
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: users,
eventType: {
id: 1,
isRRWeightsEnabled: true,
},
allRRHosts,
})
).resolves.toStrictEqual(users[0]);
});
it("applies calibration to newly added hosts so they are not penalized unfairly compared to their peers", async () => {
const users: GetLuckyUserAvailableUsersType = [
buildUser({
id: 1,
username: "test1",
name: "Test User 1",
email: "[email protected]",
bookings: [
{
createdAt: new Date("2022-01-25T05:30:00.000Z"),
},
{
createdAt: new Date("2022-01-25T06:30:00.000Z"),
},
],
}),
buildUser({
id: 2,
username: "test2",
name: "Test User 2",
email: "[email protected]",
bookings: [
{
createdAt: new Date("2022-01-25T04:30:00.000Z"),
},
],
}),
];
const middleOfMonth = new Date(
Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 14, 12, 0, 0)
);
const allRRHosts = [
{
user: { id: users[0].id, email: users[0].email },
weight: users[0].weight,
createdAt: middleOfMonth,
},
{
user: { id: users[1].id, email: users[1].email },
weight: users[1].weight,
createdAt: new Date(0),
},
];
// TODO: we may be able to use native prisma generics somehow?
prismaMock.user.findMany.mockResolvedValue(users);
prismaMock.host.findMany.mockResolvedValue([
{
userId: allRRHosts[0].user.id,
weight: allRRHosts[0].weight,
createdAt: allRRHosts[0].createdAt,
},
]);
// findMany bookings are BEFORE the new host (user 1) was added, calibration=2.
prismaMock.booking.findMany.mockResolvedValue([
buildBooking({
id: 4,
userId: 2,
createdAt: dayjs(middleOfMonth).subtract(2, "days").toDate(),
}),
buildBooking({
id: 5,
userId: 2,
createdAt: dayjs(middleOfMonth).subtract(5, "days").toDate(),
}),
]);
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: users,
eventType: {
id: 1,
isRRWeightsEnabled: true,
},
allRRHosts,
})
).resolves.toStrictEqual(users[1]);
// findMany bookings are AFTER the new host (user 1) was added, calibration=0.
prismaMock.booking.findMany.mockResolvedValue([
buildBooking({
id: 4,
userId: 2,
createdAt: dayjs(middleOfMonth).add(2, "days").toDate(),
}),
buildBooking({
id: 5,
userId: 2,
createdAt: dayjs(middleOfMonth).add(5, "days").toDate(),
}),
]);
await expect(
getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers: users,
eventType: {
id: 1,
isRRWeightsEnabled: true,
},
allRRHosts,
})
).resolves.toStrictEqual(users[0]);
});
});
+126 -35
View File
@@ -5,6 +5,13 @@ import prisma from "@calcom/prisma";
import type { Booking } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
export enum DistributionMethod {
PRIORITIZE_AVAILABILITY = "PRIORITIZE_AVAILABILITY",
// BALANCED_ASSIGNMENT = "BALANCED_ASSIGNMENT",
// ROUND_ROBIN (for fairness, rotating through assignees)
// LOAD_BALANCED (ensuring an even workload)
}
type PartialBooking = Pick<Booking, "id" | "createdAt" | "userId" | "status"> & {
attendees: { email: string | null }[];
};
@@ -12,14 +19,18 @@ type PartialBooking = Pick<Booking, "id" | "createdAt" | "userId" | "status"> &
type PartialUser = Pick<User, "id" | "email">;
interface GetLuckyUserParams<T extends PartialUser> {
availableUsers: T[];
availableUsers: [T, ...T[]]; // ensure contains at least 1
eventType: { id: number; isRRWeightsEnabled: boolean };
allRRHosts: {
user: { id: number; email: string };
createdAt: Date;
weight?: number | null;
weightAdjustment?: number | null;
}[];
}
// === dayjs.utc().startOf("month").toDate();
const startOfMonth = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 1));
// TS helper function.
const isNonEmptyArray = <T>(arr: T[]): arr is [T, ...T[]] => arr.length > 0;
async function leastRecentlyBookedUser<T extends PartialUser>({
availableUsers,
@@ -107,29 +118,88 @@ async function leastRecentlyBookedUser<T extends PartialUser>({
return leastRecentlyBookedUser;
}
async function getHostsWithCalibration(
eventTypeId: number,
hosts: { userId: number; email: string; createdAt: Date }[]
) {
const [newHostsArray, existingBookings] = await Promise.all([
prisma.host.findMany({
where: {
userId: {
in: hosts.map((host) => host.userId),
},
eventTypeId,
isFixed: false,
createdAt: {
gte: startOfMonth,
},
},
}),
BookingRepository.getAllBookingsForRoundRobin({
eventTypeId,
users: hosts.map((host) => ({
id: host.userId,
email: host.email,
})),
startDate: startOfMonth,
endDate: new Date(),
}),
]);
// Return early if there are no new hosts or no existing bookings
if (newHostsArray.length === 0 || existingBookings.length === 0) {
return hosts.map((host) => ({ ...host, calibration: 0 }));
}
// Helper function to calculate calibration for a new host
function calculateCalibration(newHost: { userId: number; createdAt: Date }) {
const existingBookingsBeforeAdded = existingBookings.filter(
(booking) => booking.userId !== newHost.userId && booking.createdAt < newHost.createdAt
);
const hostsAddedBefore = hosts.filter(
(host) => host.userId !== newHost.userId && host.createdAt < newHost.createdAt
);
return existingBookingsBeforeAdded.length && hostsAddedBefore.length
? existingBookingsBeforeAdded.length / hostsAddedBefore.length
: 0;
}
// Calculate calibration for each new host and store in a Map
const newHostsWithCalibration = new Map(
newHostsArray.map((newHost) => [
newHost.userId,
{ ...newHost, calibration: calculateCalibration(newHost) },
])
);
// Map hosts with their respective calibration values
return hosts.map((host) => ({
...host,
calibration: newHostsWithCalibration.get(host.userId)?.calibration ?? 0,
}));
}
function getUsersWithHighestPriority<T extends PartialUser & { priority?: number | null }>({
availableUsers,
}: {
availableUsers: T[];
}) {
const highestPriority = Math.max(...availableUsers.map((user) => user.priority ?? 2));
return availableUsers.filter(
const usersWithHighestPriority = availableUsers.filter(
(user) => user.priority === highestPriority || (user.priority == null && highestPriority === 2)
);
if (!isNonEmptyArray(usersWithHighestPriority)) {
throw new Error("Internal Error: Highest Priority filter should never return length=0.");
}
return usersWithHighestPriority;
}
async function getUsersBasedOnWeights<
async function filterUsersBasedOnWeights<
T extends PartialUser & {
weight?: number | null;
weightAdjustment?: number | null;
}
>({
availableUsers,
bookingsOfAvailableUsers,
allRRHosts,
eventType,
}: GetLuckyUserParams<T> & { bookingsOfAvailableUsers: PartialBooking[] }) {
}: GetLuckyUserParams<T> & { bookingsOfAvailableUsers: PartialBooking[] }): Promise<[T, ...T[]]> {
//get all bookings of all other RR hosts that are not available
const availableUserIds = new Set(availableUsers.map((user) => user.id));
@@ -155,20 +225,30 @@ async function getUsersBasedOnWeights<
const bookingsOfNotAvailableUsers = await BookingRepository.getAllBookingsForRoundRobin({
eventTypeId: eventType.id,
users: notAvailableHosts,
startDate: startOfMonth,
endDate: new Date(),
});
const allBookings = bookingsOfAvailableUsers.concat(bookingsOfNotAvailableUsers);
// Calculate the total weightAdjustments and weight of all round-robin hosts
const { allWeightAdjustments, totalWeight } = allRRHosts.reduce(
(acc, host) => {
acc.allWeightAdjustments += host.weightAdjustment ?? 0;
acc.totalWeight += host.weight ?? 100;
return acc;
},
{ allWeightAdjustments: 0, totalWeight: 0 }
const allHostsWithCalibration = await getHostsWithCalibration(
eventType.id,
allRRHosts.map((host) => {
return { email: host.user.email, userId: host.user.id, createdAt: host.createdAt };
})
);
// Calculate the total calibration and weight of all round-robin hosts
const totalWeight = allRRHosts.reduce((totalWeight, host) => {
totalWeight += host.weight ?? 100;
return totalWeight;
}, 0);
const totalCalibration = allHostsWithCalibration.reduce((totalCalibration, host) => {
totalCalibration += host.calibration;
return totalCalibration;
}, 0);
// Calculate booking shortfall for each available user
const usersWithBookingShortfalls = availableUsers.map((user) => {
const targetPercentage = (user.weight ?? 100) / totalWeight;
@@ -178,8 +258,11 @@ async function getUsersBasedOnWeights<
booking.userId === user.id || booking.attendees.some((attendee) => attendee.email === user.email)
);
const targetNumberOfBookings = (allBookings.length + allWeightAdjustments) * targetPercentage;
const bookingShortfall = targetNumberOfBookings - (userBookings.length + (user.weightAdjustment ?? 0));
const targetNumberOfBookings = (allBookings.length + totalCalibration) * targetPercentage;
// I need to get the user's current calibration here
const userCalibration = allHostsWithCalibration.find((host) => host.userId === user.id)?.calibration ?? 0;
const bookingShortfall = targetNumberOfBookings - (userBookings.length + userCalibration);
return {
...user,
@@ -199,8 +282,13 @@ async function getUsersBasedOnWeights<
const userIdsWithMaxShortfallAndWeight = new Set(
usersWithMaxShortfall.filter((user) => user.weight === maxWeight).map((user) => user.id)
);
return availableUsers.filter((user) => userIdsWithMaxShortfallAndWeight.has(user.id));
const remainingUsersAfterWeightFilter = availableUsers.filter((user) =>
userIdsWithMaxShortfallAndWeight.has(user.id)
);
if (!isNonEmptyArray(remainingUsersAfterWeightFilter)) {
throw new Error("Internal Error: Weight filter should never return length=0.");
}
return remainingUsersAfterWeightFilter;
}
// TODO: Configure distributionAlgorithm from the event type configuration
@@ -209,40 +297,43 @@ export async function getLuckyUser<
T extends PartialUser & {
priority?: number | null;
weight?: number | null;
weightAdjustment?: number | null;
}
>(
distributionAlgorithm: "MAXIMIZE_AVAILABILITY" = "MAXIMIZE_AVAILABILITY",
getLuckyUserParams: GetLuckyUserParams<T>
distributionMethod: DistributionMethod = DistributionMethod.PRIORITIZE_AVAILABILITY,
{ availableUsers, ...getLuckyUserParams }: GetLuckyUserParams<T>
) {
const { availableUsers, eventType, allRRHosts } = getLuckyUserParams;
const { eventType } = getLuckyUserParams;
// there is only one user
if (availableUsers.length === 1) {
return availableUsers[0];
}
const bookingsOfAvailableUsers = await BookingRepository.getAllBookingsForRoundRobin({
const currentMonthBookingsOfAvailableUsers = await BookingRepository.getAllBookingsForRoundRobin({
eventTypeId: eventType.id,
users: availableUsers.map((user) => {
return { id: user.id, email: user.email };
}),
startDate: startOfMonth,
endDate: new Date(),
});
switch (distributionAlgorithm) {
case "MAXIMIZE_AVAILABILITY":
let possibleLuckyUsers = availableUsers;
switch (distributionMethod) {
case DistributionMethod.PRIORITIZE_AVAILABILITY: {
if (eventType.isRRWeightsEnabled) {
possibleLuckyUsers = await getUsersBasedOnWeights({
availableUsers = await filterUsersBasedOnWeights({
...getLuckyUserParams,
bookingsOfAvailableUsers,
availableUsers,
bookingsOfAvailableUsers: currentMonthBookingsOfAvailableUsers,
});
}
const highestPriorityUsers = getUsersWithHighestPriority({ availableUsers: possibleLuckyUsers });
return leastRecentlyBookedUser<T>({
const highestPriorityUsers = getUsersWithHighestPriority({ availableUsers });
// No need to round-robin through the only user, return early also.
if (highestPriorityUsers.length === 1) return highestPriorityUsers[0];
// TS is happy.
return leastRecentlyBookedUser({
...getLuckyUserParams,
availableUsers: highestPriorityUsers,
bookingsOfAvailableUsers,
bookingsOfAvailableUsers: currentMonthBookingsOfAvailableUsers,
});
}
}
}
+13
View File
@@ -77,9 +77,13 @@ export class BookingRepository {
static async getAllBookingsForRoundRobin({
users,
eventTypeId,
startDate,
endDate,
}: {
users: { id: number; email: string }[];
eventTypeId: number;
startDate?: Date;
endDate?: Date;
}) {
const whereClause: Prisma.BookingWhereInput = {
OR: [
@@ -111,6 +115,14 @@ export class BookingRepository {
attendees: { some: { noShow: false } },
status: BookingStatus.ACCEPTED,
eventTypeId,
...(startDate && endDate
? {
createdAt: {
gte: startDate,
lte: endDate,
},
}
: {}),
};
const allBookings = await prisma.booking.findMany({
@@ -121,6 +133,7 @@ export class BookingRepository {
userId: true,
createdAt: true,
status: true,
startTime: true,
},
orderBy: {
createdAt: "desc",
@@ -534,7 +534,6 @@ export class EventTypeRepository {
userId: true,
priority: true,
weight: true,
weightAdjustment: true,
scheduleId: true,
},
},
+2 -3
View File
@@ -262,8 +262,8 @@ type UserPayload = Prisma.UserGetPayload<{
};
}>;
export const buildUser = <T extends Partial<UserPayload>>(
user?: T & { priority?: number; weight?: number; weightAdjustment?: number }
): UserPayload & { priority: number; weight: number; weightAdjustment: number } => {
user?: T & { priority?: number; weight?: number }
): UserPayload & { priority: number; weight: number } => {
return {
locked: false,
smsLockState: "UNLOCKED",
@@ -312,7 +312,6 @@ export const buildUser = <T extends Partial<UserPayload>>(
movedToProfileId: null,
priority: user?.priority ?? 2,
weight: user?.weight ?? 100,
weightAdjustment: user?.weightAdjustment ?? 0,
isPlatformManaged: false,
...user,
};