From edecc7e60e184731cf471d3ca2c2f5b02d5c72b4 Mon Sep 17 00:00:00 2001 From: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com> Date: Wed, 6 Nov 2024 10:51:36 -0500 Subject: [PATCH] feat: Round Robin Skip If contact owner first available slot is more than 2 weeks, round robin as normal [CAL-4651] (#17416) * If contact owner first available slot is more than 2 weeks. Normal RR * If contact owner first available slot is more than 2 weeks. Normal RR * Type fix * Add test --- apps/web/test/lib/getSchedule.test.ts | 135 ++++++- .../utils/bookingScenario/bookingScenario.ts | 5 + .../trpc/server/routers/viewer/slots/util.ts | 379 +++++++++++------- 3 files changed, 364 insertions(+), 155 deletions(-) diff --git a/apps/web/test/lib/getSchedule.test.ts b/apps/web/test/lib/getSchedule.test.ts index 80a6493049..7ba0fd7295 100644 --- a/apps/web/test/lib/getSchedule.test.ts +++ b/apps/web/test/lib/getSchedule.test.ts @@ -223,8 +223,10 @@ describe("getSchedule", () => { ); }); test("correctly get slots for event with round robin and fixed hosts", async () => { - const { dateString: plus1DateString } = getDate({ dateIncrement: 1 }); - const { dateString: plus2DateString } = getDate({ dateIncrement: 2 }); + vi.setSystemTime("2024-05-21T00:00:13Z"); + + const plus1DateString = "2024-05-22"; + const plus2DateString = "2024-05-23"; const crmCredential = { id: 1, @@ -365,6 +367,135 @@ describe("getSchedule", () => { } ); }); + test("correctly get slots for event with only round robin hosts", async () => { + vi.setSystemTime("2024-05-21T00:00:13Z"); + + const plus1DateString = "2024-05-22"; + const plus2DateString = "2024-05-23"; + + const crmCredential = { + id: 1, + type: "salesforce_crm", + key: { + clientId: "test-client-id", + }, + userId: 1, + teamId: null, + appId: "salesforce", + invalid: false, + user: { email: "test@test.com" }, + }; + + await createCredentials([crmCredential]); + + mockCrmApp("salesforce", { + getContacts: [ + { + id: "contact-id", + email: "test@test.com", + ownerEmail: "example@example.com", + }, + ], + createContacts: [{ id: "contact-id", email: "test@test.com" }], + }); + + await createBookingScenario({ + eventTypes: [ + { + id: 1, + slotInterval: 60, + length: 60, + hosts: [ + { + userId: 101, + isFixed: false, + }, + { + userId: 102, + isFixed: false, + }, + ], + schedulingType: "ROUND_ROBIN", + metadata: { + apps: { + salesforce: { + enabled: true, + appCategories: ["crm"], + roundRobinLeadSkip: true, + }, + }, + }, + }, + ], + users: [ + { + ...TestData.users.example, + email: "example@example.com", + id: 101, + schedules: [TestData.schedules.EmptyAvailability], + }, + { + ...TestData.users.example, + email: "example1@example.com", + id: 102, + schedules: [TestData.schedules.IstMorningShift], + defaultScheduleId: 2, + }, + ], + bookings: [], + }); + + const scheduleWithLeadSkip = await getSchedule({ + input: { + eventTypeId: 1, + eventTypeSlug: "", + startTime: `${plus1DateString}T18:30:00.000Z`, + endTime: `${plus2DateString}T18:29:59.999Z`, + timeZone: Timezones["+5:30"], + isTeamEvent: true, + teamMemberEmail: "example@example.com", + orgSlug: null, + }, + }); + + // only slots where example@example.com is available + expect(scheduleWithLeadSkip).toHaveDateDisabled({ + dateString: plus2DateString, + }); + + const scheduleWithoutLeadSkip = await getSchedule({ + input: { + eventTypeId: 1, + eventTypeSlug: "", + startTime: `${plus1DateString}T18:30:00.000Z`, + endTime: `${plus2DateString}T18:29:59.999Z`, + timeZone: Timezones["+5:30"], + isTeamEvent: true, + orgSlug: null, + }, + }); + + // slots where either one of the rr hosts is available + expect(scheduleWithoutLeadSkip).toHaveTimeSlots( + [ + `04:30:00.000Z`, + `05:30:00.000Z`, + `06:30:00.000Z`, + `07:30:00.000Z`, + `08:30:00.000Z`, + `09:30:00.000Z`, + `10:30:00.000Z`, + `11:30:00.000Z`, + `12:30:00.000Z`, + `13:30:00.000Z`, + `14:30:00.000Z`, + `15:30:00.000Z`, + ], + { + dateString: plus2DateString, + } + ); + }); }); describe("User Event", () => { diff --git a/apps/web/test/utils/bookingScenario/bookingScenario.ts b/apps/web/test/utils/bookingScenario/bookingScenario.ts index 4461f1c8f9..5eabc04760 100644 --- a/apps/web/test/utils/bookingScenario/bookingScenario.ts +++ b/apps/web/test/utils/bookingScenario/bookingScenario.ts @@ -1093,6 +1093,11 @@ export const TestData = { ], timeZone: Timezones["+5:30"], }, + EmptyAvailability: { + name: "Empty Availability", + availability: [], + timeZone: Timezones["+5:30"], + }, IstWorkHoursWithDateOverride: (dateString: string) => ({ name: "9:30AM to 6PM in India - 4:00AM to 12:30PM in GMT but with a Date Override for 2PM to 6PM IST(in GST time it is 8:30AM to 12:30PM)", availability: [ diff --git a/packages/trpc/server/routers/viewer/slots/util.ts b/packages/trpc/server/routers/viewer/slots/util.ts index 58cd02d9b2..ccdc76a6b0 100644 --- a/packages/trpc/server/routers/viewer/slots/util.ts +++ b/packages/trpc/server/routers/viewer/slots/util.ts @@ -1,5 +1,6 @@ // eslint-disable-next-line no-restricted-imports import { countBy } from "lodash"; +import type { Logger } from "tslog"; import { v4 as uuid } from "uuid"; import { getAggregatedAvailability } from "@calcom/core/getAggregatedAvailability"; @@ -399,6 +400,13 @@ export function getUsersWithCredentialsConsideringContactOwner({ return contactOwnerAndFixedHosts; } +const getStartTime = (startTimeInput: string, timeZone?: string, minimumBookingNotice?: number) => { + const startTimeMin = dayjs.utc().add(minimumBookingNotice || 1, "minutes"); + const startTime = timeZone === "Etc/GMT" ? dayjs.utc(startTimeInput) : dayjs(startTimeInput).tz(timeZone); + + return startTimeMin.isAfter(startTime) ? startTimeMin.tz(timeZone) : startTime; +}; + export const getAvailableSlots = async ( ...args: Parameters ): Promise> => { @@ -447,14 +455,11 @@ async function _getAvailableSlots({ input, ctx }: GetScheduleOptions): Promise { - const startTimeMin = dayjs.utc().add(eventType.minimumBookingNotice || 1, "minutes"); - const startTime = timeZone === "Etc/GMT" ? dayjs.utc(startTimeInput) : dayjs(startTimeInput).tz(timeZone); - - return startTimeMin.isAfter(startTime) ? startTimeMin.tz(timeZone) : startTime; - }; - - const startTime = getStartTime(startTimeAdjustedForRollingWindowComputation, input.timeZone); + const startTime = getStartTime( + startTimeAdjustedForRollingWindowComputation, + input.timeZone, + eventType.minimumBookingNotice + ); const endTime = input.timeZone === "Etc/GMT" ? dayjs.utc(input.endTime) : dayjs(input.endTime).utc().tz(input.timeZone); @@ -486,159 +491,52 @@ async function _getAvailableSlots({ input, ctx }: GetScheduleOptions): Promise host.user.id === originalRescheduledBooking?.userId || 0 - ); - } - - const usersWithCredentials = monitorCallbackSync(getUsersWithCredentialsConsideringContactOwner, { - contactOwnerEmail, - hosts: routedHostsWithContactOwnerAndFixedHosts, - }); - - loggerWithEventDetails.debug("Using users", { - usersWithCredentials: usersWithCredentials.map((user) => user.email), - }); - - const durationToUse = input.duration || 0; - - const startTimeDate = - input.rescheduleUid && durationToUse - ? startTime.subtract(durationToUse, "minute").toDate() - : startTime.toDate(); - - const endTimeDate = - input.rescheduleUid && durationToUse ? endTime.add(durationToUse, "minute").toDate() : endTime.toDate(); - - const sharedQuery = { - startTime: { lte: endTimeDate }, - endTime: { gte: startTimeDate }, - status: { - in: [BookingStatus.ACCEPTED], - }, - }; - - const allUserIds = usersWithCredentials.map((user) => user.id); - const currentBookingsAllUsers = await monitorCallbackAsync( - getExistingBookings, - startTimeDate, - endTimeDate, - eventType, - sharedQuery, - usersWithCredentials, - allUserIds - ); - - const outOfOfficeDaysAllUsers = await monitorCallbackAsync( - getOOODates, - startTimeDate, - endTimeDate, - allUserIds - ); - - const bookingLimits = parseBookingLimit(eventType?.bookingLimits); - const durationLimits = parseDurationLimit(eventType?.durationLimits); - let busyTimesFromLimitsBookingsAllUsers: Awaited> = []; - - if (eventType && (bookingLimits || durationLimits)) { - busyTimesFromLimitsBookingsAllUsers = await monitorCallbackAsync(getBusyTimesForLimitChecks, { - userIds: allUserIds, - eventTypeId: eventType.id, - startDate: startTime.format(), - endDate: endTime.format(), - rescheduleUid: input.rescheduleUid, - bookingLimits, - durationLimits, - }); - } - - const users = monitorCallbackSync(function enrichUsersWithData() { - return usersWithCredentials.map((currentUser) => { - return { - ...currentUser, - currentBookings: currentBookingsAllUsers - .filter( - (b) => b.userId === currentUser.id || b.attendees?.some((a) => a.email === currentUser.email) - ) - .map((bookings) => { - const { attendees: _attendees, ...bookingWithoutAttendees } = bookings; - return bookingWithoutAttendees; - }), - outOfOfficeDays: outOfOfficeDaysAllUsers.filter((o) => o.user.id === currentUser.id), - }; - }); - }); - - const premappedUsersAvailability = await getUsersAvailability({ - users, - query: { - dateFrom: startTime.format(), - dateTo: endTime.format(), - eventTypeId: eventType.id, - afterEventBuffer: eventType.afterEventBuffer, - beforeEventBuffer: eventType.beforeEventBuffer, - duration: input.duration || 0, - returnDateOverrides: false, - bypassBusyCalendarTimes, - }, - initialData: { + let { aggregatedAvailability, allUsersAvailability, usersWithCredentials } = + await calculateHostsAndAvailabilities({ + input, eventType, + routedHostsWithContactOwnerAndFixedHosts, + contactOwnerEmail, + loggerWithEventDetails, + startTime, + endTime, currentSeats, - rescheduleUid: input.rescheduleUid, - busyTimesFromLimitsBookings: busyTimesFromLimitsBookingsAllUsers, - }, - }); - /* We get all users working hours and busy slots */ - const allUsersAvailability = premappedUsersAvailability.map( - ( - { busy, dateRanges, oooExcludedDateRanges, currentSeats: _currentSeats, timeZone, datesOutOfOffice }, - index - ) => { - const currentUser = users[index]; - if (!currentSeats && _currentSeats) currentSeats = _currentSeats; - return { - timeZone, - dateRanges, - oooExcludedDateRanges, - busy, - user: currentUser, - datesOutOfOffice, - }; + bypassBusyCalendarTimes, + }); + + // If contact skipping, determine if there's availability within two weeks + if (contactOwnerEmail && aggregatedAvailability.length > 0) { + const twoWeeksFromNow = dayjs().add(2, "week"); + const diff = aggregatedAvailability[0].start.diff(twoWeeksFromNow, "day"); + + if (diff > 0) { + const routedHostsAndFixedHosts = routedHostsWithContactOwnerAndFixedHosts.filter( + (host) => host.email !== contactOwnerEmail + ); + + if (routedHostsAndFixedHosts.length > 0) { + // if the first available slot is more than 2 weeks from now, round robin as normal + ({ aggregatedAvailability, allUsersAvailability, usersWithCredentials } = + await calculateHostsAndAvailabilities({ + input, + eventType, + routedHostsWithContactOwnerAndFixedHosts: routedHostsAndFixedHosts, + contactOwnerEmail, + loggerWithEventDetails, + startTime, + endTime, + currentSeats, + bypassBusyCalendarTimes, + })); + } } - ); - - const availabilityCheckProps = { - eventLength: input.duration || eventType.length, - currentSeats, - }; - - const aggregatedAvailability = monitorCallbackSync( - getAggregatedAvailability, - allUsersAvailability, - eventType.schedulingType - ); + } const isTeamEvent = eventType.schedulingType === SchedulingType.COLLECTIVE || @@ -678,6 +576,11 @@ async function _getAvailableSlots({ input, ctx }: GetScheduleOptions): Promise 0) { let occupiedSeats: typeof selectedSlots = selectedSlots.filter( (item) => item.isSeat && item.eventTypeId === eventType.id @@ -1104,3 +1007,173 @@ export function getAllDatesWithBookabilityStatus(availableDates: string[]) { } return allDates; } + +const calculateHostsAndAvailabilities = async ({ + input, + eventType, + routedHostsWithContactOwnerAndFixedHosts, + contactOwnerEmail, + loggerWithEventDetails, + startTime, + endTime, + currentSeats, + bypassBusyCalendarTimes, +}: { + input: TGetScheduleInputSchema; + eventType: Exclude>, null>; + routedHostsWithContactOwnerAndFixedHosts: { + isFixed?: boolean; + user: GetAvailabilityUser; + }[]; + contactOwnerEmail?: string | null; + loggerWithEventDetails: Logger; + startTime: ReturnType; + endTime: Dayjs; + currentSeats?: CurrentSeats | undefined; + bypassBusyCalendarTimes: boolean; +}) => { + if ( + input.rescheduleUid && + eventType.rescheduleWithSameRoundRobinHost && + eventType.schedulingType === SchedulingType.ROUND_ROBIN + ) { + const originalRescheduledBooking = await prisma.booking.findFirst({ + where: { + uid: input.rescheduleUid, + status: { + in: [BookingStatus.ACCEPTED], + }, + }, + select: { + userId: true, + }, + }); + routedHostsWithContactOwnerAndFixedHosts = routedHostsWithContactOwnerAndFixedHosts.filter( + (host) => host.user.id === originalRescheduledBooking?.userId || 0 + ); + } + + const usersWithCredentials = monitorCallbackSync(getUsersWithCredentialsConsideringContactOwner, { + contactOwnerEmail, + hosts: routedHostsWithContactOwnerAndFixedHosts, + }); + + loggerWithEventDetails.debug("Using users", { + usersWithCredentials: usersWithCredentials.map((user) => user.email), + }); + + const durationToUse = input.duration || 0; + + const startTimeDate = + input.rescheduleUid && durationToUse + ? startTime.subtract(durationToUse, "minute").toDate() + : startTime.toDate(); + + const endTimeDate = + input.rescheduleUid && durationToUse ? endTime.add(durationToUse, "minute").toDate() : endTime.toDate(); + + const sharedQuery = { + startTime: { lte: endTimeDate }, + endTime: { gte: startTimeDate }, + status: { + in: [BookingStatus.ACCEPTED], + }, + }; + + const allUserIds = usersWithCredentials.map((user) => user.id); + const currentBookingsAllUsers = await monitorCallbackAsync( + getExistingBookings, + startTimeDate, + endTimeDate, + eventType, + sharedQuery, + usersWithCredentials, + allUserIds + ); + + const outOfOfficeDaysAllUsers = await monitorCallbackAsync( + getOOODates, + startTimeDate, + endTimeDate, + allUserIds + ); + + const bookingLimits = parseBookingLimit(eventType?.bookingLimits); + const durationLimits = parseDurationLimit(eventType?.durationLimits); + let busyTimesFromLimitsBookingsAllUsers: Awaited> = []; + + if (eventType && (bookingLimits || durationLimits)) { + busyTimesFromLimitsBookingsAllUsers = await monitorCallbackAsync(getBusyTimesForLimitChecks, { + userIds: allUserIds, + eventTypeId: eventType.id, + startDate: startTime.format(), + endDate: endTime.format(), + rescheduleUid: input.rescheduleUid, + bookingLimits, + durationLimits, + }); + } + + const users = monitorCallbackSync(function enrichUsersWithData() { + return usersWithCredentials.map((currentUser) => { + return { + ...currentUser, + currentBookings: currentBookingsAllUsers + .filter( + (b) => b.userId === currentUser.id || b.attendees?.some((a) => a.email === currentUser.email) + ) + .map((bookings) => { + const { attendees: _attendees, ...bookingWithoutAttendees } = bookings; + return bookingWithoutAttendees; + }), + outOfOfficeDays: outOfOfficeDaysAllUsers.filter((o) => o.user.id === currentUser.id), + }; + }); + }); + + const premappedUsersAvailability = await getUsersAvailability({ + users, + query: { + dateFrom: startTime.format(), + dateTo: endTime.format(), + eventTypeId: eventType.id, + afterEventBuffer: eventType.afterEventBuffer, + beforeEventBuffer: eventType.beforeEventBuffer, + duration: input.duration || 0, + returnDateOverrides: false, + bypassBusyCalendarTimes, + }, + initialData: { + eventType, + currentSeats, + rescheduleUid: input.rescheduleUid, + busyTimesFromLimitsBookings: busyTimesFromLimitsBookingsAllUsers, + }, + }); + /* We get all users working hours and busy slots */ + const allUsersAvailability = premappedUsersAvailability.map( + ( + { busy, dateRanges, oooExcludedDateRanges, currentSeats: _currentSeats, timeZone, datesOutOfOffice }, + index + ) => { + const currentUser = users[index]; + if (!currentSeats && _currentSeats) currentSeats = _currentSeats; + return { + timeZone, + dateRanges, + oooExcludedDateRanges, + busy, + user: currentUser, + datesOutOfOffice, + }; + } + ); + + const aggregatedAvailability = monitorCallbackSync( + getAggregatedAvailability, + allUsersAvailability, + eventType.schedulingType + ); + + return { aggregatedAvailability, allUsersAvailability, usersWithCredentials }; +};