Scheduling infrastructure for absolutely everyone.
fix: reschedule with google meet (#14730)
Udit Takkar3f4d9962a748
diff --git a/apps/web/test/utils/bookingScenario/bookingScenario.ts b/apps/web/test/utils/bookingScenario/bookingScenario.tsindex e202773b13a..649e3b37c3d 100644--- a/apps/web/test/utils/bookingScenario/bookingScenario.ts+++ b/apps/web/test/utils/bookingScenario/bookingScenario.ts@@ -763,6 +763,15 @@ export function getGoogleCalendarCredential() {});}+export function getGoogleMeetCredential() {+ return getMockedCredential({+ metadataLookupKey: "googlevideo",+ key: {+ scope: "",+ },+ });+}+export function getAppleCalendarCredential() {return getMockedCredential({metadataLookupKey: "applecalendar",@@ -890,6 +899,17 @@ export const TestData = {redirect_uris: ["http://localhost:3000/auth/callback"],},},+ "google-meet": {+ ...appStoreMetadata.googlevideo,+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ //@ts-ignore+ keys: {+ expiry_date: Infinity,+ client_id: "client_id",+ client_secret: "client_secret",+ redirect_uris: ["http://localhost:3000/auth/callback"],+ },+ },"daily-video": {...appStoreMetadata.dailyvideo,// eslint-disable-next-line @typescript-eslint/ban-ts-comment@@ -1084,6 +1104,12 @@ export function mockNoTranslations() {});}+export const enum BookingLocations {+ CalVideo = "integrations:daily",+ ZoomVideo = "integrations:zoom",+ GoogleMeet = "integrations:google:meet",+}+/*** @param metadataLookupKey* @param calendarData Specify uids and other data to be faked to be returned by createEvent and updateEvent@@ -1164,6 +1190,7 @@ export function mockCalendar(log.silly("mockCalendar.updateEvent", JSON.stringify({ uid, event, externalCalendarId }));// eslint-disable-next-line prefer-rest-paramsupdateEventCalls.push(rest);+ const isGoogleMeetLocation = event.location === BookingLocations.GoogleMeet;return Promise.resolve({type: app.type,additionalInfo: {},@@ -1175,6 +1202,9 @@ export function mockCalendar(// Password and URL seems useless for CalendarService, plan to remove them if that's the casepassword: "MOCK_PASSWORD",url: "https://UNUSED_URL",+ location: isGoogleMeetLocation ? "https://UNUSED_URL" : undefined,+ hangoutLink: isGoogleMeetLocation ? "https://UNUSED_URL" : undefined,+ conferenceData: isGoogleMeetLocation ? event.conferenceData : undefined,});},// eslint-disable-next-line @typescript-eslint/no-explicit-any@@ -1487,19 +1517,16 @@ export function getMockBookingAttendee(};}-export const enum BookingLocations {- CalVideo = "integrations:daily",- ZoomVideo = "integrations:zoom",-}-const getMockAppStatus = ({slug,failures,success,+ overrideName,}: {slug: string;failures: number;success: number;+ overrideName?: string;}) => {const foundEntry = Object.entries(appStoreMetadata).find(([, app]) => {return app.slug === slug;@@ -1509,7 +1536,7 @@ const getMockAppStatus = ({}const foundApp = foundEntry[1];return {- appName: foundApp.slug,+ appName: overrideName ?? foundApp.slug,type: foundApp.type,failures,success,@@ -1520,6 +1547,6 @@ export const getMockFailingAppStatus = ({ slug }: { slug: string }) => {return getMockAppStatus({ slug, failures: 1, success: 0 });};-export const getMockPassingAppStatus = ({ slug }: { slug: string }) => {- return getMockAppStatus({ slug, failures: 0, success: 1 });+export const getMockPassingAppStatus = ({ slug, overrideName }: { slug: string; overrideName?: string }) => {+ return getMockAppStatus({ slug, overrideName, failures: 0, success: 1 });};diff --git a/packages/features/bookings/lib/handleNewBooking.ts b/packages/features/bookings/lib/handleNewBooking.tsindex be5e70cd47e..9abe3bb6447 100644--- a/packages/features/bookings/lib/handleNewBooking.ts+++ b/packages/features/bookings/lib/handleNewBooking.ts@@ -1868,7 +1868,11 @@ async function handler(});}- if (googleCalResult?.createdEvent?.hangoutLink) {+ const googleHangoutLink = Array.isArray(googleCalResult?.updatedEvent)+ ? googleCalResult.updatedEvent[0]?.hangoutLink+ : googleCalResult?.updatedEvent?.hangoutLink ?? googleCalResult?.createdEvent?.hangoutLink;++ if (googleHangoutLink) {results.push({...googleMeetResult,success: true,@@ -1877,31 +1881,33 @@ async function handler(// Add google_meet to referencesToCreate in the same index as google_calendarupdateManager.referencesToCreate[googleCalIndex] = {...updateManager.referencesToCreate[googleCalIndex],- meetingUrl: googleCalResult.createdEvent.hangoutLink,+ meetingUrl: googleHangoutLink,};// Also create a new referenceToCreate with type video for google_meetupdateManager.referencesToCreate.push({type: "google_meet_video",- meetingUrl: googleCalResult.createdEvent.hangoutLink,+ meetingUrl: googleHangoutLink,uid: googleCalResult.uid,credentialId: updateManager.referencesToCreate[googleCalIndex].credentialId,});- } else if (googleCalResult && !googleCalResult.createdEvent?.hangoutLink) {+ } else if (googleCalResult && !googleHangoutLink) {results.push({...googleMeetResult,success: false,});}}-- metadata.hangoutLink = results[0].createdEvent?.hangoutLink;- metadata.conferenceData = results[0].createdEvent?.conferenceData;- metadata.entryPoints = results[0].createdEvent?.entryPoints;+ const createdOrUpdatedEvent = Array.isArray(results[0]?.updatedEvent)+ ? results[0]?.updatedEvent[0]+ : results[0]?.updatedEvent ?? results[0]?.createdEvent;+ metadata.hangoutLink = createdOrUpdatedEvent?.hangoutLink;+ metadata.conferenceData = createdOrUpdatedEvent?.conferenceData;+ metadata.entryPoints = createdOrUpdatedEvent?.entryPoints;evt.appsStatus = handleAppsStatus(results, booking, reqAppsStatus);videoCallUrl =metadata.hangoutLink ||- results[0].createdEvent?.url ||+ createdOrUpdatedEvent?.url ||organizerOrFirstDynamicGroupMemberDefaultLocationUrl ||getVideoCallUrlFromCalEvent(evt) ||videoCallUrl;diff --git a/packages/features/bookings/lib/handleNewBooking/test/reschedule.test.ts b/packages/features/bookings/lib/handleNewBooking/test/reschedule.test.tsindex f332a036824..6d555f6c30e 100644--- a/packages/features/bookings/lib/handleNewBooking/test/reschedule.test.ts+++ b/packages/features/bookings/lib/handleNewBooking/test/reschedule.test.ts@@ -11,6 +11,7 @@ import {createBookingScenario,getDate,getGoogleCalendarCredential,+ getGoogleMeetCredential,TestData,getOrganizer,getBooker,@@ -1138,6 +1139,250 @@ describe("handleNewBooking", () => {},timeout);+ test(+ `[GOOGLE MEET AS LOCATION]should rechedule a booking, that requires confirmation, without confirmation - When booker is the organizer of the existing booking as well as the event-type+ 1. Should cancel the existing booking+ 2. Should delete existing calendar invite and Video meeting+ 2. Should create a new booking in the database in ACCEPTED state+ 3. Should send rescheduled emails to the booker as well as organizer+ 4. Should trigger BOOKING_RESCHEDULED webhook+ `,+ async ({ emails }) => {+ const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;+ const booker = getBooker({+ email: "[email protected]",+ name: "Booker",+ });++ const organizer = getOrganizer({+ name: "Organizer",+ email: "[email protected]",+ id: 101,+ schedules: [TestData.schedules.IstWorkHours],+ credentials: [getGoogleCalendarCredential(), getGoogleMeetCredential()],+ selectedCalendars: [TestData.selectedCalendars.google],+ });++ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });+ const uidOfBookingToBeRescheduled = "n5Wv3eHgconAED2j4gcVhP";+ await createBookingScenario(+ getScenarioData({+ webhooks: [+ {+ userId: organizer.id,+ eventTriggers: ["BOOKING_CREATED"],+ subscriberUrl: "http://my-webhook.example.com",+ active: true,+ eventTypeId: 1,+ appId: null,+ },+ ],+ workflows: [+ {+ userId: organizer.id,+ trigger: "RESCHEDULE_EVENT",+ action: "EMAIL_HOST",+ template: "REMINDER",+ activeEventTypeId: 1,+ },+ ],+ eventTypes: [+ {+ id: 1,+ requiresConfirmation: true,+ slotInterval: 15,+ length: 15,+ locations: [+ {+ type: BookingLocations.GoogleMeet,+ },+ ],+ users: [+ {+ id: 101,+ },+ ],+ destinationCalendar: {+ integration: "google_calendar",+ externalId: "[email protected]",+ },+ },+ ],+ bookings: [+ {+ uid: uidOfBookingToBeRescheduled,+ eventTypeId: 1,+ userId: organizer.id,+ status: BookingStatus.ACCEPTED,+ location: BookingLocations.GoogleMeet,+ startTime: `${plus1DateString}T05:00:00.000Z`,+ endTime: `${plus1DateString}T05:15:00.000Z`,+ references: [+ getMockBookingReference({+ type: appStoreMetadata.googlecalendar.type,+ uid: "MOCK_ID",+ meetingId: "MOCK_ID",+ meetingPassword: "MOCK_PASSWORD",+ meetingUrl: "https://UNUSED_URL",+ externalCalendarId: "MOCK_EXTERNAL_CALENDAR_ID",+ credentialId: 1,+ }),+ getMockBookingReference({+ type: appStoreMetadata.googlevideo.type,+ uid: "MOCK_ID",+ meetingId: "MOCK_ID",+ meetingPassword: "MOCK_PASSWORD",+ meetingUrl: "https://UNUSED_URL",+ externalCalendarId: "MOCK_EXTERNAL_CALENDAR_ID",+ credentialId: 1,+ }),+ ],+ attendees: [+ getMockBookingAttendee({+ id: 1,+ name: organizer.name,+ email: organizer.email,+ locale: "en",+ timeZone: "Europe/London",+ }),+ getMockBookingAttendee({+ id: 2,+ name: booker.name,+ email: booker.email,+ // Booker's locale when the fresh booking happened earlier+ locale: "hi",+ // Booker's timezone when the fresh booking happened earlier+ timeZone: "Asia/Kolkata",+ }),+ ],+ },+ ],+ organizer,+ apps: [TestData.apps["google-calendar"], TestData.apps["google-meet"]],+ })+ );++ const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {+ create: {+ uid: "MOCK_ID",+ },+ update: {+ iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",+ uid: "UPDATED_MOCK_ID",+ },+ });++ const mockBookingData = getMockRequestDataForBooking({+ data: {+ eventTypeId: 1,+ rescheduleUid: uidOfBookingToBeRescheduled,+ start: `${plus1DateString}T04:00:00.000Z`,+ end: `${plus1DateString}T04:15:00.000Z`,+ // Organizer is doing the rescheduling from his timezone which is different from Booker Timezone as per the booking being rescheduled+ timeZone: "Europe/London",+ responses: {+ email: booker.email,+ name: booker.name,+ location: { optionValue: "", value: BookingLocations.GoogleMeet },+ },+ },+ });++ const { req } = createMockNextJsRequest({+ method: "POST",+ body: mockBookingData,+ });++ // Fake the request to be from organizer+ req.userId = organizer.id;++ const createdBooking = await handleNewBooking(req);++ /**+ * Booking Time should be new time+ */+ expect(createdBooking.startTime?.toISOString()).toBe(`${plus1DateString}T04:00:00.000Z`);+ expect(createdBooking.endTime?.toISOString()).toBe(`${plus1DateString}T04:15:00.000Z`);++ await expectBookingInDBToBeRescheduledFromTo({+ from: {+ uid: uidOfBookingToBeRescheduled,+ },+ to: {+ description: "",+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion+ uid: createdBooking.uid!,+ eventTypeId: mockBookingData.eventTypeId,+ status: BookingStatus.ACCEPTED,+ location: BookingLocations.GoogleMeet,+ responses: expect.objectContaining({+ email: booker.email,+ name: booker.name,+ }),+ references: [+ {+ type: appStoreMetadata.googlecalendar.type,+ uid: "MOCK_ID",+ meetingId: "MOCK_ID",+ meetingPassword: "MOCK_PASSWORD",+ meetingUrl: "https://UNUSED_URL",+ externalCalendarId: "MOCK_EXTERNAL_CALENDAR_ID",+ },+ ],+ },+ });++ expectWorkflowToBeTriggered({ emailsToReceive: [organizer.email], emails });++ expectSuccessfulCalendarEventUpdationInCalendar(calendarMock, {+ externalCalendarId: "MOCK_EXTERNAL_CALENDAR_ID",+ calEvent: {+ location: BookingLocations.GoogleMeet,+ videoCallData: expect.objectContaining({+ id: "MOCK_ID",+ password: "MOCK_PASSWORD",+ type: "google_video",+ url: "https://UNUSED_URL",+ }),+ attendees: expect.arrayContaining([+ expect.objectContaining({+ email: booker.email,+ name: booker.name,+ // Expect that the booker timezone is his earlier timezone(from original booking), even though the rescheduling is done by organizer from his timezone+ timeZone: "Asia/Kolkata",+ language: expect.objectContaining({+ // Expect that the booker locale is his earlier locale(from original booking), even though the rescheduling is done by organizer with his locale+ locale: "hi",+ }),+ }),+ ]),+ },+ uid: "MOCK_ID",+ });++ expectSuccessfulBookingRescheduledEmails({+ booker,+ organizer,+ emails,+ iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",+ appsStatus: [+ getMockPassingAppStatus({ slug: appStoreMetadata.googlecalendar.slug }),+ getMockPassingAppStatus({+ slug: appStoreMetadata.googlevideo.slug,+ overrideName: "Google Meet",+ }),+ ],+ });+ expectBookingRescheduledWebhookToHaveBeenFired({+ booker,+ organizer,+ location: BookingLocations.GoogleMeet,+ subscriberUrl: "http://my-webhook.example.com",+ videoCallUrl: "https://UNUSED_URL",+ });+ },+ timeout+ );test(`should rechedule a booking, that requires confirmation, in PENDING state - Even when the rescheduler is the organizer of the event-type but not the organizer of the existing bookingdiff --git a/packages/types/Calendar.d.ts b/packages/types/Calendar.d.tsindex b3ffec8d633..dd10ed17488 100644--- a/packages/types/Calendar.d.ts+++ b/packages/types/Calendar.d.ts@@ -70,6 +70,9 @@ export type NewCalendarEventType = {url: string;additionalInfo: AdditionalInfo;iCalUID?: string | null;+ location?: string | null;+ hangoutLink?: string | null;+ conferenceData?: ConferenceData;};export type CalendarEventType = {