feat: Domain-wide delegation for Google Calendar and Google Meet (#16622)

* Add endpoints for testing the flow

* Add MVP

* new route

* Fixes

* Fixes

* Remove enable toggle support from domainWideDelegation

* Fixes

* Revert "Remove enable toggle support from domainWideDelegation"

This reverts commit c29e729206cd1fa063f9c9ce0cf148ef1577d60b.

* Revert yarn.lock

* More fixes

* Fix new workspace platform add

* refactor: improvements

* refactor: bug fixes and improvements

* fix: type errors

* fix: conflicts

* chore: update test

* fix: logic

* chore: improvements

* fix: toglle

* fix: bugs

* fix: type err

* chore: check number type

* fix: after conflicts

* chore: fix type err

* fix: type errors and tests

* fix: tets

* test

* chore: remove unused

* fix: google meet url on booking page and secondary calendar

* fix: add property

* fix: type err

* fix: re assingment bug

* fix: use getAllCredentials

* chore: fix import

* fix: installed count

* fix: pass event type

* fix: import

* fix: [Stacked PR] Review fixes (#17958)

* Review fixes

* fix: destination calendar bug

---------

Co-authored-by: Udit Takkar <[email protected]>

* refactor: use repository

* chore: remove duplicate

* fix: More review fixes for domain wide delegation (#17969)

* Reuse buildCredentialPayloadForCalendar

* fixes

---------

Co-authored-by: Udit Takkar <[email protected]>

* fix ts error

* Fix getSchedule not using dwd credentials (#17995)

* fix: Remove direct DWD table access from google-calendar and remove delegatedToId column from Credential (#18015)

* Remove fn rename to reduce number of files changed

* chore: check feature globally

* test: add unit tests

* chore: move function

* test: add booking test

* wip

* Remove domain-wide-delegation team feature flag

* Make sure duplicate calendars are not shown due to DWD. Show DWD when there is conflict

* Fix tests and their ts errors

* Fix more tests

* Move findUsersForAvailabilityCheck to separate file as it has AppStore dependency causing problem with Routing Forms. Build crashes

* fix: Multiple calendar connections from Google not showing up in apps/installed

* DestinationCalendar must have either credentialId or domainWideDeelgationId. Also handle the case when DWD is disabled and there was a non-dwd credential that could be used

* Disable deletetion of DWD as it is destructive and prefer disabling instead

* Show DWD credential calendars at the top

* Fixed tests

* Calendar Cache DWD support

* Self-Review: Verify email required and add more selectedCalendar tests

* Self Review: shorten names

* Self ReviewL Dead code removal

* Revert "Calendar Cache DWD support"

This reverts commit 009f236470fa21eba5986117d4f6e4d4c5e38c34.

* Some misc fixes

* fixes

* Performance improvememt in slots loading and booking

* More cases for handling dwd credentials

* simplify the logic. Ensure that EventManager and the modules below it in the flow have CredentialForCalendarService available

* Fix tests

* Fix installed/conferencing not showing gogole meet

* Shorten name

* Fix ApI v2 tests

* Add some more tests

* add getSchedule tests

* Improve tests

* Make Google Meet default when DWD for google is enabled

* Enable feature flagging for DWD

* chore: bump libraries

* Encrypt serviceaccount private key

* Fix ts errors

* bump platform libraries

* org add dwd

* org add dwd

* bump platform libraries

* fix selected calendars

* fix remove selected dwd calendar

* remove oauthclient id aliad in authedCalendar

* remove oauthclient id aliad in authedCalendar

* refactor: OrganizationsDwdController

* chore: export toggleDwdEnabled from platform-libraries

* feat: v2 update (enable / disable) dwd

* refactor: SelectedCalendarsController check if user belongs to dwd org & for not dwd use previous logic

* wip: DestinationCalendar send domainWideDelegationCredentialId from frontend to api

* try fix set destination calendar api v2

* fixup! try fix set destination calendar api v2

* setting google meet as default location working for dwd

* bump platform libraries version

* allow office 365 workspace slug

* allow office 365 workspace slug

* chore: v2 create dwd MS and Google service keys input

* fix: CreateDwdInput serviceAccountKey

* fix: CredentialForCalendarService type

* fix: check workspace slug

* feat: update serviceAccessKey of DWD

* testing

* fixup! testing

* fix: getAuthUtl bug

* fix: unit tests

* fix: type err and unit test

* fix: e2e test

* fix: credentials bug and failing unit tests

* Update CalendarService.ts

* chore: refactor office365 calendar service and add testDomainWideDelegationSetup

* fix: office365Calendar use correct clientId/Secret for DWD

* fix: office365Calendar dwd no need refresh token

* test: add unit test for outlook dwd and setup

* feat: added dwd support for office365 calendar

* feat: added dwd support for office365 video

* test: finish test for outlook dwd

* fix: create dialog bug

* chore: remove console logs

* fix: refreshToken bug

* bump version libraries

* refactor: fetch dwd credentials only in findQualifiedHosts

* fixup! refactor: fetch dwd credentials only in findQualifiedHosts

* fix: type err

* fix: type err

* fix: getUserDisplayName

* fix: unit test

* chore: bump platform lib

---------

Co-authored-by: Syed Ali Shahbaz <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Morgan Vernay <[email protected]>
Co-authored-by: supalarry <[email protected]>
Co-authored-by: Somay Chauhan <[email protected]>
Co-authored-by: Morgan <[email protected]>
This commit is contained in:
173 files changed
+12277 -1137

No files matched your search

@@ -0,0 +1,208 @@
import {
getDate,
createBookingScenario,
Timezones,
TestData,
mockCalendar,
createDwdCredential,
createOrganization,
getOrganizer,
} from "../../utils/bookingScenario/bookingScenario";
import { expectNoAttemptToGetAvailability } from "../../utils/bookingScenario/expects";
import { describe, test } from "vitest";
import { MembershipRole } from "@calcom/prisma/enums";
import { getAvailableSlots as getSchedule } from "@calcom/trpc/server/routers/viewer/slots/util";
import { expect, expectedSlotsForSchedule } from "./expects";
import { setupAndTeardown } from "./setupAndTeardown";
describe("getSchedule", () => {
setupAndTeardown();
describe("Domain Wide Delegation", () => {
test("correctly identifies unavailable slots using DWD credentials", async () => {
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const { dateString: plus2DateString } = getDate({ dateIncrement: 2 });
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
const payloadToMakePartOfOrganization = [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: org.id,
name: "Test Org",
slug: "testorg",
},
},
];
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.google],
// User must be part of organization to be able to use that organization's DWD credential
teams: payloadToMakePartOfOrganization,
// No regular credentials provided
credentials: [],
});
await createDwdCredential(org.id);
const googleCalendarMock = mockCalendar("googlecalendar", {
create: {
uid: "MOCK_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
busySlots: [
{
start: `${plus2DateString}T04:45:00.000Z`,
end: `${plus2DateString}T23:00:00.000Z`,
},
],
});
const scenarioData = {
eventTypes: [
{
id: 1,
slotInterval: 45,
length: 45,
users: [
{
id: organizer.id,
},
],
},
],
users: [organizer],
apps: [TestData.apps["google-calendar"]],
};
await createBookingScenario(scenarioData);
const scheduleForDayWithAGoogleCalendarBooking = await getSchedule({
input: {
eventTypeId: 1,
eventTypeSlug: "",
startTime: `${plus1DateString}T18:30:00.000Z`,
endTime: `${plus2DateString}T18:29:59.999Z`,
timeZone: Timezones["+5:30"],
isTeamEvent: false,
orgSlug: null,
},
});
// As per Google Calendar Availability, only 4PM(4-4:45PM) GMT slot would be available
expect(scheduleForDayWithAGoogleCalendarBooking).toHaveTimeSlots([`04:00:00.000Z`], {
dateString: plus2DateString,
});
});
test("fails to get schedule when user isn't part of the organization with DWD credential", async () => {
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const { dateString: plus2DateString } = getDate({ dateIncrement: 2 });
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
const anotherOrg = await createOrganization({
name: "Another Org",
slug: "anotherorg",
});
// User is part of a different org
const payloadToMakePartOfDifferentOrganization = [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: anotherOrg.id,
name: "Another Org",
slug: "anotherorg",
},
},
];
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.google],
teams: payloadToMakePartOfDifferentOrganization,
credentials: [],
});
// Create DWD credential for the org user isn't part of
await createDwdCredential(org.id);
const googleCalendarMock = mockCalendar("googlecalendar", {
create: {
uid: "MOCK_ID",
iCalUID: "MOCKED_GOOGLE_CALENDAR_ICS_ID",
},
busySlots: [
{
start: `${plus2DateString}T04:45:00.000Z`,
end: `${plus2DateString}T23:00:00.000Z`,
},
],
});
const scenarioData = {
eventTypes: [
{
id: 1,
slotInterval: 60,
length: 60,
users: [
{
id: organizer.id,
},
],
},
],
users: [organizer],
apps: [TestData.apps["google-calendar"]],
};
await createBookingScenario(scenarioData);
const scheduleForDayWithAGoogleCalendarBooking = await getSchedule({
input: {
eventTypeId: 1,
eventTypeSlug: "",
startTime: `${plus1DateString}T18:30:00.000Z`,
endTime: `${plus2DateString}T18:29:59.999Z`,
timeZone: Timezones["+5:30"],
isTeamEvent: false,
orgSlug: null,
},
});
expectNoAttemptToGetAvailability(googleCalendarMock);
// All slots would be available as no DWD credentials are available
expect(scheduleForDayWithAGoogleCalendarBooking).toHaveTimeSlots(
expectedSlotsForSchedule.IstWorkHours.interval["1hr"].allPossibleSlotsStartingAt430,
{
dateString: plus2DateString,
}
);
});
});
});
@@ -30,8 +30,10 @@ import type { teamMetadataSchema } from "@calcom/prisma/zod-utils";
import type { userMetadataType } from "@calcom/prisma/zod-utils";
import type { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
import type { AppMeta } from "@calcom/types/App";
import type { CalendarEvent, IntegrationCalendar } from "@calcom/types/Calendar";
import type { NewCalendarEventType } from "@calcom/types/Calendar";
import type { EventBusyDate, IntervalLimit } from "@calcom/types/Calendar";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { getMockPaymentService } from "./MockPaymentService";
import type { getMockRequestDataForBooking } from "./getMockRequestDataForBooking";
@@ -41,6 +43,17 @@ vi.mock("@calcom/lib/raqb/findTeamMembersMatchingAttributeLogic", () => ({
default: {},
}));
vi.mock("@calcom/lib/crypto", async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const actual = await importOriginal<any>();
return {
...actual,
symmetricEncrypt: vi.fn((serviceAccountKey) => serviceAccountKey),
symmetricDecrypt: vi.fn((serviceAccountKey) => serviceAccountKey),
};
});
type Fields = z.infer<typeof eventTypeBookingFields>;
logger.settings.minLevel = 1;
@@ -906,7 +919,8 @@ export async function createOrganization(orgData: {
slug: string;
metadata?: z.infer<typeof teamMetadataSchema>;
withTeam?: boolean;
}): Promise<TeamCreateReturnType & { slug: NonNullable<TeamCreateReturnType["slug"]> }> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}): Promise<TeamCreateReturnType & { slug: NonNullable<TeamCreateReturnType["slug"]>; children: any }> {
const org = await prismock.team.create({
data: {
name: orgData.name,
@@ -933,7 +947,12 @@ export async function createOrganization(orgData: {
});
}
assertNonNullableSlug(org);
return org;
const team = await prismock.team.findUnique({ where: { id: org.id }, include: { children: true } });
if (!team) {
throw new Error(`Team with id ${org.id} not found`);
}
assertNonNullableSlug(team);
return team;
}
export async function createCredentials(
@@ -1119,6 +1138,10 @@ export const TestData = {
integration: "google_calendar",
externalId: "[email protected]",
},
office365: {
integration: "office365_calendar",
externalId: "[email protected]",
},
},
credentials: {
google: getGoogleCalendarCredential(),
@@ -1320,6 +1343,16 @@ export const TestData = {
redirect_uris: ["http://localhost:3000/auth/callback"],
},
},
"office365-calendar": {
...appStoreMetadata.office365calendar,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
keys: {
expiry_date: Infinity,
client_id: "client_id",
client_secret: "client_secret",
},
},
"google-meet": {
...appStoreMetadata.googlevideo,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@@ -1550,6 +1583,52 @@ export const enum BookingLocations {
GoogleMeet = "integrations:google:meet",
}
export type CalendarServiceMethodMockCallBase = {
calendarServiceConstructorArgs: {
credential: CredentialForCalendarService;
};
};
type CreateEventMethodMockCall = CalendarServiceMethodMockCallBase & {
args: {
calEvent: CalendarEvent;
credentialId: number;
externalCalendarId?: string;
};
};
type UpdateEventMethodMockCall = CalendarServiceMethodMockCallBase & {
args: {
uid: string;
event: CalendarEvent;
externalCalendarId?: string;
};
};
type DeleteEventMethodMockCall = CalendarServiceMethodMockCallBase & {
args: {
uid: string;
event: CalendarEvent;
externalCalendarId?: string;
};
};
type GetAvailabilityMethodMockCall = CalendarServiceMethodMockCallBase & {
args: {
dateFrom: string;
dateTo: string;
selectedCalendars: IntegrationCalendar[];
shouldServeCache?: boolean;
};
};
export type CalendarServiceMethodMock = {
createEventCalls: CreateEventMethodMockCall[];
updateEventCalls: UpdateEventMethodMockCall[];
deleteEventCalls: DeleteEventMethodMockCall[];
getAvailabilityCalls: GetAvailabilityMethodMockCall[];
};
/**
* @param metadataLookupKey
* @param calendarData Specify uids and other data to be faked to be returned by createEvent and updateEvent
@@ -1561,18 +1640,34 @@ export function mockCalendar(
id?: string;
uid?: string;
iCalUID?: string;
appSpecificData?: {
googleCalendar?: {
hangoutLink?: string;
};
office365Calendar?: {
url?: string;
};
};
};
update?: {
id?: string;
uid: string;
iCalUID?: string;
appSpecificData?: {
googleCalendar?: {
hangoutLink?: string;
};
office365Calendar?: {
url?: string;
};
};
};
busySlots?: { start: `${string}Z`; end: `${string}Z` }[];
creationCrash?: boolean;
updationCrash?: boolean;
getAvailabilityCrash?: boolean;
}
) {
): CalendarServiceMethodMock {
const appStoreLookupKey = metadataLookupKey;
const normalizedCalendarData = calendarData || {
create: {
@@ -1583,12 +1678,11 @@ export function mockCalendar(
},
};
log.silly(`Mocking ${appStoreLookupKey} on appStoreMock`);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const createEventCalls: any[] = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const updateEventCalls: any[] = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const deleteEventCalls: any[] = [];
const createEventCalls: CreateEventMethodMockCall[] = [];
const updateEventCalls: UpdateEventMethodMockCall[] = [];
const deleteEventCalls: DeleteEventMethodMockCall[] = [];
const getAvailabilityCalls: GetAvailabilityMethodMockCall[] = [];
const app = appStoreMetadata[metadataLookupKey as keyof typeof appStoreMetadata];
const appMock = appStoreMock.default[appStoreLookupKey as keyof typeof appStoreMock.default];
@@ -1599,20 +1693,37 @@ export function mockCalendar(
lib: {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
CalendarService: function MockCalendarService() {
CalendarService: function MockCalendarService(credential: CredentialForCalendarService) {
return {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createEvent: async function (...rest: any[]): Promise<NewCalendarEventType> {
if (calendarData?.creationCrash) {
throw new Error("MockCalendarService.createEvent fake error");
}
const [calEvent, credentialId] = rest;
log.silly("mockCalendar.createEvent", JSON.stringify({ calEvent, credentialId }));
createEventCalls.push(rest);
const [calEvent, credentialId, externalCalendarId] = rest;
log.debug(
"mockCalendar.createEvent",
JSON.stringify({ calEvent, credentialId, externalCalendarId })
);
createEventCalls.push({
args: {
calEvent,
credentialId,
externalCalendarId,
},
calendarServiceConstructorArgs: {
credential,
},
});
const isGoogleMeetLocation = calEvent?.location === BookingLocations.GoogleMeet;
return Promise.resolve({
type: app.type,
additionalInfo: {},
uid: "PROBABLY_UNUSED_UID",
hangoutLink:
(isGoogleMeetLocation
? normalizedCalendarData.create?.appSpecificData?.googleCalendar?.hangoutLink
: null) || "https://UNUSED_URL",
// A Calendar is always expected to return an id.
id: normalizedCalendarData.create?.id || "FALLBACK_MOCK_CALENDAR_EVENT_ID",
iCalUID: normalizedCalendarData.create?.iCalUID,
@@ -1629,21 +1740,32 @@ export function mockCalendar(
const [uid, event, externalCalendarId] = rest;
log.silly("mockCalendar.updateEvent", JSON.stringify({ uid, event, externalCalendarId }));
// eslint-disable-next-line prefer-rest-params
updateEventCalls.push(rest);
updateEventCalls.push({
args: {
uid,
event,
externalCalendarId,
},
calendarServiceConstructorArgs: {
credential,
},
});
const isGoogleMeetLocation = event.location === BookingLocations.GoogleMeet;
return Promise.resolve({
type: app.type,
additionalInfo: {},
uid: "PROBABLY_UNUSED_UID",
iCalUID: normalizedCalendarData.update?.iCalUID,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
id: normalizedCalendarData.update?.uid || "FALLBACK_MOCK_ID",
// Password and URL seems useless for CalendarService, plan to remove them if that's the case
password: "MOCK_PASSWORD",
url: "https://UNUSED_URL",
location: isGoogleMeetLocation ? "https://UNUSED_URL" : undefined,
hangoutLink: isGoogleMeetLocation ? "https://UNUSED_URL" : undefined,
hangoutLink:
(isGoogleMeetLocation
? normalizedCalendarData.update?.appSpecificData?.googleCalendar?.hangoutLink
: null) || "https://UNUSED_URL",
conferenceData: isGoogleMeetLocation ? event.conferenceData : undefined,
});
},
@@ -1651,12 +1773,33 @@ export function mockCalendar(
deleteEvent: async (...rest: any[]) => {
log.silly("mockCalendar.deleteEvent", JSON.stringify({ rest }));
// eslint-disable-next-line prefer-rest-params
deleteEventCalls.push(rest);
deleteEventCalls.push({
args: {
uid: rest[0],
event: rest[1],
externalCalendarId: rest[2],
},
calendarServiceConstructorArgs: {
credential,
},
});
},
getAvailability: async (): Promise<EventBusyDate[]> => {
getAvailability: async (...rest: any[]): Promise<EventBusyDate[]> => {
if (calendarData?.getAvailabilityCrash) {
throw new Error("MockCalendarService.getAvailability fake error");
}
const [dateFrom, dateTo, selectedCalendars, shouldServeCache] = rest;
getAvailabilityCalls.push({
args: {
dateFrom,
dateTo,
selectedCalendars,
shouldServeCache,
},
calendarServiceConstructorArgs: {
credential,
},
});
return new Promise((resolve) => {
resolve(calendarData?.busySlots || []);
});
@@ -1669,6 +1812,7 @@ export function mockCalendar(
createEventCalls,
deleteEventCalls,
updateEventCalls,
getAvailabilityCalls,
};
}
@@ -2164,3 +2308,123 @@ export const getDefaultBookingFields = ({
...bookingFields,
] as Fields;
};
export const createDwdCredential = async (orgId: number, type: "google" | "office365" = "google") => {
if (type === "google") {
const encryptedServiceAccountKey = {
type: "service_account",
auth_uri: "https://accounts.google.com/o/oauth2/auth",
client_id: "CLIENT_ID",
token_uri: "https://oauth2.googleapis.com/token",
project_id: "PROJECT_ID",
encrypted_credentials: `{"private_key": "PRIVATE_KEY"}`,
client_email: "CLIENT_EMAIL",
private_key_id: "PRIVATE_KEY_ID",
universe_domain: "googleapis.com",
client_x509_cert_url: "CLIENT_X509_CERT_URL",
auth_provider_x509_cert_url: "AUTH_PROVIDER_X509_CERT_URL",
};
const workspace = await prismock.workspacePlatform.create({
data: {
name: "Test Workspace",
slug: "google",
description: "Test Workspace",
defaultServiceAccountKey: encryptedServiceAccountKey,
enabled: true,
},
});
const decryptedServiceAccountKey = {
type: "service_account",
auth_uri: "https://accounts.google.com/o/oauth2/auth",
client_id: "CLIENT_ID",
token_uri: "https://oauth2.googleapis.com/token",
project_id: "PROJECT_ID",
private_key: "PRIVATE_KEY",
client_email: "CLIENT_EMAIL",
private_key_id: "PRIVATE_KEY_ID",
universe_domain: "googleapis.com",
client_x509_cert_url: "CLIENT_X509_CERT_URL",
auth_provider_x509_cert_url: "AUTH_PROVIDER_X509_CERT_URL",
};
const dwd = await prismock.domainWideDelegation.create({
data: {
workspacePlatform: {
connect: {
id: workspace.id,
},
},
domain: "example.com",
enabled: true,
organization: {
connect: {
id: orgId,
},
},
// @ts-expect-error - TODO: fix this
serviceAccountKey: workspace.defaultServiceAccountKey,
},
});
return { ...dwd, serviceAccountKey: decryptedServiceAccountKey };
} else if (type === "office365") {
const encryptedServiceAccountKey = {
client_id: "CLIENT_ID",
encrypted_credentials: `{"private_key": "PRIVATE_KEY"}`,
tenant_id: "TENANT_ID",
};
const workspace = await prismock.workspacePlatform.create({
data: {
name: "Test Workspace",
slug: "office365",
description: "Test Workspace",
defaultServiceAccountKey: encryptedServiceAccountKey,
enabled: true,
},
});
const decryptedServiceAccountKey = {
client_id: "CLIENT_ID",
private_key: "PRIVATE_KEY",
tenant_id: "TENANT_ID",
};
const dwd = await prismock.domainWideDelegation.create({
data: {
workspacePlatform: {
connect: {
id: workspace.id,
},
},
domain: "example.com",
enabled: true,
organization: {
connect: {
id: orgId,
},
},
// @ts-expect-error - TODO: fix this
serviceAccountKey: workspace.defaultServiceAccountKey,
},
});
return { ...dwd, serviceAccountKey: decryptedServiceAccountKey };
}
throw new Error(`Unsupported type: ${type}`);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const buildDwdCredential = ({ serviceAccountKey }: { serviceAccountKey: any }) => {
return {
id: -1,
key: {
access_token: "NOOP_UNUSED_DELEGATION_TOKEN",
},
delegatedTo: {
serviceAccountKey,
},
};
};
+73 -53
View File
@@ -1,6 +1,6 @@
import prismaMock from "../../../../../tests/libs/__mocks__/prisma";
import type { InputEventType, getOrganizer } from "./bookingScenario";
import type { InputEventType, getOrganizer, CalendarServiceMethodMock } from "./bookingScenario";
import type { WebhookTriggerEvents, Booking, BookingReference, DestinationCalendar } from "@prisma/client";
import { parse } from "node-html-parser";
@@ -16,6 +16,7 @@ import { safeStringify } from "@calcom/lib/safeStringify";
import { BookingStatus } from "@calcom/prisma/enums";
import type { AppsStatus } from "@calcom/types/Calendar";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { Fixtures } from "@calcom/web/test/fixtures/fixtures";
import { DEFAULT_TIMEZONE_BOOKER } from "./getMockRequestDataForBooking";
@@ -448,6 +449,7 @@ export function expectSuccessfulBookingCreationEmails({
bookingTimeRange,
booking,
destinationEmail,
calendarType,
}: {
emails: Fixtures["emails"];
organizer: { email: string; name: string; timeZone: string };
@@ -460,6 +462,7 @@ export function expectSuccessfulBookingCreationEmails({
bookingTimeRange?: { start: Date; end: Date };
booking: { uid: string; urlOrigin?: string };
destinationEmail?: string;
calendarType?: string;
}) {
const bookingUrlOrigin = booking.urlOrigin || WEBSITE_URL;
expect(emails).toHaveEmail(
@@ -495,12 +498,16 @@ export function expectSuccessfulBookingCreationEmails({
}
: null),
to: `${destinationEmail ?? organizer.email}`,
ics: {
filename: "event.ics",
iCalUID: `${iCalUID}`,
recurrence,
method: "REQUEST",
},
...(calendarType !== "office365_calendar"
? {
ics: {
filename: "event.ics",
iCalUID: `${iCalUID}`,
recurrence,
method: "REQUEST",
},
}
: {}),
},
`${destinationEmail ?? organizer.email}`
);
@@ -1170,32 +1177,32 @@ export function expectBookingPaymentIntiatedWebhookToHaveBeenFired({
});
}
type ExpectedForSuccessfulCalendarEventCreationInCalendar = {
calendarId?: string | null;
/**
* explciityl set to null if you don't want to match on videoCallUrl
*/
videoCallUrl: string | null;
destinationCalendars?: Partial<DestinationCalendar>[];
credential?: Partial<CredentialForCalendarService>;
};
export function expectSuccessfulCalendarEventCreationInCalendar(
calendarMock: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createEventCalls: any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
updateEventCalls: any[];
},
calendarMock: CalendarServiceMethodMock,
expected:
| {
calendarId?: string | null;
videoCallUrl: string;
destinationCalendars?: Partial<DestinationCalendar>[];
}
| {
calendarId?: string | null;
videoCallUrl: string;
destinationCalendars?: Partial<DestinationCalendar>[];
}[]
| ExpectedForSuccessfulCalendarEventCreationInCalendar
| ExpectedForSuccessfulCalendarEventCreationInCalendar[]
) {
const expecteds = expected instanceof Array ? expected : [expected];
expect(calendarMock.createEventCalls.length).toBe(expecteds.length);
for (let i = 0; i < calendarMock.createEventCalls.length; i++) {
const expected = expecteds[i];
const calEvent = calendarMock.createEventCalls[i][0];
const createEventCall = calendarMock.createEventCalls[i];
const { credential } = createEventCall.calendarServiceConstructorArgs;
const { calEvent } = createEventCall.args;
if (expected.credential) {
expect(credential).toEqual(expect.objectContaining(expected.credential));
}
expect(calEvent).toEqual(
expect.objectContaining({
destinationCalendar: expected.calendarId
@@ -1207,21 +1214,21 @@ export function expectSuccessfulCalendarEventCreationInCalendar(
: expected.destinationCalendars
? expect.arrayContaining(expected.destinationCalendars.map((cal) => expect.objectContaining(cal)))
: null,
videoCallData: expect.objectContaining({
url: expected.videoCallUrl,
}),
...(expected.videoCallUrl !== null
? {
videoCallData: expect.objectContaining({
url: expected.videoCallUrl,
}),
}
: {}),
})
);
}
}
export function expectSuccessfulCalendarEventUpdationInCalendar(
calendarMock: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createEventCalls: any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
updateEventCalls: any[];
},
calendarMock: CalendarServiceMethodMock,
expected: {
externalCalendarId: string;
calEvent: Partial<CalendarEvent>;
@@ -1230,23 +1237,14 @@ export function expectSuccessfulCalendarEventUpdationInCalendar(
) {
expect(calendarMock.updateEventCalls.length).toBe(1);
const call = calendarMock.updateEventCalls[0];
const uid = call[0];
const calendarEvent = call[1];
const externalId = call[2];
const { uid, event, externalCalendarId } = call.args;
expect(uid).toBe(expected.uid);
expect(calendarEvent).toEqual(expect.objectContaining(expected.calEvent));
expect(externalId).toBe(expected.externalCalendarId);
expect(event).toEqual(expect.objectContaining(expected.calEvent));
expect(externalCalendarId).toBe(expected.externalCalendarId);
}
export function expectSuccessfulCalendarEventDeletionInCalendar(
calendarMock: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createEventCalls: any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
updateEventCalls: any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
deleteEventCalls: any[];
},
calendarMock: CalendarServiceMethodMock,
expected: {
externalCalendarId: string;
calEvent: Partial<CalendarEvent>;
@@ -1255,12 +1253,10 @@ export function expectSuccessfulCalendarEventDeletionInCalendar(
) {
expect(calendarMock.deleteEventCalls.length).toBe(1);
const call = calendarMock.deleteEventCalls[0];
const uid = call[0];
const calendarEvent = call[1];
const externalId = call[2];
const { uid, event, externalCalendarId } = call.args;
expect(uid).toBe(expected.uid);
expect(calendarEvent).toEqual(expect.objectContaining(expected.calEvent));
expect(externalId).toBe(expected.externalCalendarId);
expect(event).toEqual(expect.objectContaining(expected.calEvent));
expect(externalCalendarId).toBe(expected.externalCalendarId);
}
export function expectSuccessfulVideoMeetingCreation(
@@ -1351,3 +1347,27 @@ export function expectICalUIDAsString(iCalUID: string | undefined | null) {
return iCalUID;
}
export async function expectBookingToNotHaveReference(
booking: Pick<Booking, "uid">,
reference: Partial<BookingReference>
) {
const actualBooking = await prismaMock.booking.findUnique({
where: {
uid: booking.uid,
},
include: {
references: true,
},
});
expect(actualBooking?.references).not.toEqual(expect.arrayContaining([expect.objectContaining(reference)]));
}
export function expectNoAttemptToCreateCalendarEvent(calendarMock: CalendarServiceMethodMock) {
expect(calendarMock.createEventCalls.length).toBe(0);
}
export function expectNoAttemptToGetAvailability(calendarMock: CalendarServiceMethodMock) {
expect(calendarMock.getAvailabilityCalls.length).toBe(0);
}