Refactored buildSlots (#6389)

* Refactored buildSlots

* Added typing for computedAvailableSlots

* Adds very simple boundary logic to make sure slots start at the right times

* Logic was cutting off too early

* Woops, should be eventLength, not frequency

* Expect 12:15 slots as availability is till 12:30 for booking

* Deliberately skip test for testing purposes

* slotInterval overrides intervals, but not duration

* Fix calendar mocking

* Another 45m length

* Unskip :(

* Fix test

Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: Omar López <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-01-11 17:33:34 +00:00
1 parent b34a568a93
commit c8744768c4
7 files changed
+179 -209

No files matched your search

+5 -8
View File
@@ -164,7 +164,7 @@ export async function getUserAvailability(
let startDate = dayjs(dateFrom);
const endDate = dayjs(dateTo);
while (startDate.isBefore(endDate)) {
dates.push(startDate.add(1, "day"));
dates.push(startDate);
startDate = startDate.add(1, "day");
}
@@ -173,7 +173,6 @@ export async function getUserAvailability(
);
// Apply booking limit filter against our bookings
for (const [key, limit] of Object.entries(bookingLimits)) {
const limitKey = key as keyof BookingLimit;
@@ -192,18 +191,16 @@ export async function getUserAvailability(
});
break;
}
// Take PER_DAY and turn it into day and PER_WEEK into week etc.
const filter = limitKey.split("_")[1].toLocaleLowerCase() as "day" | "week" | "month" | "year";
const filter = limitKey.split("_")[1].toLowerCase() as "day" | "week" | "month" | "year";
// loop through all dates and check if we have reached the limit
for (const date of dates) {
let total = 0;
const startDate = dayjs(date).startOf(filter);
const startDate = date.startOf(filter);
// this is parsed above with parseBookingLimit so we know it's safe.
const endDate = dayjs(date).endOf(filter);
const endDate = date.endOf(filter);
for (const booking of ourBookings) {
const bookingEventTypeId = booking.source?.split("-")[1];
const bookingEventTypeId = parseInt(booking.source?.split("-")[1] as string, 10);
if (
// Only check OUR booking that matches the current eventTypeId
// we don't care about another event type in this case as we dont need to know their booking limits
+69 -66
View File
@@ -15,41 +15,6 @@ export type TimeFrame = { userIds?: number[]; startTime: number; endTime: number
const minimumOfOne = (input: number) => (input < 1 ? 1 : input);
/**
* TODO: What does this function do?
* Why is it needed?
*/
const splitAvailableTime = (
startTimeMinutes: number,
endTimeMinutes: number,
frequency: number,
eventLength: number
): TimeFrame[] => {
let initialTime = startTimeMinutes;
const finalizationTime = endTimeMinutes;
const result = [] as TimeFrame[];
// Ensure that both the frequency and event length are at least 1 minute, if they
// would be zero, we would have an infinite loop in this while!
const frequencyMinimumOne = minimumOfOne(frequency);
const eventLengthMinimumOne = minimumOfOne(eventLength);
while (initialTime < finalizationTime) {
const periodTime = initialTime + frequencyMinimumOne;
const slotEndTime = initialTime + eventLengthMinimumOne;
/*
check if the slot end time surpasses availability end time of the user
1 minute is added to round up the hour mark so that end of the slot is considered in the check instead of x9
eg: if finalization time is 11:59, slotEndTime is 12:00, we ideally want the slot to be available
*/
if (slotEndTime <= finalizationTime + 1) result.push({ startTime: initialTime, endTime: periodTime });
// Ensure that both the frequency and event length are at least 1 minute, if they
// would be zero, we would have an infinite loop in this while!
initialTime += frequencyMinimumOne;
}
return result;
};
function buildSlots({
startOfInviteeDay,
computedLocalAvailability,
@@ -63,24 +28,75 @@ function buildSlots({
frequency: number;
eventLength: number;
}) {
const slotsTimeFrameAvailable: TimeFrame[] = [];
// no slots today
if (startOfInviteeDay.isBefore(startDate, "day")) {
return [];
}
// keep the old safeguards in; may be needed.
frequency = minimumOfOne(frequency);
eventLength = minimumOfOne(eventLength);
// A day starts at 00:00 unless the startDate is the same as the current day
const dayStart = startOfInviteeDay.isSame(startDate, "day")
? Math.ceil((startDate.hour() * 60 + startDate.minute()) / frequency) * frequency
: 0;
computedLocalAvailability.forEach((item) => {
const userSlotsTimeFrameAvailable = splitAvailableTime(
item.startTime,
item.endTime,
frequency,
eventLength
).map((slot) => ({ ...slot, userIds: item.userIds }));
// Record type so we can use slotStart as key
const slotsTimeFrameAvailable: Record<
string,
{
userIds: number[];
startTime: number;
endTime: number;
}
> = {};
// get boundaries sorted by start time.
const boundaries = computedLocalAvailability
.map((item) => [item.startTime < dayStart ? dayStart : item.startTime, item.endTime])
.sort((a, b) => a[0] - b[0]);
slotsTimeFrameAvailable.push(...userSlotsTimeFrameAvailable);
});
const ranges: number[][] = [];
let currentRange: number[] = [];
for (const [start, end] of boundaries) {
// bypass invalid value
if (start >= end) continue;
// fill first elem
if (!currentRange.length) {
currentRange = [start, end];
continue;
}
if (currentRange[1] < start) {
ranges.push(currentRange);
currentRange = [start, end];
} else if (currentRange[1] < end) {
currentRange[1] = end;
}
}
if (currentRange) {
ranges.push(currentRange);
}
const slots: { [x: string]: { time: Dayjs; userIds?: number[] } } = {};
slotsTimeFrameAvailable.forEach((item) => {
// XXX: Hack alert, as dayjs is supposedly not aware of timezone the current slot may have invalid UTC offset.
const timeZone =
(startOfInviteeDay as unknown as { $x: { $timezone: string } })["$x"]["$timezone"] || "UTC";
for (const [boundaryStart, boundaryEnd] of ranges) {
// loop through the day, based on frequency.
for (let slotStart = boundaryStart; slotStart < boundaryEnd; slotStart += frequency) {
computedLocalAvailability.forEach((item) => {
// TODO: This logic does not allow for past-midnight bookings.
if (slotStart < item.startTime || slotStart > item.endTime + 15 - eventLength) {
return;
}
slotsTimeFrameAvailable[slotStart.toString()] = {
userIds: (slotsTimeFrameAvailable[slotStart]?.userIds || []).concat(item.userIds || []),
startTime: slotStart,
endTime: slotStart + eventLength,
};
});
}
}
// XXX: Hack alert, as dayjs is supposedly not aware of timezone the current slot may have invalid UTC offset.
const timeZone =
(startOfInviteeDay as unknown as { $x: { $timezone: string } })["$x"]["$timezone"] || "UTC";
const slots: { time: Dayjs; userIds?: number[] }[] = [];
for (const item of Object.values(slotsTimeFrameAvailable)) {
/*
* @calcom/web:dev: 2022-11-06T00:00:00-04:00
* @calcom/web:dev: 2022-11-06T01:00:00-04:00
@@ -97,22 +113,9 @@ function buildSlots({
// As the time has now fallen backwards, or forwards; this difference -
// needs to be manually added as this is not done for us. Usually 0.
slot.time = slot.time.add(startOfInviteeDay.utcOffset() - slot.time.utcOffset(), "minutes");
if (slots[slot.time.format()]) {
slots[slot.time.format()] = {
...slot,
userIds: [...(slots[slot.time.format()].userIds || []), ...(item.userIds || [])],
};
return;
}
// Validating slot its not on the past
if (slot.time.isBefore(startDate)) {
return;
}
slots[slot.time.format()] = slot;
});
return Object.values(slots);
slots.push(slot);
}
return slots;
}
const getSlots = ({
+72 -59
View File
@@ -265,7 +265,6 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
);
const workingHours = getAggregateWorkingHours(userAvailability, eventType.schedulingType);
const computedAvailableSlots: Record<string, Slot[]> = {};
const availabilityCheckProps = {
eventLength: eventType.length,
currentSeats,
@@ -280,67 +279,80 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
periodDays: eventType.periodDays,
});
let currentCheckedTime = startTime;
let getSlotsTime = 0;
const getSlotsTime = 0;
let checkForAvailabilityTime = 0;
let getSlotsCount = 0;
const getSlotsCount = 0;
let checkForAvailabilityCount = 0;
do {
const startGetSlots = performance.now();
const timeSlots: ReturnType<typeof getTimeSlots> = [];
for (
let currentCheckedTime = startTime;
currentCheckedTime.isBefore(endTime);
currentCheckedTime = currentCheckedTime.add(1, "day")
) {
// get slots retrieves the available times for a given day
const timeSlots = getTimeSlots({
inviteeDate: currentCheckedTime,
eventLength: input.duration || eventType.length,
workingHours,
dateOverrides,
minimumBookingNotice: eventType.minimumBookingNotice,
frequency: eventType.slotInterval || input.duration || eventType.length,
});
timeSlots.push(
...getTimeSlots({
inviteeDate: currentCheckedTime,
eventLength: input.duration || eventType.length,
workingHours,
dateOverrides,
minimumBookingNotice: eventType.minimumBookingNotice,
frequency: eventType.slotInterval || input.duration || eventType.length,
})
);
}
const endGetSlots = performance.now();
getSlotsTime += endGetSlots - startGetSlots;
getSlotsCount++;
const isCollective = !eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE;
const isCollective = !eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE;
let availableTimeSlots: typeof timeSlots = [];
if (isCollective) {
availableTimeSlots = timeSlots.filter((slot) =>
userAvailability.every((schedule) => {
const startCheckForAvailability = performance.now();
const isAvailable = checkIfIsAvailable({
time: slot.time,
...schedule,
...availabilityCheckProps,
});
const endCheckForAvailability = performance.now();
checkForAvailabilityCount++;
checkForAvailabilityTime += endCheckForAvailability - startCheckForAvailability;
return isAvailable;
})
);
} else {
availableTimeSlots = timeSlots
.map((slot) => {
slot.userIds = slot.userIds?.filter((slotUserId) => {
const userSchedule = userAvailability.find(({ userId }) => userId === slotUserId);
if (!userSchedule) {
throw new TRPCError({
message: "Shouldn't happen that we don't have a matching user schedule here",
code: "INTERNAL_SERVER_ERROR",
});
}
return checkIfIsAvailable({
time: slot.time,
...userSchedule,
...availabilityCheckProps,
});
});
return slot;
})
.filter((slot) => slot.userIds && slot.userIds.length > 0);
}
const availableTimeSlots = timeSlots
.filter((slot) => isTimeWithinBounds(slot.time))
.filter((slot) =>
isCollective
? // The slot should be available for every user
userAvailability.every((schedule) => {
const startCheckForAvailability = performance.now();
const isAvailable = checkIfIsAvailable({
time: slot.time,
...schedule,
...availabilityCheckProps,
});
const endCheckForAvailability = performance.now();
checkForAvailabilityCount++;
checkForAvailabilityTime += endCheckForAvailability - startCheckForAvailability;
return isAvailable;
})
: (() => {
// The slot should be available for the atleast one of the slot owners.
return slot.userIds?.some((slotUserId) => {
const userSchedule = userAvailability.find(({ userId }) => userId === slotUserId);
if (!userSchedule) {
throw new TRPCError({
message: "Shouldn't happen that we don't have a matching user schedule here",
code: "INTERNAL_SERVER_ERROR",
});
}
return checkIfIsAvailable({
time: slot.time,
...userSchedule,
...availabilityCheckProps,
});
});
})()
);
availableTimeSlots = availableTimeSlots.filter((slot) => isTimeWithinBounds(slot.time));
computedAvailableSlots[currentCheckedTime.format("YYYY-MM-DD")] = availableTimeSlots.map(
({ time: time, ...passThroughProps }) => ({
const computedAvailableSlots = availableTimeSlots.reduce(
(
r: Record<string, { time: string; users: string[]; attendees?: number; bookingUid?: string }[]>,
{ time: time, ...passThroughProps }
) => {
r[time.format("YYYY-MM-DD")] = r[time.format("YYYY-MM-DD")] || [];
r[time.format("YYYY-MM-DD")].push({
...passThroughProps,
time: time.toISOString(),
users: eventType.users.map((user) => user.username || ""),
@@ -355,10 +367,11 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
currentSeats.findIndex((booking) => booking.startTime.toISOString() === time.toISOString())
].uid,
}),
})
);
currentCheckedTime = currentCheckedTime.add(1, "day");
} while (currentCheckedTime.isBefore(endTime));
});
return r;
},
Object.create(null)
);
logger.debug(`getSlots took ${getSlotsTime}ms and executed ${getSlotsCount} times`);