Scheduling infrastructure for absolutely everyone.
feat: add booking flags for skipAvailabilityCheck, skipEventLimitsCheck, skipCalendarSyncTaskCreation (#24122)
Volnei Munhoz358434429efd
diff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/handleNewBooking.tsindex f466bd50ed1..7f067f209a9 100644--- a/packages/features/bookings/lib/handleNewBooking.ts+++ b/packages/features/bookings/lib/handleNewBooking.ts@@ -1,4 +1,4 @@-// eslint-disable-next-line no-restricted-imports+import short, { uuid } from "short-uuid";import { v5 as uuidv5 } from "uuid";@@ -403,6 +403,9 @@ export type BookingHandlerInput = {// These used to come from headers but now we're passing them as paramshostname?: string;forcedSlug?: string;+ skipAvailabilityCheck?: boolean;+ skipEventLimitsCheck?: boolean;+ skipCalendarSyncTaskCreation?: boolean;} & PlatformParams;function formatAvailabilitySnapshot(data: {@@ -437,6 +440,9 @@ async function handler(hostname,forcedSlug,areCalendarEventsEnabled = true,+ skipAvailabilityCheck = false,+ skipEventLimitsCheck = false,+ skipCalendarSyncTaskCreation = false,} = input;const isPlatformBooking = !!platformClientId;@@ -511,7 +517,7 @@ async function handler(try {await verifyCodeUnAuthenticated(bookerEmail, verificationCode);- } catch (error) {+ } catch {throw new HttpError({statusCode: 400,message: "invalid_verification_code",@@ -719,12 +725,14 @@ async function handler(location,});- const checkBookingAndDurationLimitsService = getCheckBookingAndDurationLimitsService();- await checkBookingAndDurationLimitsService.checkBookingAndDurationLimits({- eventType,- reqBodyStart: reqBody.start,- reqBodyRescheduleUid: reqBody.rescheduleUid,- });+ if (!skipEventLimitsCheck) {+ const checkBookingAndDurationLimitsService = getCheckBookingAndDurationLimitsService();+ await checkBookingAndDurationLimitsService.checkBookingAndDurationLimits({+ eventType,+ reqBodyStart: reqBody.start,+ reqBodyRescheduleUid: reqBody.rescheduleUid,+ });+ }let luckyUserResponse;let isFirstSeat = true;@@ -798,48 +806,55 @@ async function handler(if (isTeamEvent) {// each fixed user must be availablefor (const key in fixedUsers) {+ if (!skipAvailabilityCheck) {+ await ensureAvailableUsers(+ { ...eventTypeWithUsers, users: [fixedUsers[key]] },+ {+ dateFrom: dayjs(start).tz(reqBody.timeZone).format(),+ dateTo: dayjs(end).tz(reqBody.timeZone).format(),+ timeZone: reqBody.timeZone,+ originalRescheduledBooking: originalRescheduledBooking ?? null,+ },+ loggerWithEventDetails,+ shouldServeCache+ );+ }+ }+ } else {+ if (!skipAvailabilityCheck) {await ensureAvailableUsers(- { ...eventTypeWithUsers, users: [fixedUsers[key]] },+ eventTypeWithUsers,{dateFrom: dayjs(start).tz(reqBody.timeZone).format(),dateTo: dayjs(end).tz(reqBody.timeZone).format(),timeZone: reqBody.timeZone,- originalRescheduledBooking: originalRescheduledBooking ?? null,+ originalRescheduledBooking,},loggerWithEventDetails,shouldServeCache);}- } else {- eventTypeWithUsers.users[0].credentials;- await ensureAvailableUsers(- eventTypeWithUsers,+ }+ }+ }++ if (!input.bookingData.allRecurringDates || input.bookingData.isFirstRecurringSlot) {+ try {+ if (!skipAvailabilityCheck) {+ availableUsers = await ensureAvailableUsers(+ { ...eventTypeWithUsers, users: [...qualifiedRRUsers, ...fixedUsers] as IsFixedAwareUser[] },{- dateFrom: dayjs(start).tz(reqBody.timeZone).format(),- dateTo: dayjs(end).tz(reqBody.timeZone).format(),+ dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),+ dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),timeZone: reqBody.timeZone,originalRescheduledBooking,},loggerWithEventDetails,shouldServeCache);+ } else {+ availableUsers = [...qualifiedRRUsers, ...fixedUsers] as IsFixedAwareUser[];}- }- }-- if (!input.bookingData.allRecurringDates || input.bookingData.isFirstRecurringSlot) {- try {- availableUsers = await ensureAvailableUsers(- { ...eventTypeWithUsers, users: [...qualifiedRRUsers, ...fixedUsers] as IsFixedAwareUser[] },- {- dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),- dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),- timeZone: reqBody.timeZone,- originalRescheduledBooking,- },- loggerWithEventDetails,- shouldServeCache- );} catch {if (additionalFallbackRRUsers.length) {loggerWithEventDetails.debug(@@ -851,20 +866,24 @@ async function handler();// can happen when contact owner not available for 2 weeks or fairness would block at least 2 weeks// use fallback instead- availableUsers = await ensureAvailableUsers(- {- ...eventTypeWithUsers,- users: [...additionalFallbackRRUsers, ...fixedUsers] as IsFixedAwareUser[],- },- {- dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),- dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),- timeZone: reqBody.timeZone,- originalRescheduledBooking,- },- loggerWithEventDetails,- shouldServeCache- );+ if (!skipAvailabilityCheck) {+ availableUsers = await ensureAvailableUsers(+ {+ ...eventTypeWithUsers,+ users: [...additionalFallbackRRUsers, ...fixedUsers] as IsFixedAwareUser[],+ },+ {+ dateFrom: dayjs(reqBody.start).tz(reqBody.timeZone).format(),+ dateTo: dayjs(reqBody.end).tz(reqBody.timeZone).format(),+ timeZone: reqBody.timeZone,+ originalRescheduledBooking,+ },+ loggerWithEventDetails,+ shouldServeCache+ );+ } else {+ availableUsers = [...additionalFallbackRRUsers, ...fixedUsers] as IsFixedAwareUser[];+ }} else {loggerWithEventDetails.debug("Qualified users not available, no fallback users",@@ -880,7 +899,11 @@ async function handler(const nonFixedUsers: IsFixedAwareUser[] = [];availableUsers.forEach((user) => {- user.isFixed ? fixedUserPool.push(user) : nonFixedUsers.push(user);+ if (user.isFixed) {+ fixedUserPool.push(user);+ } else {+ nonFixedUsers.push(user);+ }});// Group non-fixed users by their group IDs@@ -958,17 +981,19 @@ async function handler(const start = input.bookingData.allRecurringDates[i].start;const end = input.bookingData.allRecurringDates[i].end;- await ensureAvailableUsers(- { ...eventTypeWithUsers, users: [newLuckyUser] },- {- dateFrom: dayjs(start).tz(reqBody.timeZone).format(),- dateTo: dayjs(end).tz(reqBody.timeZone).format(),- timeZone: reqBody.timeZone,- originalRescheduledBooking,- },- loggerWithEventDetails,- shouldServeCache- );+ if (!skipAvailabilityCheck) {+ await ensureAvailableUsers(+ { ...eventTypeWithUsers, users: [newLuckyUser] },+ {+ dateFrom: dayjs(start).tz(reqBody.timeZone).format(),+ dateTo: dayjs(end).tz(reqBody.timeZone).format(),+ timeZone: reqBody.timeZone,+ originalRescheduledBooking,+ },+ loggerWithEventDetails,+ shouldServeCache+ );+ }}// if no error, then lucky user is available for the next slotsluckyUsers.push(newLuckyUser);@@ -1000,7 +1025,7 @@ async function handler(// Filter out host groups that have no hosts in themconst nonEmptyHostGroups = Object.fromEntries(- Object.entries(hostGroups).filter(([_groupId, hosts]) => hosts.length > 0)+ Object.entries(hostGroups).filter(([, hosts]) => hosts.length > 0));// If there are RR hosts, we need to find a lucky userif (@@ -1658,9 +1683,10 @@ async function handler(// After polling videoBusyTimes, credentials might have been changed due to refreshment, so query them again.const credentials = await refreshCredentials(allCredentials);const apps = eventTypeAppMetadataOptionalSchema.parse(eventType?.metadata?.apps);- const eventManager = !isDryRun- ? new EventManager({ ...organizerUser, credentials }, apps)- : buildDryRunEventManager();+ const eventManager =+ !isDryRun && !skipCalendarSyncTaskCreation+ ? new EventManager({ ...organizerUser, credentials }, apps)+ : buildDryRunEventManager();let videoCallUrl;@@ -1721,20 +1747,24 @@ async function handler(: evt.responses,};- await originalHostEventManager.deleteEventsAndMeetings({- event: deletionEvent,- bookingReferences: originalRescheduledBooking.references,- });+ if (!skipCalendarSyncTaskCreation) {+ await originalHostEventManager.deleteEventsAndMeetings({+ event: deletionEvent,+ bookingReferences: originalRescheduledBooking.references,+ });+ }}- const updateManager = await eventManager.reschedule(- evt,- originalRescheduledBooking.uid,- undefined,- changedOrganizer,- previousHostDestinationCalendar,- isBookingRequestedReschedule,- skipDeleteEventsAndMeetings- );+ const updateManager = !skipCalendarSyncTaskCreation+ ? await eventManager.reschedule(+ evt,+ originalRescheduledBooking.uid,+ undefined,+ changedOrganizer,+ previousHostDestinationCalendar,+ isBookingRequestedReschedule,+ skipDeleteEventsAndMeetings+ )+ : placeholderCreatedEvent;// This gets overridden when updating the event - to check if notes have been hidden or not. We just reset this back// to the default description when we are sending the emails.evt.description = eventType.description;@@ -1870,7 +1900,10 @@ async function handler(// Create a booking} else if (isConfirmedByDefault) {// Use EventManager to conditionally use all needed integrations.- const createManager = areCalendarEventsEnabled ? await eventManager.create(evt) : placeholderCreatedEvent;+ const createManager =+ areCalendarEventsEnabled && !skipCalendarSyncTaskCreation+ ? await eventManager.create(evt)+ : placeholderCreatedEvent;if (evt.location) {booking.location = evt.location;}diff --git a/packages/features/bookings/lib/handleNewBooking/test/booking-flags.test.ts b/packages/features/bookings/lib/handleNewBooking/test/booking-flags.test.tsnew file mode 100644index 00000000000..302c63b4196--- /dev/null+++ b/packages/features/bookings/lib/handleNewBooking/test/booking-flags.test.ts@@ -0,0 +1,396 @@+import prismaMock from "../../../../../../tests/libs/__mocks__/prisma";++import {+ createBookingScenario,+ getDate,+ getGoogleCalendarCredential,+ TestData,+ getOrganizer,+ getBooker,+ getScenarioData,+ mockCalendarToHaveNoBusySlots,+ mockCalendar,+} from "@calcom/web/test/utils/bookingScenario/bookingScenario";+import { expectBookingToBeInDatabase } from "@calcom/web/test/utils/bookingScenario/expects";+import { getMockRequestDataForBooking } from "@calcom/web/test/utils/bookingScenario/getMockRequestDataForBooking";+import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";++import { describe, expect, test } from "vitest";++import { BookingStatus } from "@calcom/prisma/enums";++import { getNewBookingHandler } from "./getNewBookingHandler";++setupAndTeardown();++describe("handleNewBooking - Booking Flags", () => {+ describe("skipAvailabilityCheck flag", () => {+ test("should skip availability checks when skipAvailabilityCheck is true", async () => {+ const handleNewBooking = getNewBookingHandler();+ const booker = getBooker({+ email: "[email protected]",+ name: "Booker",+ });++ const organizer = getOrganizer({+ name: "Organizer",+ email: "[email protected]",+ id: 101,+ schedules: [TestData.schedules.IstWorkHours],+ credentials: [getGoogleCalendarCredential()],+ selectedCalendars: [TestData.selectedCalendars.google],+ });++ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });++ await createBookingScenario(+ getScenarioData({+ webhooks: [+ {+ userId: organizer.id,+ eventTriggers: ["BOOKING_CREATED"],+ subscriberUrl: "http://my-webhook.example.com",+ active: true,+ eventTypeId: 1,+ appId: null,+ },+ ],+ eventTypes: [+ {+ id: 1,+ slotInterval: 45,+ length: 45,+ users: [+ {+ id: 101,+ },+ ],+ },+ ],+ organizer,+ apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],+ })+ );++ mockCalendarToHaveNoBusySlots("googlecalendar", {+ create: {+ uid: "MOCK_ID",+ },+ });++ const mockBookingData = getMockRequestDataForBooking({+ data: {+ eventTypeId: 1,+ responses: {+ email: booker.email,+ name: booker.name,+ location: { optionValue: "", value: "integrations:daily" },+ },+ start: `${plus1DateString}T05:00:00.000Z`,+ end: `${plus1DateString}T05:45:00.000Z`,+ },+ });++ const createdBooking = await handleNewBooking({+ bookingData: mockBookingData,+ skipAvailabilityCheck: true,+ });++ expect(createdBooking.responses).toEqual(+ expect.objectContaining({+ email: booker.email,+ name: booker.name,+ })+ );++ expect(createdBooking.status).toBe(BookingStatus.ACCEPTED);++ await expectBookingToBeInDatabase({+ description: "",+ location: "integrations:daily",+ responses: expect.objectContaining({+ email: booker.email,+ name: booker.name,+ }),+ uid: createdBooking.uid,+ eventTypeId: mockBookingData.eventTypeId,+ status: BookingStatus.ACCEPTED,+ });+ });+ });++ describe("skipEventLimitsCheck flag", () => {+ test("should skip event limits checks when skipEventLimitsCheck is true", async () => {+ const handleNewBooking = getNewBookingHandler();+ const booker = getBooker({+ email: "[email protected]",+ name: "Booker",+ });++ const organizer = getOrganizer({+ name: "Organizer",+ email: "[email protected]",+ id: 101,+ schedules: [TestData.schedules.IstWorkHours],+ credentials: [getGoogleCalendarCredential()],+ selectedCalendars: [TestData.selectedCalendars.google],+ });++ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });++ await createBookingScenario(+ getScenarioData({+ eventTypes: [+ {+ id: 1,+ slotInterval: 45,+ length: 45,+ bookingLimits: {+ PER_DAY: 1,+ },+ users: [+ {+ id: 101,+ },+ ],+ },+ ],+ organizer,+ apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],+ })+ );++ mockCalendarToHaveNoBusySlots("googlecalendar", {+ create: {+ uid: "MOCK_ID",+ },+ });++ const mockBookingData = getMockRequestDataForBooking({+ data: {+ eventTypeId: 1,+ responses: {+ email: booker.email,+ name: booker.name,+ location: { optionValue: "", value: "integrations:daily" },+ },+ start: `${plus1DateString}T05:00:00.000Z`,+ end: `${plus1DateString}T05:45:00.000Z`,+ },+ });++ const createdBooking = await handleNewBooking({+ bookingData: mockBookingData,+ skipEventLimitsCheck: true,+ });++ expect(createdBooking.responses).toEqual(+ expect.objectContaining({+ email: booker.email,+ name: booker.name,+ })+ );++ expect(createdBooking.status).toBe(BookingStatus.ACCEPTED);++ await expectBookingToBeInDatabase({+ description: "",+ location: "integrations:daily",+ responses: expect.objectContaining({+ email: booker.email,+ name: booker.name,+ }),+ uid: createdBooking.uid,+ eventTypeId: mockBookingData.eventTypeId,+ status: BookingStatus.ACCEPTED,+ });+ });+ });++ describe("skipCalendarSyncTaskCreation flag", () => {+ test("should skip calendar sync when skipCalendarSyncTaskCreation is true", async () => {+ const handleNewBooking = getNewBookingHandler();+ const booker = getBooker({+ email: "[email protected]",+ name: "Booker",+ });++ const organizer = getOrganizer({+ name: "Organizer",+ email: "[email protected]",+ id: 101,+ schedules: [TestData.schedules.IstWorkHours],+ credentials: [getGoogleCalendarCredential()],+ selectedCalendars: [TestData.selectedCalendars.google],+ });++ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });++ await createBookingScenario(+ getScenarioData({+ eventTypes: [+ {+ id: 1,+ slotInterval: 45,+ length: 45,+ users: [+ {+ id: 101,+ },+ ],+ },+ ],+ organizer,+ apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],+ })+ );++ mockCalendar("googlecalendar", {+ create: {+ uid: "MOCK_ID",+ },+ });++ const mockBookingData = getMockRequestDataForBooking({+ data: {+ eventTypeId: 1,+ responses: {+ email: booker.email,+ name: booker.name,+ location: { optionValue: "", value: "integrations:daily" },+ },+ start: `${plus1DateString}T05:00:00.000Z`,+ end: `${plus1DateString}T05:45:00.000Z`,+ },+ });++ const createdBooking = await handleNewBooking({+ bookingData: mockBookingData,+ skipCalendarSyncTaskCreation: true,+ });++ expect(createdBooking.responses).toEqual(+ expect.objectContaining({+ email: booker.email,+ name: booker.name,+ })+ );++ expect(createdBooking.status).toBe(BookingStatus.ACCEPTED);++ await expectBookingToBeInDatabase({+ description: "",+ location: "integrations:daily",+ responses: expect.objectContaining({+ email: booker.email,+ name: booker.name,+ }),+ uid: createdBooking.uid,+ eventTypeId: mockBookingData.eventTypeId,+ status: BookingStatus.ACCEPTED,+ });++ const actualBooking = await prismaMock.booking.findFirst({+ where: { uid: createdBooking.uid },+ include: { references: true },+ });+ expect(actualBooking?.references).toEqual([]);+ });+ });++ describe("combined flags", () => {+ test("should work with multiple flags enabled", async () => {+ const handleNewBooking = getNewBookingHandler();+ const booker = getBooker({+ email: "[email protected]",+ name: "Booker",+ });++ const organizer = getOrganizer({+ name: "Organizer",+ email: "[email protected]",+ id: 101,+ schedules: [TestData.schedules.IstWorkHours],+ credentials: [getGoogleCalendarCredential()],+ selectedCalendars: [TestData.selectedCalendars.google],+ });++ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });++ await createBookingScenario(+ getScenarioData({+ eventTypes: [+ {+ id: 1,+ slotInterval: 45,+ length: 45,+ bookingLimits: {+ PER_DAY: 1,+ },+ users: [+ {+ id: 101,+ },+ ],+ },+ ],+ organizer,+ apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],+ })+ );++ mockCalendar("googlecalendar", {+ create: {+ uid: "MOCK_ID",+ },+ });++ const mockBookingData = getMockRequestDataForBooking({+ data: {+ eventTypeId: 1,+ responses: {+ email: booker.email,+ name: booker.name,+ location: { optionValue: "", value: "integrations:daily" },+ },+ start: `${plus1DateString}T05:00:00.000Z`,+ end: `${plus1DateString}T05:45:00.000Z`,+ },+ });++ const createdBooking = await handleNewBooking({+ bookingData: mockBookingData,+ skipAvailabilityCheck: true,+ skipEventLimitsCheck: true,+ skipCalendarSyncTaskCreation: true,+ });++ expect(createdBooking.responses).toEqual(+ expect.objectContaining({+ email: booker.email,+ name: booker.name,+ })+ );++ expect(createdBooking.status).toBe(BookingStatus.ACCEPTED);++ await expectBookingToBeInDatabase({+ description: "",+ location: "integrations:daily",+ responses: expect.objectContaining({+ email: booker.email,+ name: booker.name,+ }),+ uid: createdBooking.uid,+ eventTypeId: mockBookingData.eventTypeId,+ status: BookingStatus.ACCEPTED,+ });++ const actualBooking = await prismaMock.booking.findFirst({+ where: { uid: createdBooking.uid },+ include: { references: true },+ });+ expect(actualBooking?.references).toEqual([]);+ });+ });+});