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

@@ -57,7 +57,7 @@ import logger from "@calcom/lib/logger";
import { handlePayment } from "@calcom/lib/payment/handlePayment";
import { getPiiFreeCalendarEvent, getPiiFreeEventType } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getLuckyUser } from "@calcom/lib/server";
import { DistributionMethod, getLuckyUser } from "@calcom/lib/server/getLuckyUser";
import { getTranslation } from "@calcom/lib/server/i18n";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
@@ -114,6 +114,12 @@ export const createLoggerWithEventDetails = (
});
};
function assertNonEmptyArray<T>(arr: T[]): asserts arr is [T, ...T[]] {
if (arr.length === 0) {
throw new Error("Array should have at least one item, but it's empty");
}
}
function getICalSequence(originalRescheduledBooking: BookingType | null) {
// If new booking set the sequence to 0
if (!originalRescheduledBooking) {
@@ -451,6 +457,10 @@ async function handler(
const freeUsers = luckyUserPool.filter(
(user) => !luckyUsers.concat(notAvailableLuckyUsers).find((existing) => existing.id === user.id)
);
// no more freeUsers after subtracting notAvailableLuckyUsers from luckyUsers :(
if (freeUsers.length === 0) break;
assertNonEmptyArray(freeUsers); // make sure TypeScript knows it too wih an assertion; the error will never be thrown.
// freeUsers is ensured
const originalRescheduledBookingUserId =
originalRescheduledBooking && originalRescheduledBooking.userId;
const isSameRoundRobinHost =
@@ -460,7 +470,7 @@ async function handler(
const newLuckyUser = isSameRoundRobinHost
? freeUsers.find((user) => user.id === originalRescheduledBookingUserId)
: await getLuckyUser("MAXIMIZE_AVAILABILITY", {
: await getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
// find a lucky user that is not already in the luckyUsers array
availableUsers: freeUsers,
allRRHosts: eventTypeWithUsers.hosts.filter((host) => !host.isFixed),
@@ -53,7 +53,8 @@ export async function ensureAvailableUsers(
},
input: { dateFrom: string; dateTo: string; timeZone: string; originalRescheduledBooking?: BookingType },
loggerWithEventDetails: Logger<unknown>
) {
// ReturnType hint of at least one IsFixedAwareUser, as it's made sure at least one entry exists
): Promise<[IsFixedAwareUser, ...IsFixedAwareUser[]]> {
const availableUsers: IsFixedAwareUser[] = [];
const startDateTimeUtc = getDateTimeInUtc(input.dateFrom, input.timeZone);
@@ -142,7 +143,7 @@ export async function ensureAvailableUsers(
}
});
if (!availableUsers.length) {
if (availableUsers.length === 0) {
loggerWithEventDetails.error(
`No available users found.`,
safeStringify({
@@ -153,6 +154,6 @@ export async function ensureAvailableUsers(
);
throw new Error(ErrorCode.NoAvailableUsersFound);
}
return availableUsers;
// make sure TypeScript understands availableUsers is at least one.
return availableUsers.length === 1 ? [availableUsers[0]] : [availableUsers[0], ...availableUsers.slice(1)];
}
@@ -112,7 +112,7 @@ export const getEventTypesFromDB = async (eventTypeId: number) => {
isFixed: true,
priority: true,
weight: true,
weightAdjustment: true,
createdAt: true,
user: {
select: {
credentials: {
@@ -46,12 +46,11 @@ export const loadUsers = async ({
const loadUsersByEventType = async (eventType: EventType): Promise<NewBookingEventType["users"]> => {
const hosts = eventType.hosts || [];
const users = hosts.map(({ user, isFixed, priority, weight, weightAdjustment }) => ({
const users = hosts.map(({ user, isFixed, priority, weight }) => ({
...user,
isFixed,
priority,
weight,
weightAdjustment,
}));
return users.length ? users : eventType.users;
};
@@ -58,7 +58,6 @@ export type IsFixedAwareUser = User & {
organization?: { slug: string };
priority?: number;
weight?: number;
weightAdjustment?: number;
};
export type NewBookingEventType = DefaultEvent | getEventTypeResponse;
@@ -83,8 +83,8 @@ export const roundRobinManualReassignment = async ({
isFixed: false,
priority: 2,
weight: 100,
weightAdjustment: 0,
schedule: null,
createdAt: new Date(0), // use earliest possible date as fallback
}));
const fixedHost = eventTypeHosts.find((host) => host.isFixed);
@@ -21,6 +21,7 @@ import { SENDER_NAME } from "@calcom/lib/constants";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import logger from "@calcom/lib/logger";
import { getLuckyUser } from "@calcom/lib/server";
import { DistributionMethod } from "@calcom/lib/server/getLuckyUser";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import { prisma } from "@calcom/prisma";
@@ -83,8 +84,8 @@ export const roundRobinReassignment = async ({
isFixed: false,
priority: 2,
weight: 100,
weightAdjustment: 0,
schedule: null,
createdAt: new Date(0), // use earliest possible date as fallback
}));
const roundRobinHosts = eventType.hosts.filter((host) => !host.isFixed);
@@ -125,7 +126,7 @@ export const roundRobinReassignment = async ({
roundRobinReassignLogger
);
const reassignedRRHost = await getLuckyUser("MAXIMIZE_AVAILABILITY", {
const reassignedRRHost = await getLuckyUser(DistributionMethod.PRIORITIZE_AVAILABILITY, {
availableUsers,
eventType: {
id: eventType.id,
@@ -74,7 +74,6 @@ const CheckedHostField = ({
userId: parseInt(option.value, 10),
priority: option.priority ?? 2,
weight: option.weight ?? 100,
weightAdjustment: option.weightAdjustment ?? 0,
scheduleId: option.defaultScheduleId,
}))
);
@@ -15,7 +15,6 @@ export type CheckedSelectOption = {
value: string;
priority?: number;
weight?: number;
weightAdjustment?: number;
isFixed?: boolean;
disabled?: boolean;
defaultScheduleId?: number | null;
@@ -24,7 +24,6 @@ export type Host = {
userId: number;
priority: number;
weight: number;
weightAdjustment: number;
scheduleId?: number | null;
};
@@ -53,7 +53,6 @@ export const PriorityDialog = (props: IDialog) => {
priority: host.userId === parseInt(option.value, 10) ? newPriority.value : host.priority,
isFixed: false,
weight: host.weight,
weightAdjustment: host.weightAdjustment,
};
});
@@ -135,7 +134,6 @@ export const WeightDialog = (props: IDialog) => {
priority: host.priority,
weight: host.userId === parseInt(option.value, 10) ? newWeight : host.weight,
isFixed: false,
weightAdjustment: host.weightAdjustment,
};
});
@@ -145,7 +145,6 @@ const FixedHosts = ({
userId: parseInt(teamMember.value, 10),
priority: 2,
weight: 100,
weightAdjustment: 0,
// if host was already added, retain scheduleId
scheduleId: host?.scheduleId || teamMember.defaultScheduleId,
};
@@ -194,7 +193,6 @@ const FixedHosts = ({
userId: parseInt(teamMember.value, 10),
priority: 2,
weight: 100,
weightAdjustment: 0,
// if host was already added, retain scheduleId
scheduleId: host?.scheduleId || teamMember.defaultScheduleId,
};
@@ -279,7 +277,6 @@ const RoundRobinHosts = ({
userId: parseInt(teamMember.value, 10),
priority: 2,
weight: 100,
weightAdjustment: 0,
// if host was already added, retain scheduleId
scheduleId: host?.scheduleId || teamMember.defaultScheduleId,
};
@@ -26,7 +26,6 @@ export type Host = {
userId: number;
priority: number;
weight: number;
weightAdjustment: number;
scheduleId?: number | null;
};
export type TeamMember = {