perf: Optimize team bookings query by fetching data for multiple users at once (#21137)
Co-authored-by: [email protected] <[email protected]> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
ab8556790e
commit
d770cfc65e
4 files changed
+646
-49
No files matched your search
@@ -182,6 +182,18 @@ export type GetUserAvailabilityInitialData = {
|
||||
reason: Pick<OutOfOfficeReason, "id" | "emoji" | "reason"> | null;
|
||||
})[];
|
||||
busyTimesFromLimitsBookings: EventBusyDetails[];
|
||||
busyTimesFromLimits?: Map<number, EventBusyDetails[]>;
|
||||
eventTypeForLimits?: {
|
||||
id: number;
|
||||
bookingLimits?: unknown;
|
||||
durationLimits?: unknown;
|
||||
} | null;
|
||||
teamBookingLimits?: Map<number, EventBusyDetails[]>;
|
||||
teamForBookingLimits?: {
|
||||
id: number;
|
||||
bookingLimits?: unknown;
|
||||
includeManagedEventsInLimits: boolean;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type GetAvailabilityUser = NonNullable<GetUserAvailabilityInitialData["user"]>;
|
||||
@@ -352,40 +364,49 @@ const _getUserAvailability = async function getUsersWorkingHoursLifeTheUniverseA
|
||||
const bookingLimits = parseBookingLimit(eventType?.bookingLimits);
|
||||
const durationLimits = parseDurationLimit(eventType?.durationLimits);
|
||||
|
||||
const busyTimesFromLimits =
|
||||
eventType && (bookingLimits || durationLimits)
|
||||
? await getBusyTimesFromLimits(
|
||||
bookingLimits,
|
||||
durationLimits,
|
||||
dateFrom.tz(timeZone),
|
||||
dateTo.tz(timeZone),
|
||||
duration,
|
||||
eventType,
|
||||
initialData?.busyTimesFromLimitsBookings ?? [],
|
||||
timeZone,
|
||||
initialData?.rescheduleUid ?? undefined
|
||||
)
|
||||
: [];
|
||||
let busyTimesFromLimits: EventBusyDetails[] = [];
|
||||
|
||||
if (initialData?.busyTimesFromLimits && initialData?.eventTypeForLimits) {
|
||||
busyTimesFromLimits = initialData.busyTimesFromLimits.get(user.id) || [];
|
||||
} else if (eventType && (bookingLimits || durationLimits)) {
|
||||
// Fall back to individual query if not available in initialData
|
||||
busyTimesFromLimits = await getBusyTimesFromLimits(
|
||||
bookingLimits,
|
||||
durationLimits,
|
||||
dateFrom.tz(timeZone),
|
||||
dateTo.tz(timeZone),
|
||||
duration,
|
||||
eventType,
|
||||
initialData?.busyTimesFromLimitsBookings ?? [],
|
||||
timeZone,
|
||||
initialData?.rescheduleUid ?? undefined
|
||||
);
|
||||
}
|
||||
|
||||
const teamForBookingLimits =
|
||||
initialData?.teamForBookingLimits ??
|
||||
eventType?.team ??
|
||||
(eventType?.parent?.team?.includeManagedEventsInLimits ? eventType?.parent?.team : null);
|
||||
|
||||
const teamBookingLimits = parseBookingLimit(teamForBookingLimits?.bookingLimits);
|
||||
|
||||
const busyTimesFromTeamLimits =
|
||||
teamForBookingLimits && teamBookingLimits
|
||||
? await getBusyTimesFromTeamLimits(
|
||||
user,
|
||||
teamBookingLimits,
|
||||
dateFrom.tz(timeZone),
|
||||
dateTo.tz(timeZone),
|
||||
teamForBookingLimits.id,
|
||||
teamForBookingLimits.includeManagedEventsInLimits,
|
||||
timeZone,
|
||||
initialData?.rescheduleUid ?? undefined
|
||||
)
|
||||
: [];
|
||||
let busyTimesFromTeamLimits: EventBusyDetails[] = [];
|
||||
|
||||
if (initialData?.teamBookingLimits && teamForBookingLimits) {
|
||||
busyTimesFromTeamLimits = initialData.teamBookingLimits.get(user.id) || [];
|
||||
} else if (teamForBookingLimits && teamBookingLimits) {
|
||||
// Fall back to individual query if not available in initialData
|
||||
busyTimesFromTeamLimits = await getBusyTimesFromTeamLimits(
|
||||
user,
|
||||
teamBookingLimits,
|
||||
dateFrom.tz(timeZone),
|
||||
dateTo.tz(timeZone),
|
||||
teamForBookingLimits.id,
|
||||
teamForBookingLimits.includeManagedEventsInLimits,
|
||||
timeZone,
|
||||
initialData?.rescheduleUid ?? undefined
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: only query what we need after applying limits (shrink date range)
|
||||
const getBusyTimesStart = dateFrom.toISOString();
|
||||
@@ -598,10 +619,15 @@ export const getPeriodStartDatesBetween = (
|
||||
return monitorCallbackSync(_getPeriodStartDatesBetween, ...args);
|
||||
};
|
||||
|
||||
const _getPeriodStartDatesBetween = (dateFrom: Dayjs, dateTo: Dayjs, period: IntervalLimitUnit) => {
|
||||
const _getPeriodStartDatesBetween = (
|
||||
dateFrom: Dayjs,
|
||||
dateTo: Dayjs,
|
||||
period: IntervalLimitUnit,
|
||||
timeZone?: string
|
||||
) => {
|
||||
const dates = [];
|
||||
let startDate = dayjs(dateFrom).startOf(period);
|
||||
const endDate = dayjs(dateTo).endOf(period);
|
||||
let startDate = timeZone ? dayjs(dateFrom).tz(timeZone).startOf(period) : dayjs(dateFrom).startOf(period);
|
||||
const endDate = timeZone ? dayjs(dateTo).tz(timeZone).endOf(period) : dayjs(dateTo).endOf(period);
|
||||
|
||||
while (startDate.isBefore(endDate)) {
|
||||
dates.push(startDate);
|
||||
|
||||
@@ -14,31 +14,32 @@ export default class LimitManager {
|
||||
/**
|
||||
* Creates a busy map key
|
||||
*/
|
||||
private static createKey(start: Dayjs, unit: IntervalLimitUnit): BusyMapKey {
|
||||
return `${unit}-${start.startOf(unit).toISOString()}`;
|
||||
private static createKey(start: Dayjs, unit: IntervalLimitUnit, timeZone?: string): BusyMapKey {
|
||||
const tzStart = timeZone ? start.tz(timeZone) : start;
|
||||
return `${unit}-${tzStart.startOf(unit).toISOString()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if already marked busy by ancestors or siblings
|
||||
*/
|
||||
isAlreadyBusy(start: Dayjs, unit: IntervalLimitUnit) {
|
||||
if (this.busyMap.has(LimitManager.createKey(start, "year"))) return true;
|
||||
isAlreadyBusy(start: Dayjs, unit: IntervalLimitUnit, timeZone?: string) {
|
||||
if (this.busyMap.has(LimitManager.createKey(start, "year", timeZone))) return true;
|
||||
|
||||
if (unit === "month" && this.busyMap.has(LimitManager.createKey(start, "month"))) {
|
||||
if (unit === "month" && this.busyMap.has(LimitManager.createKey(start, "month", timeZone))) {
|
||||
return true;
|
||||
} else if (
|
||||
unit === "week" &&
|
||||
// weeks can be part of two months
|
||||
((this.busyMap.has(LimitManager.createKey(start, "month")) &&
|
||||
this.busyMap.has(LimitManager.createKey(start.endOf("week"), "month"))) ||
|
||||
this.busyMap.has(LimitManager.createKey(start, "week")))
|
||||
((this.busyMap.has(LimitManager.createKey(start, "month", timeZone)) &&
|
||||
this.busyMap.has(LimitManager.createKey(start.endOf("week"), "month", timeZone))) ||
|
||||
this.busyMap.has(LimitManager.createKey(start, "week", timeZone)))
|
||||
) {
|
||||
return true;
|
||||
} else if (
|
||||
unit === "day" &&
|
||||
(this.busyMap.has(LimitManager.createKey(start, "month")) ||
|
||||
this.busyMap.has(LimitManager.createKey(start, "week")) ||
|
||||
this.busyMap.has(LimitManager.createKey(start, "day")))
|
||||
(this.busyMap.has(LimitManager.createKey(start, "month", timeZone)) ||
|
||||
this.busyMap.has(LimitManager.createKey(start, "week", timeZone)) ||
|
||||
this.busyMap.has(LimitManager.createKey(start, "day", timeZone)))
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
@@ -49,10 +50,11 @@ export default class LimitManager {
|
||||
/**
|
||||
* Adds a new busy time
|
||||
*/
|
||||
addBusyTime(start: Dayjs, unit: IntervalLimitUnit) {
|
||||
this.busyMap.set(`${unit}-${start.toISOString()}`, {
|
||||
start: start.toISOString(),
|
||||
end: start.endOf(unit).toISOString(),
|
||||
addBusyTime(start: Dayjs, unit: IntervalLimitUnit, timeZone?: string) {
|
||||
const tzStart = timeZone ? start.tz(timeZone) : start;
|
||||
this.busyMap.set(`${unit}-${tzStart.toISOString()}`, {
|
||||
start: tzStart.toISOString(),
|
||||
end: tzStart.endOf(unit).toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,22 @@ type TeamBookingsParamsBase = {
|
||||
shouldReturnCount?: boolean;
|
||||
};
|
||||
|
||||
type TeamBookingsMultipleUsersParamsBase = {
|
||||
users: { id: number; email: string }[];
|
||||
teamId: number;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
excludedUid?: string | null;
|
||||
includeManagedEvents: boolean;
|
||||
shouldReturnCount?: boolean;
|
||||
};
|
||||
|
||||
type TeamBookingsMultipleUsersParamsWithCount = TeamBookingsMultipleUsersParamsBase & {
|
||||
shouldReturnCount: true;
|
||||
};
|
||||
|
||||
type TeamBookingsMultipleUsersParamsWithoutCount = TeamBookingsMultipleUsersParamsBase;
|
||||
|
||||
type TeamBookingsParamsWithCount = TeamBookingsParamsBase & {
|
||||
shouldReturnCount: true;
|
||||
};
|
||||
@@ -666,4 +682,116 @@ export class BookingRepository {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async getAllAcceptedTeamBookingsOfUsers(
|
||||
params: TeamBookingsMultipleUsersParamsWithCount
|
||||
): Promise<number>;
|
||||
|
||||
static async getAllAcceptedTeamBookingsOfUsers(
|
||||
params: TeamBookingsMultipleUsersParamsWithoutCount
|
||||
): Promise<Array<Booking>>;
|
||||
|
||||
static async getAllAcceptedTeamBookingsOfUsers(params: TeamBookingsMultipleUsersParamsBase) {
|
||||
const { users, teamId, startDate, endDate, excludedUid, shouldReturnCount, includeManagedEvents } =
|
||||
params;
|
||||
|
||||
const baseWhere: Prisma.BookingWhereInput = {
|
||||
status: BookingStatus.ACCEPTED,
|
||||
startTime: {
|
||||
gte: startDate,
|
||||
},
|
||||
endTime: {
|
||||
lte: endDate,
|
||||
},
|
||||
...(excludedUid && {
|
||||
uid: {
|
||||
not: excludedUid,
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const userIds = users.map((user) => user.id);
|
||||
const userEmails = users.map((user) => user.email);
|
||||
|
||||
const whereCollectiveRoundRobinOwner: Prisma.BookingWhereInput = {
|
||||
...baseWhere,
|
||||
userId: {
|
||||
in: userIds,
|
||||
},
|
||||
eventType: {
|
||||
teamId,
|
||||
},
|
||||
};
|
||||
|
||||
const whereCollectiveRoundRobinBookingsAttendee: Prisma.BookingWhereInput = {
|
||||
...baseWhere,
|
||||
attendees: {
|
||||
some: {
|
||||
email: {
|
||||
in: userEmails,
|
||||
},
|
||||
},
|
||||
},
|
||||
eventType: {
|
||||
teamId,
|
||||
},
|
||||
};
|
||||
|
||||
const whereManagedBookings: Prisma.BookingWhereInput = {
|
||||
...baseWhere,
|
||||
userId: {
|
||||
in: userIds,
|
||||
},
|
||||
eventType: {
|
||||
parent: {
|
||||
teamId,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (shouldReturnCount) {
|
||||
const collectiveRoundRobinBookingsOwner = await prisma.booking.count({
|
||||
where: whereCollectiveRoundRobinOwner,
|
||||
});
|
||||
|
||||
const collectiveRoundRobinBookingsAttendee = await prisma.booking.count({
|
||||
where: whereCollectiveRoundRobinBookingsAttendee,
|
||||
});
|
||||
|
||||
let managedBookings = 0;
|
||||
|
||||
if (includeManagedEvents) {
|
||||
managedBookings = await prisma.booking.count({
|
||||
where: whereManagedBookings,
|
||||
});
|
||||
}
|
||||
|
||||
const totalNrOfBooking =
|
||||
collectiveRoundRobinBookingsOwner + collectiveRoundRobinBookingsAttendee + managedBookings;
|
||||
|
||||
return totalNrOfBooking;
|
||||
}
|
||||
|
||||
const collectiveRoundRobinBookingsOwner = await prisma.booking.findMany({
|
||||
where: whereCollectiveRoundRobinOwner,
|
||||
});
|
||||
|
||||
const collectiveRoundRobinBookingsAttendee = await prisma.booking.findMany({
|
||||
where: whereCollectiveRoundRobinBookingsAttendee,
|
||||
});
|
||||
|
||||
let managedBookings: typeof collectiveRoundRobinBookingsAttendee = [];
|
||||
|
||||
if (includeManagedEvents) {
|
||||
managedBookings = await prisma.booking.findMany({
|
||||
where: whereManagedBookings,
|
||||
});
|
||||
}
|
||||
|
||||
return [
|
||||
...collectiveRoundRobinBookingsOwner,
|
||||
...collectiveRoundRobinBookingsAttendee,
|
||||
...managedBookings,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user