Skip to content

Scheduling infrastructure for absolutely everyone.

feat: optimize getLuckyUser to skip data fetching for single user (#25337)

Dhairyashil Shindef6642c17f806
diff --git a/packages/features/bookings/lib/getLuckyUser.test.ts b/packages/features/bookings/lib/getLuckyUser.test.ts
index 4974f6cd1fa..8ab4935f529 100644
--- a/packages/features/bookings/lib/getLuckyUser.test.ts
+++ b/packages/features/bookings/lib/getLuckyUser.test.ts
@@ -1642,3 +1642,41 @@ describe("get interval times", () => {
expect(result).toEqual(new Date("2021-06-20T11:59:59Z")); // Based on the mocked system time
});
});
+
+it("returns the single user correctly without fetching data when only one user available", async () => {
+ const singleUser = buildUser({
+ id: 42,
+ username: "singleuser",
+ name: "Single User",
+ email: "[email protected]",
+ bookings: [],
+ });
+
+ // Create spies to verify no data fetching occurs
+ const spyCalendar = vi.spyOn(CalendarManagerMock, "getBusyCalendarTimes");
+ const spyPrismaUser = vi.spyOn(prismaMock.user, "findMany");
+ const spyPrismaHost = vi.spyOn(prismaMock.host, "findMany");
+ const spyPrismaBooking = vi.spyOn(prismaMock.booking, "findMany");
+ const spyPrismaOOO = vi.spyOn(prismaMock.outOfOfficeEntry, "findMany");
+
+ await expect(
+ luckyUserService.getLuckyUser({
+ availableUsers: [singleUser],
+ eventType: {
+ id: 1,
+ isRRWeightsEnabled: false,
+ team: { rrResetInterval: RRResetInterval.MONTH, rrTimestampBasis: RRTimestampBasis.CREATED_AT },
+ includeNoShowInRRCalculation: false,
+ },
+ allRRHosts: [],
+ routingFormResponse: null,
+ })
+ ).resolves.toStrictEqual(singleUser);
+
+ // Verify no expensive operations were called
+ expect(spyCalendar).not.toHaveBeenCalled();
+ expect(spyPrismaUser).not.toHaveBeenCalled();
+ expect(spyPrismaHost).not.toHaveBeenCalled();
+ expect(spyPrismaBooking).not.toHaveBeenCalled();
+ expect(spyPrismaOOO).not.toHaveBeenCalled();
+});
diff --git a/packages/features/bookings/lib/getLuckyUser.ts b/packages/features/bookings/lib/getLuckyUser.ts
index e0afa668f46..bd2a57b5950 100644
--- a/packages/features/bookings/lib/getLuckyUser.ts
+++ b/packages/features/bookings/lib/getLuckyUser.ts
@@ -916,6 +916,11 @@ export class LuckyUserService implements ILuckyUserService {
weight?: number | null;
}
>(getLuckyUserParams: GetLuckyUserParams<T>) {
+ // Early return if only one available user to avoid unnecessary data fetching
+ if (getLuckyUserParams.availableUsers.length === 1) {
+ return getLuckyUserParams.availableUsers[0];
+ }
+
const fetchedData = await this.fetchAllDataNeededForCalculations(getLuckyUserParams);
const { luckyUser } = this.getLuckyUser_requiresDataToBePreFetched({