fix: validate Round Robin host availability in handleNewBooking (#22253)

* fix: validate Round Robin host availability in handleNewBooking

- Add validation to ensure Round Robin events have at least one available non-fixed host
- Throw NoAvailableUsersFound error when no Round Robin hosts are available
- Add unit test to verify the fix works correctly
- Fixes issue where Round Robin events with fixed hosts could be booked without Round Robin hosts

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* test: fix host configuration in Round Robin test

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* test: improve Round Robin test to only make RR host busy

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: correct Round Robin validation to only check when RR hosts assigned

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: refine Round Robin validation to only apply when both fixed and RR hosts present

- Add fixedUserPool.length > 0 condition to validation
- Ensures validation only triggers for specific bug scenario: events with fixed hosts + RR hosts but no available RR hosts
- Prevents blocking normal Round Robin events that only have RR hosts
- Updates test description to reflect more precise validation logic

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: simplify Round Robin validation to resolve E2E test failures

Remove overly restrictive fixedUserPool.length > 0 condition that was
blocking valid Round Robin booking scenarios in E2E tests. The validation
now only checks if Round Robin hosts are assigned but none are available,
which is the intended behavior for the bug fix.

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: restore fixedUserPool condition to Round Robin validation

- Add back fixedUserPool.length > 0 condition to make validation specific to bug scenario
- Only triggers when Round Robin events have both fixed hosts AND Round Robin hosts but no available Round Robin hosts
- Prevents blocking normal Round Robin events that only have Round Robin hosts (like in organization settings E2E test)
- Updates test description to reflect more precise validation logic

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* throw error if no RR user is available

* add tests

* fix comments

* revert change

* remove comments

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
This commit is contained in:
Carina Wollendorfer
2025-07-11 16:47:21 +01:00
committed by GitHub
co-authored by carina@cal.com <c.wollendorfer@me.com> carina@cal.com <c.wollendorfer@me.com> Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> CarinaWolli
parent 14e14289f0
commit 45698db0b4
11 changed files with 269 additions and 12 deletions
@@ -440,7 +440,11 @@ describe("RerouteDialog", () => {
render(
<SessionProvider session={mockSession}>
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
<RerouteDialog
isOpenDialog={true}
setIsOpenDialog={mockSetIsOpenDialog}
booking={mockBooking}
/>
</TooltipProvider>
</SessionProvider>
);
@@ -483,7 +487,11 @@ describe("RerouteDialog", () => {
render(
<SessionProvider session={mockSession}>
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
<RerouteDialog
isOpenDialog={true}
setIsOpenDialog={mockSetIsOpenDialog}
booking={mockBooking}
/>
</TooltipProvider>
</SessionProvider>
);
@@ -116,6 +116,8 @@
"delete_calendar_event_error": "Unable to delete Calendar event.",
"already_signed_up_for_this_booking_error": "You are already signed up for this booking.",
"hosts_unavailable_for_booking": "Some of the hosts are unavailable for booking.",
"fixed_hosts_unavailable_for_booking": "Some of the fixed hosts are unavailable for booking.",
"round_robin_hosts_unavailable_for_booking": "No Round Robin hosts is available for booking.",
"help": "Help",
"price": "Price",
"paid": "Paid",
@@ -677,7 +677,7 @@ export default class GoogleCalendarService implements Calendar {
const fromDate = new Date(dateFrom);
const toDate = new Date(dateTo);
const oneDayMs = 1000 * 60 * 60 * 24;
const diff = Math.floor((toDate.getTime() - fromDate.getTime()) / (oneDayMs));
const diff = Math.floor((toDate.getTime() - fromDate.getTime()) / oneDayMs);
// Google API only allows a date range of 90 days for /freebusy
if (diff <= 90) {
@@ -893,10 +893,17 @@ async function handler(
luckyUsers.push(newLuckyUser);
}
}
// ALL fixed users must be available
if (fixedUserPool.length !== users.filter((user) => user.isFixed).length) {
throw new Error(ErrorCode.HostsUnavailableForBooking);
throw new Error(ErrorCode.FixedHostsUnavailableForBooking);
}
// If there are RR hosts, we need to find a lucky user
if ([...qualifiedRRUsers, ...additionalFallbackRRUsers].length > 0 && luckyUsers.length === 0) {
throw new Error(ErrorCode.RoundRobinHostsUnavailableForBooking);
}
// Pushing fixed user before the luckyUser guarantees the (first) fixed user as the organizer.
users = [...fixedUserPool, ...luckyUsers];
luckyUserResponse = { luckyUsers: luckyUsers.map((u) => u.id) };
@@ -926,7 +933,7 @@ async function handler(
if (users.length === 0 && eventType.schedulingType === SchedulingType.ROUND_ROBIN) {
loggerWithEventDetails.error(`No available users found for round robin event.`);
throw new Error(ErrorCode.NoAvailableUsersFound);
throw new Error(ErrorCode.RoundRobinHostsUnavailableForBooking);
}
// If the team member is requested then they should be the organizer
@@ -209,7 +209,7 @@ describe("handleNewBooking", () => {
await handleNewBooking({
bookingData: mockBookingData,
})
).rejects.toThrowError(ErrorCode.HostsUnavailableForBooking);
).rejects.toThrowError(ErrorCode.FixedHostsUnavailableForBooking);
},
timeout
);
@@ -298,7 +298,7 @@ describe("handleNewBooking", () => {
await handleNewBooking({
bookingData: mockBookingData,
})
).rejects.toThrowError(ErrorCode.HostsUnavailableForBooking);
).rejects.toThrowError(ErrorCode.FixedHostsUnavailableForBooking);
},
timeout
);
@@ -0,0 +1,238 @@
import {
createBookingScenario,
getBooker,
getOrganizer,
getScenarioData,
mockCalendar,
TestData,
Timezones,
getDate,
getGoogleCalendarCredential,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { getMockRequestDataForBooking } from "@calcom/web/test/utils/bookingScenario/getMockRequestDataForBooking";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import { describe, expect } from "vitest";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { SchedulingType } from "@calcom/prisma/enums";
import { test } from "@calcom/web/test/fixtures/fixtures";
const timeout = process.env.CI ? 5000 : 20000;
describe("handleNewBooking - Round Robin Host Validation", () => {
setupAndTeardown();
test(
"should throw NoAvailableUsersFound when Round Robin event has both fixed and round robin hosts busy",
async () => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const booker = getBooker({
email: "booker@example.com",
name: "Booker",
});
const fixedHost = getOrganizer({
name: "Fixed Host",
email: "fixed-host@example.com",
id: 101,
schedules: [TestData.schedules.IstMorningShift],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
});
const roundRobinHost = {
name: "Round Robin Host",
username: "round-robin-host",
timeZone: Timezones["+5:30"],
email: "round-robin-host@example.com",
id: 102,
schedules: [TestData.schedules.IstMorningShift],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
};
const scenarioData = getScenarioData({
eventTypes: [
{
id: 1,
slotInterval: 45,
length: 45,
hosts: [
{
userId: 101,
isFixed: true,
},
{
userId: 102,
isFixed: false,
},
],
schedulingType: SchedulingType.ROUND_ROBIN,
},
],
organizer: fixedHost,
usersApartFromOrganizer: [roundRobinHost],
bookings: [
{
userId: 101, // Make fixed host busy
eventTypeId: 1,
startTime: `${getDate({ dateIncrement: 1 }).dateString}T04:00:00.000Z`,
endTime: `${getDate({ dateIncrement: 1 }).dateString}T04:45:00.000Z`,
status: "ACCEPTED",
attendees: [
{
email: "existing-booker@example.com",
name: "Existing Booker",
},
],
},
{
userId: 102, // Make round robin host busy
eventTypeId: 1,
startTime: `${getDate({ dateIncrement: 1 }).dateString}T04:00:00.000Z`,
endTime: `${getDate({ dateIncrement: 1 }).dateString}T04:45:00.000Z`,
status: "ACCEPTED",
attendees: [
{
email: "existing-booker2@example.com",
name: "Existing Booker 2",
},
],
},
],
});
await createBookingScenario(scenarioData);
mockCalendar("googlecalendar", {
create: {
id: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
busySlots: [],
});
const mockBookingData = getMockRequestDataForBooking({
data: {
eventTypeId: 1,
start: `${getDate({ dateIncrement: 1 }).dateString}T04:00:00.000Z`,
end: `${getDate({ dateIncrement: 1 }).dateString}T04:45:00.000Z`,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: "integrations:daily" },
},
},
});
await expect(
handleNewBooking({
bookingData: mockBookingData,
})
).rejects.toThrow(ErrorCode.NoAvailableUsersFound);
},
timeout
);
test(
"should throw RoundRobinHostsUnavailableForBooking when Round Robin event has fixed hosts but no round robin host is available",
async () => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const booker = getBooker({
email: "booker@example.com",
name: "Booker",
});
const fixedHost = getOrganizer({
name: "Fixed Host",
email: "fixed-host@example.com",
id: 101,
schedules: [TestData.schedules.IstMorningShift],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
});
const roundRobinHost = {
name: "Round Robin Host",
username: "round-robin-host",
timeZone: Timezones["+5:30"],
email: "round-robin-host@example.com",
id: 102,
schedules: [TestData.schedules.IstMorningShift],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
};
const scenarioData = getScenarioData({
eventTypes: [
{
id: 1,
slotInterval: 45,
length: 45,
hosts: [
{
userId: 101,
isFixed: true,
},
{
userId: 102,
isFixed: false,
},
],
schedulingType: SchedulingType.ROUND_ROBIN,
},
],
organizer: fixedHost,
usersApartFromOrganizer: [roundRobinHost],
bookings: [
{
userId: 102, // Make round robin host busy with an existing booking
eventTypeId: 1,
startTime: `${getDate({ dateIncrement: 1 }).dateString}T04:00:00.000Z`,
endTime: `${getDate({ dateIncrement: 1 }).dateString}T04:45:00.000Z`,
status: "ACCEPTED",
attendees: [
{
email: "existing-booker@example.com",
name: "Existing Booker",
},
],
},
],
});
await createBookingScenario(scenarioData);
mockCalendar("googlecalendar", {
create: {
id: "MOCKED_GOOGLE_CALENDAR_EVENT_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
busySlots: [],
});
const mockBookingData = getMockRequestDataForBooking({
data: {
eventTypeId: 1,
start: `${getDate({ dateIncrement: 1 }).dateString}T04:00:00.000Z`,
end: `${getDate({ dateIncrement: 1 }).dateString}T04:45:00.000Z`,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: "integrations:daily" },
},
},
});
await expect(
handleNewBooking({
bookingData: mockBookingData,
})
).rejects.toThrow(ErrorCode.RoundRobinHostsUnavailableForBooking);
},
timeout
);
});
@@ -360,7 +360,7 @@ describe("handleNewBooking", () => {
await handleNewBooking({
bookingData: mockBookingData,
});
}).rejects.toThrowError(ErrorCode.HostsUnavailableForBooking);
}).rejects.toThrowError(ErrorCode.FixedHostsUnavailableForBooking);
},
timeout
);
@@ -21,7 +21,6 @@ import {
enrichUserWithDelegationCredentialsIncludeServiceAccountKey,
} from "@calcom/lib/delegationCredential/server";
import { getEventName } from "@calcom/lib/event";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import { IdempotencyKeyService } from "@calcom/lib/idempotencyKey/idempotencyKeyService";
import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";
import logger from "@calcom/lib/logger";
+2 -1
View File
@@ -4,7 +4,8 @@ export enum ErrorCode {
ChargeCardFailure = "couldnt_charge_card_error",
RequestBodyWithouEnd = "request_body_end_time_internal_error",
AlreadySignedUpForBooking = "already_signed_up_for_this_booking_error",
HostsUnavailableForBooking = "hosts_unavailable_for_booking",
FixedHostsUnavailableForBooking = "fixed_hosts_unavailable_for_booking",
RoundRobinHostsUnavailableForBooking = "round_robin_hosts_unavailable_for_booking",
EventTypeNotFound = "event_type_not_found_error",
BookingNotFound = "booking_not_found_error",
BookingSeatsFull = "booking_seats_full_error",
@@ -26,7 +26,8 @@ const test404Codes = [
const test409Codes = [
ErrorCode.NoAvailableUsersFound,
ErrorCode.HostsUnavailableForBooking,
ErrorCode.FixedHostsUnavailableForBooking,
ErrorCode.RoundRobinHostsUnavailableForBooking,
ErrorCode.AlreadySignedUpForBooking,
ErrorCode.BookingSeatsFull,
ErrorCode.NotEnoughAvailableSeats,
@@ -114,7 +114,8 @@ function getStatusCode(cause: Error | ErrorWithCode): number {
return 400;
// 409 Conflict
case ErrorCode.NoAvailableUsersFound:
case ErrorCode.HostsUnavailableForBooking:
case ErrorCode.FixedHostsUnavailableForBooking:
case ErrorCode.RoundRobinHostsUnavailableForBooking:
case ErrorCode.AlreadySignedUpForBooking:
case ErrorCode.BookingSeatsFull:
case ErrorCode.NotEnoughAvailableSeats: