fix: Fairness when routing (#18550)

* Partial push of new filters

* Let's always return the passed host array when a filter doesn't need to be applied

* fix: isFixed typing in same round robin host check

* Add main bulk of rewritten logic for routed fairness support

* Remove console.log

* Add getAttributeWithEnabledWeights to AttributeRepository

* Add OOO entry repository

* Use getOrderedListOfLuckyUsers in lead threshold filtering

* Shortfall already includes weight

* test against minShortfall

* first attempt to fix fallbacks

* Added testcase updates

* Partially fix filterHosts test

* Some test updates

* Removed email field from normalization

* fix no available users found error

* fix unit test

* remove fallback from same host reschedule return

* fixes and improvements for findQualifiedHosts

* include fallback logic in handleNewBooking

* use fallback in handleNewBooking

* fix for contact owner in handleNewBooking

* WIP - comment

* pass routingFormResponseId

* fix type error

* pass routingFormResponse

* fixes in treshold logic

* remove reason

* merge qualified and fallback availabilities

* fix type error

* add and fix tests

* clean up test file

* fix filterHostsBySameRoundRobinHost tests

* fix findQualifiedHosts.test.ts

* fix getRoutedUsers.test.ts

* fix tests

* fix isRerouting check

* fix start time for two weeks check

* fix fallback hosts

* fix test

* fallback hosts should also include qualified hosts

* fix type error

* fix typos

* add contact owner to fallbacks

* fix typo

* fix qualifiedRRUsers

* set fixed users when no hosts

* add tets + code clean up

* add test for reschedule with same host

* fix typo

* add more tests for findQualifiedHosts

* remove skip from test

* add comment

* remove unused code

* fix fallback users in loadAndValidateUsers

* improve naming for fallback

* rename missed fallback variable

* fix reschedule with same rr host in handleNewBooking

* fixes for fallback slots

* add more tests + small fixes for contact owner

* fix tests and type errors

* add logs for fallback

* add type:json to logger

* Fix small merge issue

* fix end time if two weeks are cut off

* add more tests for contact owner availability check

* add new logic for two weeks fallback

* fix reschedule same RR host test

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Carina Wollendorfer <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-02-18 14:59:48 +00:00
1 parent 03346f04ed
commit 649faf4ff6
22 files changed
+1971 -704

No files matched your search

@@ -180,7 +180,7 @@ function buildLuckyUsersWithJustContactOwner({
availableUsers: IsFixedAwareUser[];
fixedUserPool: IsFixedAwareUser[];
}) {
const luckyUsers: Awaited<ReturnType<typeof loadAndValidateUsers>> = [];
const luckyUsers: Awaited<ReturnType<typeof loadAndValidateUsers>>["qualifiedRRUsers"] = [];
if (!contactOwnerEmail) {
return luckyUsers;
}
@@ -491,19 +491,43 @@ async function handler(
const contactOwnerEmail = skipContactOwner ? null : contactOwnerFromReq;
const allHostUsers = await monitorCallbackAsync(loadAndValidateUsers, {
req,
eventType,
eventTypeId,
dynamicUserList,
logger: loggerWithEventDetails,
routedTeamMemberIds: routedTeamMemberIds ?? null,
contactOwnerEmail,
isSameHostReschedule: !!(eventType.rescheduleWithSameRoundRobinHost && reqBody.rescheduleUid),
});
let routingFormResponse = null;
if (routedTeamMemberIds) {
routingFormResponse = await prisma.app_RoutingForms_FormResponse.findUnique({
where: {
id: routingFormResponseId,
},
select: {
response: true,
form: {
select: {
routes: true,
fields: true,
},
},
chosenRouteId: true,
},
});
}
const { qualifiedRRUsers, additionalFallbackRRUsers, fixedUsers } = await monitorCallbackAsync(
loadAndValidateUsers,
{
req,
eventType,
eventTypeId,
dynamicUserList,
logger: loggerWithEventDetails,
routedTeamMemberIds: routedTeamMemberIds ?? null,
contactOwnerEmail,
rescheduleUid: reqBody.rescheduleUid || null,
routingFormResponse,
}
);
// We filter out users but ensure allHostUsers remain same.
let users = allHostUsers;
let users = [...qualifiedRRUsers, ...additionalFallbackRRUsers, ...fixedUsers];
let { locationBodyString, organizerOrFirstDynamicGroupMemberDefaultLocationUrl } = getLocationValuesForDb(
dynamicUserList,
@@ -601,19 +625,58 @@ async function handler(
}
if (!req.body.allRecurringDates || req.body.isFirstRecurringSlot) {
const availableUsers = await ensureAvailableUsers(
eventTypeWithUsers,
{
dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),
dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),
timeZone: reqBody.timeZone,
originalRescheduledBooking,
},
loggerWithEventDetails,
shouldServeCache
);
let availableUsers: IsFixedAwareUser[] = [];
try {
availableUsers = await ensureAvailableUsers(
{ ...eventTypeWithUsers, users: [...qualifiedRRUsers, ...fixedUsers] as IsFixedAwareUser[] },
{
dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),
dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),
timeZone: reqBody.timeZone,
originalRescheduledBooking,
},
loggerWithEventDetails,
shouldServeCache
);
} catch {
if (additionalFallbackRRUsers.length) {
loggerWithEventDetails.debug(
"Qualified users not available, check for fallback users",
safeStringify({
qualifiedRRUsers: qualifiedRRUsers.map((user) => user.id),
additionalFallbackRRUsers: additionalFallbackRRUsers.map((user) => user.id),
})
);
// can happen when contact owner not available for 2 weeks or fairness would block at least 2 weeks
// use fallback instead
availableUsers = await ensureAvailableUsers(
{
...eventTypeWithUsers,
users: [...additionalFallbackRRUsers, ...fixedUsers] as IsFixedAwareUser[],
},
{
dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),
dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),
timeZone: reqBody.timeZone,
originalRescheduledBooking,
},
loggerWithEventDetails,
shouldServeCache
);
} else {
loggerWithEventDetails.debug(
"Qualified users not available, no fallback users",
safeStringify({
qualifiedRRUsers: qualifiedRRUsers.map((user) => user.id),
})
);
throw new Error(ErrorCode.NoAvailableUsersFound);
}
}
const luckyUserPool: IsFixedAwareUser[] = [];
const fixedUserPool: IsFixedAwareUser[] = [];
availableUsers.forEach((user) => {
user.isFixed ? fixedUserPool.push(user) : luckyUserPool.push(user);
});
@@ -628,11 +691,7 @@ async function handler(
})
);
const luckyUsers: typeof users = buildLuckyUsersWithJustContactOwner({
contactOwnerEmail: contactOwnerEmail,
availableUsers,
fixedUserPool,
});
const luckyUsers: typeof users = [];
// loop through all non-fixed hosts and get the lucky users
// This logic doesn't run when contactOwner is used because in that case, luckUsers.length === 1
@@ -644,50 +703,18 @@ async function handler(
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 shouldUseSameRRHost =
!!originalRescheduledBookingUserId &&
eventType.schedulingType === SchedulingType.ROUND_ROBIN &&
eventType.rescheduleWithSameRoundRobinHost &&
// If it is rerouting, we should not force reschedule with same host.
// It will be unexpected plus could cause unavailable slots as original host might not be part of routedTeamMemberIds
!isReroutingCase;
const userIdsSet = new Set(users.map((user) => user.id));
let routingFormResponse;
if (routedTeamMemberIds) {
routingFormResponse = await prisma.app_RoutingForms_FormResponse.findUnique({
where: {
id: routingFormResponseId,
},
select: {
response: true,
form: {
select: {
routes: true,
fields: true,
},
},
chosenRouteId: true,
},
});
}
const newLuckyUser = shouldUseSameRRHost
? freeUsers.find((user) => user.id === originalRescheduledBookingUserId)
: await getLuckyUser({
// find a lucky user that is not already in the luckyUsers array
availableUsers: freeUsers,
allRRHosts: eventTypeWithUsers.hosts.filter(
(host) => !host.isFixed && userIdsSet.has(host.user.id)
), // users part of virtual queue
eventType,
routingFormResponse: routingFormResponse ?? null,
});
const newLuckyUser = await getLuckyUser({
// find a lucky user that is not already in the luckyUsers array
availableUsers: freeUsers,
allRRHosts: eventTypeWithUsers.hosts.filter(
(host) => !host.isFixed && userIdsSet.has(host.user.id)
), // users part of virtual queue
eventType,
routingFormResponse,
});
if (!newLuckyUser) {
break; // prevent infinite loop
}
@@ -1267,7 +1294,7 @@ async function handler(
endTime: reqBody.end,
contactOwnerFromReq,
contactOwnerEmail,
allHostUsers,
allHostUsers: [...qualifiedRRUsers, ...additionalFallbackRRUsers, ...fixedUsers],
isManagedEventType,
});
booking = dryRunBooking;
@@ -2,7 +2,7 @@ import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { loadAndValidateUsers } from "./loadAndValidateUsers";
type Users = Awaited<ReturnType<typeof loadAndValidateUsers>>;
type Users = Awaited<ReturnType<typeof loadAndValidateUsers>>["qualifiedRRUsers"];
const sortUsersByDynamicList = (users: Users, dynamicUserList: string[]) => {
return users.sort((a, b) => {
@@ -2,10 +2,11 @@ import type { Prisma } from "@prisma/client";
import type { IncomingMessage } from "http";
import type { Logger } from "tslog";
import { filterHostsByLeadThreshold } from "@calcom/lib/bookings/filterHostsByLeadThreshold";
import { findQualifiedHosts } from "@calcom/lib/bookings/findQualifiedHosts";
import { HttpError } from "@calcom/lib/http-error";
import { getPiiFreeUser } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import type { RoutingFormResponse } from "@calcom/lib/server/getLuckyUser";
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
import { userSelect } from "@calcom/prisma";
import prisma from "@calcom/prisma";
@@ -33,6 +34,8 @@ type EventType = Pick<
| "assignAllTeamMembers"
| "assignRRMembersUsingSegment"
| "rrSegmentQueryValue"
| "isRRWeightsEnabled"
| "rescheduleWithSameRoundRobinHost"
>;
type InputProps = {
@@ -43,7 +46,8 @@ type InputProps = {
logger: Logger<unknown>;
routedTeamMemberIds: number[] | null;
contactOwnerEmail: string | null;
isSameHostReschedule: boolean;
rescheduleUid: string | null;
routingFormResponse: RoutingFormResponse | null;
};
export async function loadAndValidateUsers({
@@ -54,8 +58,9 @@ export async function loadAndValidateUsers({
logger,
routedTeamMemberIds,
contactOwnerEmail,
isSameHostReschedule,
}: InputProps): Promise<Users> {
rescheduleUid,
routingFormResponse,
}: InputProps): Promise<{ qualifiedRRUsers: Users; additionalFallbackRRUsers: Users; fixedUsers: Users }> {
let users: Users = await loadUsers({
eventType,
dynamicUserList,
@@ -104,21 +109,32 @@ export async function loadAndValidateUsers({
? false
: user.isFixed || eventType.schedulingType !== SchedulingType.ROUND_ROBIN,
}));
const qualifiedHosts = await filterHostsByLeadThreshold({
eventTypeId: eventType.id,
hosts: eventType.hosts.map((host) => ({
isFixed: host.isFixed,
createdAt: host.createdAt,
email: host.user.email,
user: host.user,
})),
maxLeadThreshold: isSameHostReschedule ? null : eventType.maxLeadThreshold,
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } = await findQualifiedHosts({
eventType,
routedTeamMemberIds: routedTeamMemberIds || [],
rescheduleUid,
contactOwnerEmail,
routingFormResponse,
});
if (qualifiedHosts.length) {
let qualifiedRRUsers: Users = [];
let allFallbackRRUsers: Users = [];
let fixedUsers: Users = [];
if (qualifiedRRHosts.length) {
// remove users that are not in the qualified hosts array
const qualifiedHostIds = new Set(qualifiedHosts.map((qualifiedHost) => qualifiedHost.user.id));
users = users.filter((user) => qualifiedHostIds.has(user.id));
const qualifiedHostIds = new Set(qualifiedRRHosts.map((qualifiedHost) => qualifiedHost.user.id));
qualifiedRRUsers = users.filter((user) => qualifiedHostIds.has(user.id));
}
if (allFallbackRRHosts?.length) {
const fallbackHostIds = new Set(allFallbackRRHosts.map((fallbackHost) => fallbackHost.user.id));
allFallbackRRUsers = users.filter((user) => fallbackHostIds.has(user.id));
}
if (fixedHosts?.length) {
const fixedHostIds = new Set(fixedHosts.map((fixedHost) => fixedHost.user.id));
fixedUsers = users.filter((user) => fixedHostIds.has(user.id));
}
logger.debug(
@@ -128,5 +144,13 @@ export async function loadAndValidateUsers({
})
);
return users;
const additionalFallbackRRUsers = allFallbackRRUsers.filter(
(fallbackUser) => !qualifiedRRUsers.find((qualifiedUser) => qualifiedUser.id === fallbackUser.id)
);
return {
qualifiedRRUsers,
additionalFallbackRRUsers, // without qualified
fixedUsers: !qualifiedRRUsers.length && !fixedUsers.length ? users : fixedUsers,
};
}
@@ -49,7 +49,17 @@ export const loadUsers = async ({
? await loadUsersByEventType(eventType)
: await loadDynamicUsers(dynamicUserList, currentOrgDomain);
return getRoutedUsersWithContactOwnerAndFixedUsers({ users, routedTeamMemberIds, contactOwnerEmail });
const routedUsers = getRoutedUsersWithContactOwnerAndFixedUsers({
users,
routedTeamMemberIds,
contactOwnerEmail,
});
if (routedUsers.length) {
return routedUsers;
}
return users;
} catch (error) {
log.error("Unable to load users", safeStringify(error));
if (error instanceof HttpError || error instanceof Prisma.PrismaClientKnownRequestError) {
@@ -65,7 +75,7 @@ const loadUsersByEventType = async (eventType: EventType): Promise<NewBookingEve
});
const matchingHosts = await findMatchingHostsWithEventSegment({
eventType,
normalizedHosts: hosts ?? fallbackHosts,
hosts: hosts ?? fallbackHosts,
});
return matchingHosts.map(({ user, isFixed, priority, weight, createdAt }) => ({
...user,
@@ -2193,14 +2193,7 @@ describe("handleNewBooking", () => {
},
},
},
users: [
{
id: 101,
},
{
id: 102,
},
],
hosts: [{ userId: 101 }, { userId: 102 }],
},
],
organizer,
@@ -50,6 +50,12 @@ export const useSchedule = ({
const skipContactOwner = searchParams ? searchParams.get("cal.skipContactOwner") === "true" : false;
const _cacheParam = searchParams?.get("cal.cache");
const shouldServeCache = _cacheParam ? _cacheParam === "true" : undefined;
const routingFormResponseIdParam = searchParams?.get("cal.routingFormResponseId");
const email = searchParams?.get("email");
const routingFormResponseId = routingFormResponseIdParam
? parseInt(routingFormResponseIdParam, 10)
: undefined;
const input = {
isTeamEvent,
@@ -71,6 +77,8 @@ export const useSchedule = ({
routedTeamMemberIds,
skipContactOwner,
shouldServeCache,
routingFormResponseId,
email,
};
const options = {