Fixes collective availability for teams with overlapping day timezones (#3898)

* WIP

* Fix for team availability with time offsets

* Prevent empty schedule from opening up everything

* When no utcOffset or timeZone's are given, default to 0 utcOffset (UTC)

* timeZone should not be part of getUserAvailability

* Prevents {days:[X],startTime:0,endTime:0} error entry

* Added getAggregateWorkingHours() (#3913)

* Added test for getAggregateWorkingHours

* Timezone isn't used here anymore

* fix: developer docs url (#3914)

* fix: developer docs url added

* chore : remove /

* chore : import url

Co-authored-by: Zach Waterfield <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>

* Test fixes

* Reinstate prisma (generate only) and few comments

* Test fixes

* Skipping getSchedule again

* Added await to expect() as it involves async logic causing the promise to timeout

* Test cleanup

* Update jest.config.ts

Co-authored-by: Alan <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Zach Waterfield <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-08-22 23:53:51 +00:00
1 parent cb1d881cc0
commit f4ea385c7f
15 files changed
+317 -181

No files matched your search

+68 -87
View File
@@ -1,17 +1,17 @@
import { SchedulingType } from "@prisma/client";
import { z } from "zod";
import { getAggregateWorkingHours } from "@calcom/core/getAggregateWorkingHours";
import type { CurrentSeats } from "@calcom/core/getUserAvailability";
import { getUserAvailability } from "@calcom/core/getUserAvailability";
import dayjs, { Dayjs } from "@calcom/dayjs";
import { getDefaultEvent } from "@calcom/lib/defaultEvents";
import isOutOfBounds from "@calcom/lib/isOutOfBounds";
import isTimeOutOfBounds from "@calcom/lib/isOutOfBounds";
import logger from "@calcom/lib/logger";
import { performance } from "@calcom/lib/server/perfObserver";
import getSlots from "@calcom/lib/slots";
import getTimeSlots from "@calcom/lib/slots";
import prisma, { availabilityUserSelect } from "@calcom/prisma";
import { TimeRange } from "@calcom/types/schedule";
import { ValuesType } from "@calcom/types/utils";
import { TRPCError } from "@trpc/server";
@@ -45,7 +45,7 @@ export type Slot = {
users?: string[];
};
const checkForAvailability = ({
const checkIfIsAvailable = ({
time,
busy,
eventLength,
@@ -57,7 +57,7 @@ const checkForAvailability = ({
eventLength: number;
beforeBufferTime: number;
currentSeats?: CurrentSeats;
}) => {
}): boolean => {
if (currentSeats?.some((booking) => booking.startTime.toISOString() === time.toISOString())) {
return true;
}
@@ -96,6 +96,7 @@ const checkForAvailability = ({
});
};
/** This should be called getAvailableSlots */
export const slotsRouter = createRouter().query("getSchedule", {
input: getScheduleSchema,
async resolve({ input, ctx }) {
@@ -103,15 +104,8 @@ export const slotsRouter = createRouter().query("getSchedule", {
},
});
export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx: { prisma: typeof prisma }) {
if (input.debug === true) {
logger.setSettings({ minLevel: "debug" });
}
if (process.env.INTEGRATION_TEST_MODE === "true") {
logger.setSettings({ minLevel: "silly" });
}
const startPrismaEventTypeGet = performance.now();
const eventTypeObject = await ctx.prisma.eventType.findUnique({
async function getEventType(ctx: { prisma: typeof prisma }, input: z.infer<typeof getScheduleSchema>) {
return ctx.prisma.eventType.findUnique({
where: {
id: input.eventTypeId,
},
@@ -150,37 +144,52 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
},
},
});
}
const isDynamicBooking = !input.eventTypeId;
async function getDynamicEventType(ctx: { prisma: typeof prisma }, input: z.infer<typeof getScheduleSchema>) {
// For dynamic booking, we need to get and update user credentials, schedule and availability in the eventTypeObject as they're required in the new availability logic
const dynamicEventType = getDefaultEvent(input.eventTypeSlug);
let dynamicEventTypeObject = dynamicEventType;
if (isDynamicBooking) {
const users = await ctx.prisma.user.findMany({
where: {
username: {
in: input.usernameList,
},
const users = await ctx.prisma.user.findMany({
where: {
username: {
in: input.usernameList,
},
select: {
allowDynamicBooking: true,
...availabilityUserSelect,
},
});
const isDynamicAllowed = !users.some((user) => !user.allowDynamicBooking);
if (!isDynamicAllowed) {
throw new TRPCError({
message: "Some of the users in this group do not allow dynamic booking",
code: "UNAUTHORIZED",
});
}
dynamicEventTypeObject = Object.assign({}, dynamicEventType, {
users,
},
select: {
allowDynamicBooking: true,
...availabilityUserSelect,
},
});
const isDynamicAllowed = !users.some((user) => !user.allowDynamicBooking);
if (!isDynamicAllowed) {
throw new TRPCError({
message: "Some of the users in this group do not allow dynamic booking",
code: "UNAUTHORIZED",
});
}
const eventType = isDynamicBooking ? dynamicEventTypeObject : eventTypeObject;
return Object.assign({}, dynamicEventType, {
users,
});
}
function getRegularOrDynamicEventType(
ctx: { prisma: typeof prisma },
input: z.infer<typeof getScheduleSchema>
) {
const isDynamicBooking = !input.eventTypeId;
return isDynamicBooking ? getDynamicEventType(ctx, input) : getEventType(ctx, input);
}
/** This should be called getAvailableSlots */
export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx: { prisma: typeof prisma }) {
if (input.debug === true) {
logger.setSettings({ minLevel: "debug" });
}
if (process.env.INTEGRATION_TEST_MODE === "true") {
logger.setSettings({ minLevel: "silly" });
}
const startPrismaEventTypeGet = performance.now();
const eventType = await getRegularOrDynamicEventType(ctx, input);
const endPrismaEventTypeGet = performance.now();
logger.debug(
`Prisma eventType get took ${endPrismaEventTypeGet - startPrismaEventTypeGet}ms for event:${
@@ -203,12 +212,14 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
}
let currentSeats: CurrentSeats | undefined = undefined;
const userSchedules = await Promise.all(
/* We get all users working hours and busy slots */
const usersWorkingHoursAndBusySlots = await Promise.all(
eventType.users.map(async (currentUser) => {
const {
busy,
workingHours,
currentSeats: _currentSeats,
timeZone,
} = await getUserAvailability(
{
userId: currentUser.id,
@@ -223,52 +234,22 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
if (!currentSeats && _currentSeats) currentSeats = _currentSeats;
return {
timeZone,
workingHours,
busy,
};
})
);
// flatMap does not work for COLLECTIVE events
const workingHours = userSchedules?.reduce(
(currentValue: ValuesType<typeof userSchedules>["workingHours"], s) => {
// Collective needs to be exclusive of overlap throughout - others inclusive.
if (eventType.schedulingType === SchedulingType.COLLECTIVE) {
// taking the first item as a base
if (!currentValue.length) {
currentValue.push(...s.workingHours);
return currentValue;
}
// the remaining logic subtracts
return s.workingHours.reduce((compare, workingHour) => {
return compare.map((c) => {
const intersect = workingHour.days.filter((day) => c.days.includes(day));
return intersect.length
? {
days: intersect,
startTime: Math.max(workingHour.startTime, c.startTime),
endTime: Math.min(workingHour.endTime, c.endTime),
}
: c;
});
}, currentValue);
} else {
// flatMap for ROUND_ROBIN and individuals
currentValue.push(...s.workingHours);
}
return currentValue;
},
[]
);
const slots: Record<string, Slot[]> = {};
const workingHours = getAggregateWorkingHours(usersWorkingHoursAndBusySlots, eventType.schedulingType);
const computedAvailableSlots: Record<string, Slot[]> = {};
const availabilityCheckProps = {
eventLength: eventType.length,
beforeBufferTime: eventType.beforeEventBuffer,
currentSeats,
};
const isWithinBounds = (_time: Parameters<typeof isOutOfBounds>[0]) =>
!isOutOfBounds(_time, {
const isTimeWithinBounds = (_time: Parameters<typeof isTimeOutOfBounds>[0]) =>
!isTimeOutOfBounds(_time, {
periodType: eventType.periodType,
periodStartDate: eventType.periodStartDate,
periodEndDate: eventType.periodEndDate,
@@ -276,7 +257,7 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
periodDays: eventType.periodDays,
});
let time = startTime;
let currentCheckedTime = startTime;
let getSlotsTime = 0;
let checkForAvailabilityTime = 0;
let getSlotsCount = 0;
@@ -285,8 +266,8 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
do {
const startGetSlots = performance.now();
// get slots retrieves the available times for a given day
const times = getSlots({
inviteeDate: time,
const timeSlots = getTimeSlots({
inviteeDate: currentCheckedTime,
eventLength: eventType.length,
workingHours,
minimumBookingNotice: eventType.minimumBookingNotice,
@@ -302,18 +283,18 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
? ("every" as const)
: ("some" as const);
const filteredTimes = times.filter(isWithinBounds).filter((time) =>
userSchedules[filterStrategy]((schedule) => {
const availableTimeSlots = timeSlots.filter(isTimeWithinBounds).filter((time) =>
usersWorkingHoursAndBusySlots[filterStrategy]((schedule) => {
const startCheckForAvailability = performance.now();
const result = checkForAvailability({ time, ...schedule, ...availabilityCheckProps });
const isAvailable = checkIfIsAvailable({ time, ...schedule, ...availabilityCheckProps });
const endCheckForAvailability = performance.now();
checkForAvailabilityCount++;
checkForAvailabilityTime += endCheckForAvailability - startCheckForAvailability;
return result;
return isAvailable;
})
);
slots[time.format("YYYY-MM-DD")] = filteredTimes.map((time) => ({
computedAvailableSlots[currentCheckedTime.format("YYYY-MM-DD")] = availableTimeSlots.map((time) => ({
time: time.toISOString(),
users: eventType.users.map((user) => user.username || ""),
// Conditionally add the attendees and booking id to slots object if there is already a booking during that time
@@ -328,17 +309,17 @@ export async function getSchedule(input: z.infer<typeof getScheduleSchema>, ctx:
].uid,
}),
}));
time = time.add(1, "day");
} while (time.isBefore(endTime));
currentCheckedTime = currentCheckedTime.add(1, "day");
} while (currentCheckedTime.isBefore(endTime));
logger.debug(`getSlots took ${getSlotsTime}ms and executed ${getSlotsCount} times`);
logger.debug(
`checkForAvailability took ${checkForAvailabilityTime}ms and executed ${checkForAvailabilityCount} times`
);
logger.silly(`Available slots: ${JSON.stringify(slots)}`);
logger.silly(`Available slots: ${JSON.stringify(computedAvailableSlots)}`);
return {
slots,
slots: computedAvailableSlots,
};
}
@@ -426,7 +426,6 @@ export const viewerTeamsRouter = createProtectedRouter()
return await getUserAvailability(
{
username: member.user.username,
timezone: input.timezone,
dateFrom: input.dateFrom,
dateTo: input.dateTo,
},