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

@@ -12,6 +12,7 @@ import type {
EventTypes,
} from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { BulkEditDefaultForEventsModal } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppCategories } from "@calcom/prisma/enums";
import { type RouterOutputs } from "@calcom/trpc";
@@ -229,7 +230,7 @@ function ConnectOrDisconnectIntegrationMenuItem(props: {
<DropdownItem
color="destructive"
onClick={() => handleDisconnect(credentialId, app, teamId)}
disabled={isGlobal}
disabled={isGlobal || isDwdCredential({ credentialId })}
StartIcon="trash">
{t("remove_app")}
</DropdownItem>
@@ -2,6 +2,7 @@
import { useState } from "react";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { ButtonProps } from "@calcom/ui";
@@ -37,11 +38,14 @@ export default function DisconnectIntegration(props: {
},
});
// Such a credential is added in-memory and removed when Domain-wide delegation is disabled.
const disableDisconnect = isDwdCredential({ credentialId });
return (
<DisconnectIntegrationComponent
onDeletionConfirmation={() => mutation.mutate({ id: credentialId, ...(teamId ? { teamId } : {}) })}
isModalOpen={modalOpen}
onModalOpen={() => setModalOpen((prevValue) => !prevValue)}
disabled={disableDisconnect}
{...props}
/>
);
@@ -643,6 +643,7 @@ export const getOptions = ({
const gCalService = new GoogleCalendarService({
...gcalCredential,
user: null,
delegatedTo: null,
});
if (
@@ -1,5 +1,6 @@
import type z from "zod";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { UserRepository } from "@calcom/lib/server/repository/user";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -7,18 +8,20 @@ import { eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { CredentialPayload } from "@calcom/types/Credential";
export type EventType = {
userId?: number | null;
team?: { id: number | null; parentId: number | null } | null;
parentId?: number | null;
metadata: z.infer<typeof EventTypeMetaDataSchema>;
} | null;
/**
* Gets credentials from the user, team, and org if applicable
*
*/
export const getAllCredentials = async (
user: { id: number; username: string | null; credentials: CredentialPayload[] },
eventType: {
userId?: number | null;
team?: { id: number | null; parentId: number | null } | null;
parentId?: number | null;
metadata: z.infer<typeof EventTypeMetaDataSchema>;
} | null
user: { id: number; username: string | null; email: string; credentials: CredentialPayload[] },
eventType: EventType
) => {
let allCredentials = user.credentials;
@@ -117,5 +120,9 @@ export const getAllCredentials = async (
}
});
return allCredentials;
const userWithDwdCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
user: { ...user, credentials: allCredentials },
});
return userWithDwdCredentials.credentials;
};
@@ -1,6 +1,8 @@
import async from "async";
import type { CredentialPayload } from "@calcom/types/Credential";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { buildAllCredentials } from "@calcom/lib/domainWideDelegation/server";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { refreshCredential } from "./refreshCredential";
@@ -10,7 +12,14 @@ import { refreshCredential } from "./refreshCredential";
* @param credentials
*/
export async function refreshCredentials(
credentials: Array<CredentialPayload>
): Promise<Array<CredentialPayload>> {
return await async.mapLimit(credentials, 5, refreshCredential);
credentials: Array<CredentialForCalendarService>
): Promise<Array<CredentialForCalendarService>> {
const nonDwdCredentials = credentials.filter(
(cred) => !isDwdCredential({ credentialId: cred.id })
);
const dwdCredentials = credentials.filter((cred) =>
isDwdCredential({ credentialId: cred.id })
);
const refreshedDbCredentials = await async.mapLimit(nonDwdCredentials, 5, refreshCredential);
return buildAllCredentials({ dwdCredentials, existingCredentials: refreshedDbCredentials });
}
@@ -70,6 +70,7 @@ async function getBookingToDelete(id: number | undefined, uid: string | undefine
externalCalendarId: true,
credentialId: true,
thirdPartyRecurringEventId: true,
domainWideDelegationCredentialId: true,
},
},
payment: true,
@@ -47,8 +47,12 @@ import {
scheduleTrigger,
} from "@calcom/features/webhooks/lib/scheduleTrigger";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import { isRerouting, shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
import { getDefaultEvent, getUsernameList } from "@calcom/lib/defaultEvents";
import {
enrichHostsWithDwdCredentials,
getFirstDwdConferencingCredentialAppLocation,
} from "@calcom/lib/domainWideDelegation/server";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { extractBaseEmail } from "@calcom/lib/extract-base-email";
@@ -76,6 +80,7 @@ import type { PlatformClientParams } from "@calcom/prisma/zod-utils";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import { getAllWorkflowsFromEventType } from "@calcom/trpc/server/routers/viewer/workflows/util";
import type { AdditionalInformation, AppsStatus, CalendarEvent, Person } from "@calcom/types/Calendar";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { EventResult, PartialReference } from "@calcom/types/EventManager";
import type { EventPayloadType, EventTypeInfo } from "../../webhooks/lib/sendPayload";
@@ -113,6 +118,10 @@ import handleSeats from "./handleSeats/handleSeats";
const translator = short();
const log = logger.getSubLogger({ prefix: ["[api] book:user"] });
type IsFixedAwareUserWithCredentials = Omit<IsFixedAwareUser, "credentials"> & {
credentials: CredentialForCalendarService[];
};
export const createLoggerWithEventDetails = (
eventTypeId: number,
reqBodyUser: string | string[] | undefined,
@@ -167,36 +176,6 @@ type BookingDataSchemaGetter =
| typeof getBookingDataSchema
| typeof import("@calcom/features/bookings/lib/getBookingDataSchemaForApi").default;
/**
* Adds the contact owner to be the only lucky user
* @returns
*/
function buildLuckyUsersWithJustContactOwner({
contactOwnerEmail,
availableUsers,
fixedUserPool,
}: {
contactOwnerEmail: string | null;
availableUsers: IsFixedAwareUser[];
fixedUserPool: IsFixedAwareUser[];
}) {
const luckyUsers: Awaited<ReturnType<typeof loadAndValidateUsers>>["qualifiedRRUsers"] = [];
if (!contactOwnerEmail) {
return luckyUsers;
}
const isContactOwnerAFixedHostAlready = fixedUserPool.some((user) => user.email === contactOwnerEmail);
if (isContactOwnerAFixedHostAlready) {
return luckyUsers;
}
const teamMember = availableUsers.find((user) => user.email === contactOwnerEmail);
if (teamMember) {
luckyUsers.push(teamMember);
}
return luckyUsers;
}
type CreatedBooking = Booking & { appsStatus?: AppsStatus[]; paymentUid?: string; paymentId?: number };
const buildDryRunBooking = ({
@@ -478,11 +457,6 @@ async function handler(
const contactOwnerFromReq = reqBody.teamMemberEmail ?? null;
const isReroutingCase = isRerouting({
rescheduleUid: reqBody.rescheduleUid ?? null,
routedTeamMemberIds: routedTeamMemberIds ?? null,
});
const skipContactOwner = shouldIgnoreContactOwner({
skipContactOwner: reqBody.skipContactOwner ?? null,
rescheduleUid: reqBody.rescheduleUid ?? null,
@@ -529,11 +503,13 @@ async function handler(
// We filter out users but ensure allHostUsers remain same.
let users = [...qualifiedRRUsers, ...additionalFallbackRRUsers, ...fixedUsers];
let { locationBodyString, organizerOrFirstDynamicGroupMemberDefaultLocationUrl } = getLocationValuesForDb(
const firstUser = users[0];
let { locationBodyString, organizerOrFirstDynamicGroupMemberDefaultLocationUrl } = getLocationValuesForDb({
dynamicUserList,
users,
location
);
location,
});
await monitorCallbackAsync(checkBookingAndDurationLimits, {
eventType,
@@ -565,11 +541,11 @@ async function handler(
//checks what users are available
if (isFirstSeat) {
const eventTypeWithUsers: getEventTypeResponse & {
users: IsFixedAwareUser[];
const eventTypeWithUsers: Omit<getEventTypeResponse, "users"> & {
users: IsFixedAwareUserWithCredentials[];
} = {
...eventType,
users: users as IsFixedAwareUser[],
users: users as IsFixedAwareUserWithCredentials[],
...(eventType.recurringEvent && {
recurringEvent: {
...eventType.recurringEvent,
@@ -583,7 +559,7 @@ async function handler(
eventType.schedulingType === SchedulingType.ROUND_ROBIN;
const fixedUsers = isTeamEvent
? eventTypeWithUsers.users.filter((user: IsFixedAwareUser) => user.isFixed)
? eventTypeWithUsers.users.filter((user: IsFixedAwareUserWithCredentials) => user.isFixed)
: [];
for (
@@ -609,6 +585,7 @@ async function handler(
);
}
} else {
eventTypeWithUsers.users[0].credentials;
await ensureAvailableUsers(
eventTypeWithUsers,
{
@@ -705,13 +682,19 @@ async function handler(
// freeUsers is ensured
const userIdsSet = new Set(users.map((user) => user.id));
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: eventTypeWithUsers.users[0].id ?? null,
teamId: eventType.teamId,
});
const newLuckyUser = await getLuckyUser({
// find a lucky user that is not already in the luckyUsers array
availableUsers: freeUsers,
allRRHosts: eventTypeWithUsers.hosts.filter(
(host) => !host.isFixed && userIdsSet.has(host.user.id)
), // users part of virtual queue
allRRHosts: (
await enrichHostsWithDwdCredentials({
orgId: firstUserOrgId ?? null,
hosts: eventTypeWithUsers.hosts,
})
).filter((host) => !host.isFixed && userIdsSet.has(host.user.id)),
eventType,
routingFormResponse,
});
@@ -825,6 +808,11 @@ async function handler(
locationBodyString = OrganizerDefaultConferencingAppType;
}
}
const organizationDefaultLocation = getFirstDwdConferencingCredentialAppLocation({
credentials: firstUser.credentials,
});
// use host default
if (locationBodyString == OrganizerDefaultConferencingAppType) {
const metadataParseResult = userMetadataSchema.safeParse(organizerUser.metadata);
@@ -836,6 +824,8 @@ async function handler(
organizerOrFirstDynamicGroupMemberDefaultLocationUrl =
organizerMetadata?.defaultConferencingApp?.appLink;
}
} else if (organizationDefaultLocation) {
locationBodyString = organizationDefaultLocation;
} else {
locationBodyString = "integrations:daily";
}
@@ -1294,7 +1284,7 @@ async function handler(
endTime: reqBody.end,
contactOwnerFromReq,
contactOwnerEmail,
allHostUsers: [...qualifiedRRUsers, ...additionalFallbackRRUsers, ...fixedUsers],
allHostUsers: users,
isManagedEventType,
});
booking = dryRunBooking;
@@ -49,7 +49,7 @@ const hasDateRangeForBooking = (
};
export async function ensureAvailableUsers(
eventType: getEventTypeResponse & {
eventType: Omit<getEventTypeResponse, "users"> & {
users: IsFixedAwareUser[];
},
input: { dateFrom: string; dateTo: string; timeZone: string; originalRescheduledBooking?: BookingType },
@@ -1,10 +1,12 @@
import { getFirstDwdConferencingCredentialAppLocation } from "@calcom/lib/domainWideDelegation/server";
import type { Prisma } from "@calcom/prisma/client";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { loadAndValidateUsers } from "./loadAndValidateUsers";
type Users = Awaited<ReturnType<typeof loadAndValidateUsers>>["qualifiedRRUsers"];
const sortUsersByDynamicList = (users: Users, dynamicUserList: string[]) => {
const sortUsersByDynamicList = <TUser extends { username: string | null }>(
users: TUser[],
dynamicUserList: string[]
) => {
return users.sort((a, b) => {
const aIndex = (a.username && dynamicUserList.indexOf(a.username)) || 0;
const bIndex = (b.username && dynamicUserList.indexOf(b.username)) || 0;
@@ -12,19 +14,41 @@ const sortUsersByDynamicList = (users: Users, dynamicUserList: string[]) => {
});
};
export const getLocationValuesForDb = (
dynamicUserList: string[],
users: Users,
locationBodyString: string
) => {
// TODO: It's definition should be moved to getLocationValueForDb
let organizerOrFirstDynamicGroupMemberDefaultLocationUrl;
if (dynamicUserList.length > 1) {
users = sortUsersByDynamicList(users, dynamicUserList);
const firstUsersMetadata = userMetadataSchema.parse(users[0].metadata);
locationBodyString = firstUsersMetadata?.defaultConferencingApp?.appLink || locationBodyString;
organizerOrFirstDynamicGroupMemberDefaultLocationUrl =
firstUsersMetadata?.defaultConferencingApp?.appLink;
export const getLocationValuesForDb = <
TUser extends {
username: string | null;
metadata: Prisma.JsonValue;
credentials: CredentialForCalendarService[];
}
return { locationBodyString, organizerOrFirstDynamicGroupMemberDefaultLocationUrl };
>({
dynamicUserList,
users,
location: locationBodyString,
}: {
dynamicUserList: string[];
users: TUser[];
location: string;
}) => {
const isDynamicGroupBookingCase = dynamicUserList.length > 1;
let firstDynamicGroupMemberDefaultLocationUrl;
// TODO: It's definition should be moved to getLocationValueForDb
if (isDynamicGroupBookingCase) {
users = sortUsersByDynamicList(users, dynamicUserList);
const firstDynamicGroupMember = users[0];
const firstDynamicGroupMemberMetadata = userMetadataSchema.parse(firstDynamicGroupMember.metadata);
const firstDynamicGroupMemberDwdConferencingAppLocation = getFirstDwdConferencingCredentialAppLocation({
credentials: firstDynamicGroupMember.credentials,
});
firstDynamicGroupMemberDefaultLocationUrl =
firstDynamicGroupMemberMetadata?.defaultConferencingApp?.appLink ||
firstDynamicGroupMemberDwdConferencingAppLocation;
locationBodyString = firstDynamicGroupMemberDefaultLocationUrl || locationBodyString;
}
return {
locationBodyString,
organizerOrFirstDynamicGroupMemberDefaultLocationUrl: firstDynamicGroupMemberDefaultLocationUrl,
};
};
@@ -2,7 +2,9 @@ import type { Prisma } from "@prisma/client";
import type { IncomingMessage } from "http";
import type { Logger } from "tslog";
import { findQualifiedHosts } from "@calcom/lib/bookings/findQualifiedHosts";
import { findQualifiedHostsWithDwdCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDwdCredentials";
import { enrichUsersWithDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { HttpError } from "@calcom/lib/http-error";
import { getPiiFreeUser } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -12,6 +14,7 @@ import { userSelect } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import { SchedulingType } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { loadUsers } from "./loadUsers";
import type { NewBookingEventType } from "./types";
@@ -22,6 +25,13 @@ type Users = (Awaited<ReturnType<typeof loadUsers>>[number] & {
createdAt?: Date;
})[];
export type UsersWithDwdCredentials = (Omit<Awaited<ReturnType<typeof loadUsers>>[number], "credentials"> & {
isFixed?: boolean;
metadata?: Prisma.JsonValue;
createdAt?: Date;
credentials: CredentialForCalendarService[];
})[];
type EventType = Pick<
NewBookingEventType,
| "hosts"
@@ -36,6 +46,7 @@ type EventType = Pick<
| "rrSegmentQueryValue"
| "isRRWeightsEnabled"
| "rescheduleWithSameRoundRobinHost"
| "teamId"
>;
type InputProps = {
@@ -60,7 +71,11 @@ export async function loadAndValidateUsers({
contactOwnerEmail,
rescheduleUid,
routingFormResponse,
}: InputProps): Promise<{ qualifiedRRUsers: Users; additionalFallbackRRUsers: Users; fixedUsers: Users }> {
}: InputProps): Promise<{
qualifiedRRUsers: UsersWithDwdCredentials;
additionalFallbackRRUsers: UsersWithDwdCredentials;
fixedUsers: UsersWithDwdCredentials;
}> {
let users: Users = await loadUsers({
eventType,
dynamicUserList,
@@ -68,6 +83,7 @@ export async function loadAndValidateUsers({
routedTeamMemberIds,
contactOwnerEmail,
});
const isDynamicAllowed = !users.some((user) => !user.allowDynamicBooking);
if (!isDynamicAllowed && !eventTypeId) {
logger.warn({
@@ -109,32 +125,51 @@ export async function loadAndValidateUsers({
? false
: user.isFixed || eventType.schedulingType !== SchedulingType.ROUND_ROBIN,
}));
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } = await findQualifiedHosts({
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: routedTeamMemberIds || [],
rescheduleUid,
contactOwnerEmail,
routingFormResponse,
});
const allQualifiedHostsHashMap = [...qualifiedRRHosts, ...(allFallbackRRHosts ?? []), ...fixedHosts].reduce(
(acc, host) => {
if (host.user.id) {
return { ...acc, [host.user.id]: host };
}
return acc;
},
{} as {
[key: number]: Awaited<
ReturnType<typeof findQualifiedHostsWithDwdCredentials>
>["qualifiedRRHosts"][number];
}
);
let qualifiedRRUsers: Users = [];
let allFallbackRRUsers: Users = [];
let fixedUsers: Users = [];
let qualifiedRRUsers: UsersWithDwdCredentials = [];
let allFallbackRRUsers: UsersWithDwdCredentials = [];
let fixedUsers: UsersWithDwdCredentials = [];
if (qualifiedRRHosts.length) {
// remove users that are not in the qualified hosts array
const qualifiedHostIds = new Set(qualifiedRRHosts.map((qualifiedHost) => qualifiedHost.user.id));
qualifiedRRUsers = users.filter((user) => qualifiedHostIds.has(user.id));
qualifiedRRUsers = users
.filter((user) => qualifiedHostIds.has(user.id))
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
}
if (allFallbackRRHosts?.length) {
const fallbackHostIds = new Set(allFallbackRRHosts.map((fallbackHost) => fallbackHost.user.id));
allFallbackRRUsers = users.filter((user) => fallbackHostIds.has(user.id));
allFallbackRRUsers = users
.filter((user) => fallbackHostIds.has(user.id))
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
}
if (fixedHosts?.length) {
const fixedHostIds = new Set(fixedHosts.map((fixedHost) => fixedHost.user.id));
fixedUsers = users.filter((user) => fixedHostIds.has(user.id));
fixedUsers = users
.filter((user) => fixedHostIds.has(user.id))
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
}
logger.debug(
@@ -148,9 +183,26 @@ export async function loadAndValidateUsers({
(fallbackUser) => !qualifiedRRUsers.find((qualifiedUser) => qualifiedUser.id === fallbackUser.id)
);
if (!qualifiedRRUsers.length && !fixedUsers.length) {
const firstUser = users[0];
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: firstUser.id ?? null,
teamId: eventType.teamId,
});
const usersEnrichedWithDwd = await enrichUsersWithDwdCredentials({
orgId: firstUserOrgId ?? null,
users,
});
return {
qualifiedRRUsers,
additionalFallbackRRUsers, // without qualified
fixedUsers: usersEnrichedWithDwd,
};
}
return {
qualifiedRRUsers,
additionalFallbackRRUsers, // without qualified
fixedUsers: !qualifiedRRUsers.length && !fixedUsers.length ? users : fixedUsers,
fixedUsers,
};
}
@@ -0,0 +1,760 @@
/**
* These tests are integration tests that test the flow from receiving a api/book/event request and then verifying
* - database entries created in In-MEMORY DB using prismock
* - emails sent by checking the testEmails global variable
* - webhooks fired by mocking fetch
* - APIs of various apps called by mocking those apps' modules
*
* They don't intend to test what the apps logic should do, but rather test if the apps are called with the correct data. For testing that, once should write tests within each app.
*/
import {
createBookingScenario,
TestData,
getDate,
getOrganizer,
getBooker,
getScenarioData,
mockSuccessfulVideoMeetingCreation,
mockCalendarToHaveNoBusySlots,
BookingLocations,
createDwdCredential,
createOrganization,
buildDwdCredential,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { createMockNextJsRequest } from "@calcom/web/test/utils/bookingScenario/createMockNextJsRequest";
import {
expectWorkflowToBeTriggered,
expectSuccessfulBookingCreationEmails,
expectBookingToBeInDatabase,
expectBookingCreatedWebhookToHaveBeenFired,
expectSuccessfulCalendarEventCreationInCalendar,
expectICalUIDAsString,
expectBookingToNotHaveReference,
expectNoAttemptToCreateCalendarEvent,
} from "@calcom/web/test/utils/bookingScenario/expects";
import {
getMockRequestDataForBooking,
getMockRequestDataForDynamicGroupBooking,
} from "@calcom/web/test/utils/bookingScenario/getMockRequestDataForBooking";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import { describe, expect } from "vitest";
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { BookingStatus } from "@calcom/prisma/enums";
import { MembershipRole } from "@calcom/prisma/enums";
import { test } from "@calcom/web/test/fixtures/fixtures";
// Local test runs sometime gets too slow
const timeout = process.env.CI ? 5000 : 20000;
describe("handleNewBooking", () => {
setupAndTeardown();
describe("Domain Wide Delegation", () => {
test(
`should create a successful booking using the domain wide delegation credential
1. Should create a booking in the database with reference having DWD credential
2. Should create an event in calendar with DWD credential
3. Should use Google Meet as the location even when not explicitly set.
`,
async ({ emails }) => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
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 booker = getBooker({
email: "[email protected]",
name: "Booker",
});
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: [],
destinationCalendar: TestData.selectedCalendars.google,
});
const dwd = await createDwdCredential(org.id);
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
length: 30,
users: [
{
id: organizer.id,
},
],
};
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: "NEW_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [1],
},
],
eventTypes: [payloadToCreateUserEventTypeForOrganizer],
organizer,
apps: [TestData.apps["daily-video"], TestData.apps["google-calendar"]],
})
);
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
id: "GOOGLE_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
appSpecificData: {
googleCalendar: {
hangoutLink: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
},
},
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
eventTypeId: 1,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: BookingLocations.GoogleMeet },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
expect(createdBooking.responses).toEqual(
expect.objectContaining({
email: booker.email,
name: booker.name,
})
);
expect(createdBooking).toEqual(
expect.objectContaining({
location: BookingLocations.GoogleMeet,
})
);
await expectBookingToBeInDatabase({
description: "",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: mockBookingData.eventTypeId,
status: BookingStatus.ACCEPTED,
references: [
{
type: appStoreMetadata.googlecalendar.type,
uid: "GOOGLE_CALENDAR_EVENT_ID",
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
},
],
iCalUID: createdBooking.iCalUID,
});
expectWorkflowToBeTriggered({ emailsToReceive: [organizer.email], emails });
expectSuccessfulCalendarEventCreationInCalendar(calendarMock, {
credential: buildDwdCredential({ serviceAccountKey: dwd.serviceAccountKey }),
calendarId: TestData.selectedCalendars.google.externalId,
// There would be no videoCallUrl in this case as it is not a dedicated conferencing case and hangoutLink is used instead
videoCallUrl: null,
});
const iCalUID = expectICalUIDAsString(createdBooking.iCalUID);
expectSuccessfulBookingCreationEmails({
booking: {
uid: createdBooking.uid!,
},
booker,
organizer,
emails,
iCalUID,
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
location: BookingLocations.GoogleMeet,
subscriberUrl: "http://my-webhook.example.com",
videoCallUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
});
},
timeout
);
test(
`should create a successful booking using the office365 domain wide delegation credential with Cal Video as the location
1. Should create a booking in the database with reference having DWD credential
2. Should create an event in Outlook calendar with DWD credential
`,
async ({ emails }) => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
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 booker = getBooker({
email: "[email protected]",
name: "Booker",
});
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.office365],
// User must be part of organization to be able to use that organization's DWD credential
teams: payloadToMakePartOfOrganization,
// No regular credentials provided
credentials: [],
destinationCalendar: TestData.selectedCalendars.office365,
});
const dwd = await createDwdCredential(org.id, "office365");
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
length: 30,
users: [
{
id: organizer.id,
},
],
};
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: "NEW_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [1],
},
],
eventTypes: [payloadToCreateUserEventTypeForOrganizer],
organizer,
apps: [TestData.apps["daily-video"], TestData.apps["office365-calendar"]],
})
);
mockSuccessfulVideoMeetingCreation({
metadataLookupKey: "dailyvideo",
videoMeetingData: {
id: "MOCK_ID",
password: "MOCK_PASS",
url: `http://mock-dailyvideo.example.com/meeting-1`,
},
});
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("office365calendar", {
create: {
id: "OFFICE_365_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
appSpecificData: {
office365Calendar: {
url: "http://mock-dailyvideo.example.com/meeting-1",
},
},
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
eventTypeId: 1,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: BookingLocations.CalVideo },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
expect(createdBooking.responses).toEqual(
expect.objectContaining({
email: booker.email,
name: booker.name,
})
);
expect(createdBooking).toEqual(
expect.objectContaining({
location: BookingLocations.CalVideo,
})
);
console.log("createdBooking", createdBooking);
await expectBookingToBeInDatabase({
description: "",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: mockBookingData.eventTypeId,
status: BookingStatus.ACCEPTED,
references: [
{
type: appStoreMetadata.dailyvideo.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASS",
meetingUrl: "http://mock-dailyvideo.example.com/meeting-1",
},
{
type: appStoreMetadata.office365calendar.type,
uid: "OFFICE_365_CALENDAR_EVENT_ID",
meetingId: "OFFICE_365_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
},
],
iCalUID: createdBooking.iCalUID,
});
expectWorkflowToBeTriggered({ emailsToReceive: [organizer.email], emails });
expectSuccessfulCalendarEventCreationInCalendar(calendarMock, {
credential: buildDwdCredential({ serviceAccountKey: dwd.serviceAccountKey }),
calendarId: TestData.selectedCalendars.office365.externalId,
// There would be no videoCallUrl in this case as it is not a dedicated conferencing case and hangoutLink is used instead
videoCallUrl: null,
});
const iCalUID = expectICalUIDAsString(createdBooking.iCalUID);
expectSuccessfulBookingCreationEmails({
booking: {
uid: createdBooking.uid!,
},
booker,
organizer,
emails,
iCalUID,
calendarType: "office365_calendar",
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
location: BookingLocations.CalVideo,
subscriberUrl: "http://my-webhook.example.com",
videoCallUrl: `http://app.cal.local:3000/video/${createdBooking.uid}`,
});
},
timeout
);
test(
`should fail calendar event creation when organizer isn't part of the organization of DWD Credential`,
async () => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
withTeam: true,
});
const anotherOrg = await createOrganization({
name: "Another Org",
slug: "anotherorg",
});
const payloadToMakePartOfOrganization = [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: org.id,
name: "Test Org",
slug: "testorg",
},
},
];
const booker = getBooker({
email: "[email protected]",
name: "Booker",
});
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(anotherOrg.id);
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
length: 30,
users: [
{
id: organizer.id,
},
],
};
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: "NEW_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [1],
},
],
eventTypes: [payloadToCreateUserEventTypeForOrganizer],
organizer,
apps: [TestData.apps["daily-video"]],
})
);
mockSuccessfulVideoMeetingCreation({
metadataLookupKey: "dailyvideo",
videoMeetingData: {
id: "MOCK_ID",
password: "MOCK_PASS",
url: `http://mock-dailyvideo.example.com/meeting-1`,
},
});
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
id: "GOOGLE_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
appSpecificData: {
googleCalendar: {
hangoutLink: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
},
},
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
eventTypeId: 1,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: BookingLocations.CalVideo },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
expect(createdBooking.responses).toEqual(
expect.objectContaining({
email: booker.email,
name: booker.name,
})
);
expect(createdBooking).toEqual(
expect.objectContaining({
location: BookingLocations.CalVideo,
})
);
expectNoAttemptToCreateCalendarEvent(calendarMock);
await expectBookingToBeInDatabase({
description: "",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: mockBookingData.eventTypeId,
status: BookingStatus.ACCEPTED,
references: [
{
type: appStoreMetadata.dailyvideo.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASS",
meetingUrl: "http://mock-dailyvideo.example.com/meeting-1",
},
],
iCalUID: createdBooking.iCalUID,
});
// Could not create calendar-event
expectBookingToNotHaveReference(createdBooking, {
type: appStoreMetadata.googlecalendar.type,
uid: "GOOGLE_CALENDAR_EVENT_ID",
});
},
timeout
);
test(
`should create a successful dynamic group booking using the domain wide delegation credential
1. Should create a booking in the database with reference having DWD credential
2. Should create an event in calendar with DWD credential for both users
3. Should use Google Meet as the location even when not explicitly set.
`,
async () => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
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 booker = getBooker({
email: "[email protected]",
name: "Booker",
});
const groupUser1 = getOrganizer({
name: "group-user-1",
username: "group-user-1",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.google],
teams: payloadToMakePartOfOrganization,
credentials: [],
destinationCalendar: TestData.selectedCalendars.google,
});
const groupUser2 = getOrganizer({
name: "group-user-2",
username: "group-user-2",
email: "[email protected]",
id: 102,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.google],
teams: payloadToMakePartOfOrganization,
credentials: [],
destinationCalendar: TestData.selectedCalendars.google,
});
const dwd = await createDwdCredential(org.id);
await createBookingScenario(
getScenarioData({
webhooks: [
{
userId: groupUser1.id,
eventTriggers: ["BOOKING_CREATED"],
subscriberUrl: "http://my-webhook.example.com",
active: true,
eventTypeId: 0,
appId: null,
},
],
workflows: [
{
userId: groupUser1.id,
trigger: "NEW_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [0],
},
],
eventTypes: [],
users: [groupUser1, groupUser2],
apps: [TestData.apps["daily-video"], TestData.apps["google-calendar"]],
})
);
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
id: "GOOGLE_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
appSpecificData: {
googleCalendar: {
hangoutLink: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
},
},
},
});
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const mockBookingData = getMockRequestDataForDynamicGroupBooking({
data: {
start: `${plus1DateString}T05:00:00.000Z`,
end: `${plus1DateString}T05:30:00.000Z`,
eventTypeId: 0,
eventTypeSlug: "group-user-1+group-user-2",
user: "group-user-1+group-user-2",
responses: {
email: booker.email,
name: booker.name,
// There is no location option during booking for Dynamic Group Bookings
// location: { optionValue: "", value: BookingLocations.CalVideo },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
expect(createdBooking.responses).toEqual(
expect.objectContaining({
email: booker.email,
name: booker.name,
})
);
expect(createdBooking).toEqual(
expect.objectContaining({
location: BookingLocations.GoogleMeet,
})
);
await expectBookingToBeInDatabase({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: null,
status: BookingStatus.ACCEPTED,
location: BookingLocations.GoogleMeet,
references: [
{
type: appStoreMetadata.googlecalendar.type,
uid: "GOOGLE_CALENDAR_EVENT_ID",
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
},
],
iCalUID: createdBooking.iCalUID,
});
},
timeout
);
});
});
@@ -7,7 +7,7 @@ import type { DefaultEvent } from "@calcom/lib/defaultEvents";
import type { PaymentAppData } from "@calcom/lib/getPaymentAppData";
import type { userSelect } from "@calcom/prisma";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { Booking } from "./createBooking";
import type {
@@ -55,7 +55,7 @@ export interface IEventTypePaymentCredentialType {
export type IsFixedAwareUser = User & {
isFixed: boolean;
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
organization?: { slug: string };
priority?: number;
weight?: number;
@@ -5,6 +5,8 @@ import { updateMeeting } from "@calcom/core/videoClient";
import { sendCancelledSeatEmailsAndSMS } from "@calcom/emails";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import { getAllDwdCredentialsForUser } from "@calcom/lib/domainWideDelegation/server";
import { getDwdOrFindRegularCredential } from "@calcom/lib/domainWideDelegation/server";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -12,7 +14,6 @@ import { getTranslation } from "@calcom/lib/server/i18n";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import prisma from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { bookingCancelAttendeeSeatSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeMetadata } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
@@ -67,6 +68,12 @@ async function cancelAttendeeSeat(
(req as NextApiRequest).statusCode = 200;
const attendee = bookingToDelete?.attendees.find((attendee) => attendee.id === seatReference.attendeeId);
const bookingToDeleteUser = bookingToDelete.user ?? null;
const dwdCredentials = bookingToDeleteUser
? await getAllDwdCredentialsForUser({
user: { email: bookingToDeleteUser.email, id: bookingToDeleteUser.id },
})
: [];
if (attendee) {
/* If there are references then we should update them as well */
@@ -74,12 +81,13 @@ async function cancelAttendeeSeat(
const integrationsToUpdate = [];
for (const reference of bookingToDelete.references) {
if (reference.credentialId) {
const credential = await prisma.credential.findUnique({
where: {
id: reference.credentialId,
if (reference.credentialId || reference.domainWideDelegationCredentialId) {
const credential = await getDwdOrFindRegularCredential({
id: {
credentialId: reference.credentialId,
domainWideDelegationCredentialId: reference.domainWideDelegationCredentialId,
},
select: credentialForCalendarServiceSelect,
dwdCredentials,
});
if (credential) {
@@ -3,9 +3,10 @@ import type { Attendee } from "@prisma/client";
// eslint-disable-next-line no-restricted-imports
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { deleteMeeting } from "@calcom/core/videoClient";
import { getAllDwdCredentialsForUser } from "@calcom/lib/domainWideDelegation/server";
import { getDwdOrFindRegularCredential } from "@calcom/lib/domainWideDelegation/server";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { OriginalRescheduledBooking } from "../../handleNewBooking/types";
@@ -18,16 +19,23 @@ const lastAttendeeDeleteBooking = async (
originalBookingEvt?: CalendarEvent
) => {
let deletedReferences = false;
const bookingUser = originalRescheduledBooking?.user;
const dwdCredentials = bookingUser
? await getAllDwdCredentialsForUser({
user: { email: bookingUser.email, id: bookingUser.id },
})
: [];
if ((!filteredAttendees || filteredAttendees.length === 0) && originalRescheduledBooking) {
const integrationsToDelete = [];
for (const reference of originalRescheduledBooking.references) {
if (reference.credentialId) {
const credential = await prisma.credential.findUnique({
where: {
id: reference.credentialId,
if (reference.credentialId || reference.domainWideDelegationCredentialId) {
const credential = await getDwdOrFindRegularCredential({
id: {
credentialId: reference.credentialId,
domainWideDelegationCredentialId: reference.domainWideDelegationCredentialId,
},
select: credentialForCalendarServiceSelect,
dwdCredentials,
});
if (credential) {
@@ -1,7 +1,6 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import type { Calendar } from "@calcom/types/Calendar";
import { CalendarCacheRepository } from "./calendar-cache.repository";
@@ -10,9 +9,8 @@ import { CalendarCacheRepositoryMock } from "./calendar-cache.repository.mock";
export class CalendarCache {
static async initFromCredentialId(credentialId: number): Promise<ICalendarCacheRepository> {
const credential = await prisma.credential.findUnique({
where: { id: credentialId },
select: credentialForCalendarServiceSelect,
const credential = await CredentialRepository.findCredentialForCalendarServiceById({
id: credentialId,
});
const calendar = await getCalendar(credential);
return await CalendarCache.init(calendar);
+13 -1
View File
@@ -17,6 +17,7 @@ export type ICalendarSwitchProps = {
isLastItemInList?: boolean;
destination?: boolean;
credentialId: number;
domainWideDelegationCredentialId: string | null;
eventTypeId: number | null;
disabled?: boolean;
};
@@ -28,7 +29,17 @@ type EventCalendarSwitchProps = ICalendarSwitchProps & {
};
const CalendarSwitch = (props: ICalendarSwitchProps) => {
const { title, externalId, type, isChecked, name, credentialId, eventTypeId, disabled } = props;
const {
title,
externalId,
type,
isChecked,
name,
credentialId,
domainWideDelegationCredentialId,
eventTypeId,
disabled,
} = props;
const [checkedInternal, setCheckedInternal] = useState(isChecked);
const utils = trpc.useUtils();
const { t } = useLocale();
@@ -37,6 +48,7 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
const body = {
integration: type,
externalId: externalId,
...(domainWideDelegationCredentialId && { domainWideDelegationCredentialId }),
// new URLSearchParams does not accept numbers
credentialId: String(credentialId),
...(eventTypeId ? { eventTypeId: String(eventTypeId) } : {}),
@@ -8,6 +8,7 @@ import { sendCancelledEmailsAndSMS } from "@calcom/emails";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { deleteWebhookScheduledTriggers } from "@calcom/features/webhooks/lib/scheduleTrigger";
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
import { buildNonDwdCredential } from "@calcom/lib/domainWideDelegation/server";
import { deletePayment } from "@calcom/lib/payment/deletePayment";
import { getTranslation } from "@calcom/lib/server/i18n";
import { bookingMinimalSelect, prisma } from "@calcom/prisma";
@@ -429,7 +430,7 @@ const handleDeleteCredential = async ({
// If it's a calendar remove it from the SelectedCalendars
if (credential.app?.categories.includes(AppCategories.calendar)) {
try {
const calendar = await getCalendar(credential);
const calendar = await getCalendar(buildNonDwdCredential(credential));
const calendars = await calendar?.listCalendars();
@@ -1,59 +0,0 @@
import type { Prisma } from "@prisma/client";
type DomainWideDelegationSafeSelect = {
id: string;
enabled: boolean;
domain: string;
createdAt: Date;
updatedAt: Date;
organizationId: number;
workspacePlatform: {
name: string;
slug: string;
};
};
export interface IDomainWideDelegationRepository {
create(args: {
domain: string;
enabled: boolean;
organizationId: number;
workspacePlatformId: number;
serviceAccountKey: Exclude<Prisma.JsonValue, null>;
}): Promise<DomainWideDelegationSafeSelect | null>;
findById(args: { id: string }): Promise<DomainWideDelegationSafeSelect | null>;
findByIdIncludeSensitiveServiceAccountKey(args: {
id: string;
}): Promise<(DomainWideDelegationSafeSelect & { serviceAccountKey: any }) | null>;
findUniqueByOrganizationMemberEmail(args: {
email: string;
}): Promise<DomainWideDelegationSafeSelect | null>;
findByUser(args: { user: { email: string } }): Promise<DomainWideDelegationSafeSelect | null>;
updateById(args: {
id: string;
data: Partial<{
workspacePlatformId: number;
domain: string;
enabled: boolean;
organizationId: number;
}>;
}): Promise<DomainWideDelegationSafeSelect | null>;
deleteById(args: { id: string }): Promise<any>;
findDelegationsWithServiceAccount(args: { organizationId: number }): Promise<
(DomainWideDelegationSafeSelect & {
workspacePlatform: {
id: number;
name: string;
slug: string;
};
serviceAccountKey: any;
})[]
>;
}
@@ -1,38 +0,0 @@
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import prisma from "@calcom/prisma";
import { MockDomainWideDelegationRepository } from "./mock-domain-wide-delegation.repository";
export class DomainWideDelegation {
static async checkIfDwDIsEnabled(userId: number, teamId: number | null) {
if (!teamId) {
return false;
}
const teamFeature = await prisma.teamFeatures.findFirst({
where: {
teamId: teamId,
featureId: "domain-wide-delegation",
},
});
const membership = await prisma.membership.findFirst({
where: {
userId: userId,
teamId: teamId,
accepted: true,
},
});
return !!(teamFeature && membership);
}
static async init(userId: number, teamId: number | null) {
const domainWideDelegationEnabled = await this.checkIfDwDIsEnabled(userId, teamId);
if (!domainWideDelegationEnabled) {
return new MockDomainWideDelegationRepository();
}
return new DomainWideDelegationRepository();
}
}
@@ -1,59 +0,0 @@
import type { Prisma } from "@prisma/client";
import type { IDomainWideDelegationRepository } from "./domain-wide-delegation-repository.interface";
export class MockDomainWideDelegationRepository implements IDomainWideDelegationRepository {
async create(_data: {
domain: string;
enabled: boolean;
organizationId: number;
workspacePlatformId: number;
serviceAccountKey: Exclude<Prisma.JsonValue, null>;
}) {
return null;
}
async findById(_args: { id: string }) {
return null;
}
async findByIdIncludeSensitiveServiceAccountKey(_args: { id: string }) {
return null;
}
async findUniqueByOrganizationMemberEmail(_args: { email: string }) {
return null;
}
async findByUser(_args: { user: { email: string } }) {
return null;
}
static async findAllByDomain(_args: { domain: string }) {
return [];
}
static async findFirstByOrganizationId(_args: { organizationId: number }) {
return null;
}
async updateById(_args: {
id: string;
data: Partial<{
workspacePlatformId: number;
domain: string;
enabled: boolean;
organizationId: number;
}>;
}) {
return null;
}
async deleteById(_args: { id: string }) {
return null;
}
async findDelegationsWithServiceAccount(_args: { organizationId: number }) {
return [];
}
}
@@ -289,12 +289,12 @@ function PlatformListItem({ platform, onEdit, onToggle }: Pick<Props, "platform"
onClick: () => onEdit(platform, "meta"),
icon: "pencil",
},
{
id: "edit-service-account",
label: t("edit_service_account"),
onClick: () => onEdit(platform, "serviceAccount"),
icon: "pencil",
},
// {
// id: "edit-service-account",
// label: t("edit_service_account"),
// onClick: () => onEdit(platform, "serviceAccount"),
// icon: "pencil",
// },
]}
/>
</div>
@@ -305,7 +305,7 @@ function PlatformListItem({ platform, onEdit, onToggle }: Pick<Props, "platform"
function CreatePlatformDialog({ isOpen, onOpenChange }: Pick<Props, "isOpen" | "onOpenChange">) {
const { t } = useLocale();
type FormValues = { name: string; description: string; slug: string; defaultServiceAccountKey: string };
type FormValues = { name: string; description: string; slug: string; defaultServiceAccountKey?: string };
const form = useForm<FormValues>({
defaultValues: {
name: "",
@@ -318,7 +318,7 @@ function CreatePlatformDialog({ isOpen, onOpenChange }: Pick<Props, "isOpen" | "
name: z.string(),
description: z.string(),
slug: z.string(),
defaultServiceAccountKey: z.string(),
defaultServiceAccountKey: z.string().optional(),
})
),
});
@@ -337,16 +337,27 @@ function CreatePlatformDialog({ isOpen, onOpenChange }: Pick<Props, "isOpen" | "
});
const onSubmit: SubmitHandler<FormValues> = (values) => {
const parsedKey = JSON.parse(values.defaultServiceAccountKey);
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
if (!validatedKey.success) {
form.setError("defaultServiceAccountKey", { message: t("invalid_service_account_key") });
return;
// Only validate service account key if it's provided
if (values.defaultServiceAccountKey) {
const parsedKey = JSON.parse(values.defaultServiceAccountKey);
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
if (!validatedKey.success) {
form.setError("defaultServiceAccountKey", { message: t("invalid_service_account_key") });
return;
}
addMutation.mutate({
...values,
defaultServiceAccountKey: validatedKey.data,
});
} else {
// Submit without service account key
addMutation.mutate({
name: values.name,
description: values.description,
slug: values.slug,
enabled: true,
});
}
addMutation.mutate({
...values,
defaultServiceAccountKey: validatedKey.data,
});
};
return (
@@ -419,7 +430,7 @@ function PlatformFormFields({ isCreate }: Pick<Props, "isCreate">) {
<TextField required label={t("name")} {...form.register("name")} />
<TextAreaField required label={t("description")} {...form.register("description")} />
{isCreate && <TextField required label={t("slug")} {...form.register("slug")} />}
{isCreate && <ServiceAccountFields />}
{isCreate && false && <ServiceAccountFields />}
</div>
);
}
@@ -4,6 +4,8 @@ import { useState } from "react";
import { useForm, Controller, useFormContext } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { ServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import {
DropdownActions,
@@ -13,6 +15,7 @@ import {
DialogFooter,
Form,
TextField,
TextAreaField,
SelectField,
showToast,
Badge,
@@ -90,6 +93,7 @@ function DelegationListItemActions({
{
id: "delete",
label: t("delete"),
disabled: true,
onClick: () => onDelete(delegation.id),
icon: "trash",
},
@@ -126,31 +130,65 @@ function DelegationListItem({ delegation, toggleDelegation, onEdit, onDelete }:
);
}
type CreateDelegationData = {
domain: string;
workspacePlatformSlug: string;
enabled: boolean;
serviceAccountKey: ServiceAccountKey;
};
type CreateDelegationFormData = Omit<CreateDelegationData, "serviceAccountKey"> & {
serviceAccountKey: string;
};
type EditDelegationData = {
id: string;
domain: string;
workspacePlatformSlug: string;
enabled: boolean;
};
function CreateDelegationDialog({
isOpen,
onClose,
onSubmit,
workspacePlatforms,
handleCreate,
}: {
isOpen: boolean;
onClose: () => void;
onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void;
workspacePlatforms: WorkspacePlatform[];
handleCreate: (data: CreateDelegationData) => void;
}) {
const { t } = useLocale();
const form = useForm<{ domain: string; workspacePlatformSlug: string; enabled: boolean }>({
defaultValues: {
domain: "",
workspacePlatformSlug: "",
},
});
const form = useForm<CreateDelegationFormData>();
const handleSubmit = (values: CreateDelegationFormData) => {
try {
const parsedKey = JSON.parse(values.serviceAccountKey);
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
if (!validatedKey.success) {
form.setError("serviceAccountKey", { message: t("invalid_service_account_key") });
return;
}
handleCreate({
...values,
serviceAccountKey: validatedKey.data,
});
} catch (e) {
console.log("error", e);
form.setError("serviceAccountKey", { message: t("invalid_service_account_key") });
return;
}
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent enableOverflow title={t("add_domain_wide_delegation")}>
<Form form={form} handleSubmit={onSubmit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} />
<Form form={form} handleSubmit={handleSubmit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} isCreate={true} />
<DialogFooter>
<Button type="button" color="secondary" onClick={onClose}>
{t("cancel")}
@@ -167,19 +205,20 @@ function EditDelegationDialog({
isOpen,
onClose,
delegation,
onSubmit,
workspacePlatforms,
handleEdit,
}: {
isOpen: boolean;
onClose: () => void;
delegation: DelegationItemProps["delegation"];
onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void;
workspacePlatforms: WorkspacePlatform[];
handleEdit: (data: EditDelegationData) => void;
}) {
const { t } = useLocale();
const form = useForm<{ domain: string; workspacePlatformSlug: string; enabled: boolean }>({
const form = useForm<EditDelegationData>({
defaultValues: {
id: delegation.id,
domain: delegation.domain,
workspacePlatformSlug: delegation.workspacePlatform.slug,
},
@@ -188,8 +227,8 @@ function EditDelegationDialog({
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent title={t("edit_domain_wide_delegation")}>
<Form form={form} handleSubmit={onSubmit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} />
<Form form={form} handleSubmit={handleEdit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} isCreate={false} />
<DialogFooter>
<Button type="button" color="secondary" onClick={onClose}>
{t("cancel")}
@@ -202,7 +241,13 @@ function EditDelegationDialog({
);
}
function DelegationFormFields({ workspacePlatforms }: { workspacePlatforms: WorkspacePlatform[] }) {
function DelegationFormFields({
workspacePlatforms,
isCreate,
}: {
workspacePlatforms: WorkspacePlatform[];
isCreate: boolean;
}) {
const { t } = useLocale();
const form = useFormContext();
return (
@@ -225,44 +270,18 @@ function DelegationFormFields({ workspacePlatforms }: { workspacePlatforms: Work
);
}}
/>
{isCreate && (
<TextAreaField
required
label={t("service_account_key")}
placeholder="{...}"
{...form.register("serviceAccountKey")}
/>
)}
</div>
);
}
function CreateEditDelegationDialog({
isOpen,
onClose,
delegation,
onSubmit,
workspacePlatforms,
}: {
isOpen: boolean;
onClose: () => void;
delegation: DelegationItemProps["delegation"] | null;
onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void;
workspacePlatforms: WorkspacePlatform[];
}) {
if (delegation) {
return (
<EditDelegationDialog
isOpen={isOpen}
onClose={onClose}
delegation={delegation}
onSubmit={onSubmit}
workspacePlatforms={workspacePlatforms}
/>
);
}
return (
<CreateDelegationDialog
isOpen={isOpen}
onClose={onClose}
onSubmit={onSubmit}
workspacePlatforms={workspacePlatforms}
/>
);
}
function DomainWideDelegationList() {
const { t } = useLocale();
const utils = trpc.useContext();
@@ -336,15 +355,24 @@ function DomainWideDelegationList() {
const onCreateClick = () => setCreateEditDialog({ isOpen: true, delegation: null });
const handleSubmit = (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => {
if (createEditDialog.delegation) {
updateMutation.mutate({
id: createEditDialog.delegation.id,
...data,
});
} else {
createMutation.mutate(data);
const handleCreate = (data: CreateDelegationData) => {
createMutation.mutate({
domain: data.domain,
workspacePlatformSlug: data.workspacePlatformSlug,
serviceAccountKey: data.serviceAccountKey,
});
setCreateEditDialog({ isOpen: false, delegation: null });
};
const handleEdit = (data: EditDelegationData) => {
if (!createEditDialog.delegation) {
return;
}
updateMutation.mutate({
id: createEditDialog.delegation.id,
domain: data.domain,
workspacePlatformSlug: data.workspacePlatformSlug,
});
setCreateEditDialog({ isOpen: false, delegation: null });
};
@@ -398,13 +426,22 @@ function DomainWideDelegationList() {
/>
)}
<CreateEditDelegationDialog
isOpen={createEditDialog.isOpen}
onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}
delegation={createEditDialog.delegation}
onSubmit={handleSubmit}
workspacePlatforms={enabledWorkspacePlatforms}
/>
{createEditDialog.delegation ? (
<EditDelegationDialog
isOpen={createEditDialog.isOpen}
onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}
delegation={createEditDialog.delegation}
workspacePlatforms={enabledWorkspacePlatforms}
handleEdit={handleEdit}
/>
) : (
<CreateDelegationDialog
isOpen={createEditDialog.isOpen}
onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}
workspacePlatforms={enabledWorkspacePlatforms}
handleCreate={handleCreate}
/>
)}
</div>
);
}
@@ -5,6 +5,8 @@ import { metadata as GoogleMeetMetadata } from "@calcom/app-store/googlevideo/_m
import { MeetLocationType } from "@calcom/app-store/locations";
import EventManager from "@calcom/core/EventManager";
import type { EventManagerInitParams } from "@calcom/core/EventManager";
import { getAllCredentials } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import type { EventType } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import { getVideoCallDetails } from "@calcom/features/bookings/lib/handleNewBooking/getVideoCallDetails";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import logger from "@calcom/lib/logger";
@@ -13,6 +15,17 @@ import { BookingReferenceRepository } from "@calcom/lib/server/repository/bookin
import { prisma } from "@calcom/prisma";
import type { CalendarEvent, AdditionalInformation } from "@calcom/types/Calendar";
type InitParams = {
user: {
id: number;
name: string | null;
email: string;
username: string | null;
} & EventManagerInitParams["user"];
eventTypeAppMetadata?: EventManagerInitParams["eventTypeAppMetadata"];
eventType: EventType;
};
export const handleRescheduleEventManager = async ({
evt,
rescheduleUid,
@@ -30,7 +43,7 @@ export const handleRescheduleEventManager = async ({
newBookingId?: number;
changedOrganizer?: boolean;
previousHostDestinationCalendar?: DestinationCalendar[] | null;
initParams: EventManagerInitParams;
initParams: InitParams;
bookingLocation: string | null;
bookingId: number;
bookingICalUID?: string | null;
@@ -40,7 +53,12 @@ export const handleRescheduleEventManager = async ({
prefix: ["handleRescheduleEventManager", `${bookingId}`],
});
const eventManager = new EventManager(initParams.user, initParams?.eventTypeAppMetadata);
const allCredentials = await getAllCredentials(initParams.user, initParams?.eventType);
const eventManager = new EventManager(
{ ...initParams.user, credentials: allCredentials },
initParams?.eventTypeAppMetadata
);
const updateManager = await eventManager.reschedule(
evt,
@@ -21,6 +21,7 @@ import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/rem
import { isPrismaObjOrUndefined } from "@calcom/lib";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import { SENDER_NAME } from "@calcom/lib/constants";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
@@ -274,6 +275,10 @@ export const roundRobinManualReassignment = async ({
include: { user: { select: { email: true } } },
});
const newUserWithCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
user: { ...newUser, credentials },
});
const previousHostDestinationCalendar = hasOrganizerChanged
? await prisma.destinationCalendar.findFirst({
where: { userId: originalOrganizer.id },
@@ -287,7 +292,8 @@ export const roundRobinManualReassignment = async ({
changedOrganizer: hasOrganizerChanged,
previousHostDestinationCalendar: previousHostDestinationCalendar ? [previousHostDestinationCalendar] : [],
initParams: {
user: { ...newUser, credentials },
user: newUserWithCredentials,
eventType,
},
bookingId,
bookingLocation,
@@ -22,6 +22,10 @@ import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/rem
import { isPrismaObjOrUndefined } from "@calcom/lib";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import { SENDER_NAME } from "@calcom/lib/constants";
import {
enrichHostsWithDwdCredentials,
enrichUserWithDwdCredentialsWithoutOrgId,
} from "@calcom/lib/domainWideDelegation/server";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import logger from "@calcom/lib/logger";
import { getLuckyUser } from "@calcom/lib/server/getLuckyUser";
@@ -115,8 +119,12 @@ export const roundRobinReassignment = async ({
const previousRRHostT = await getTranslation(previousRRHost?.locale || "en", "common");
const eventTypeHosts = await enrichHostsWithDwdCredentials({
orgId,
hosts: eventType.hosts,
});
// Filter out the current attendees of the booking from the event type
const availableEventTypeUsers = eventType.hosts.reduce((availableUsers, host) => {
const availableEventTypeUsers = eventTypeHosts.reduce((availableUsers, host) => {
if (!attendeeEmailsSet.has(host.user.email) && host.user.email !== originalOrganizer.email) {
availableUsers.push({ ...host.user, isFixed: host.isFixed, priority: host?.priority ?? 2 });
}
@@ -136,7 +144,7 @@ export const roundRobinReassignment = async ({
const reassignedRRHost = await getLuckyUser({
availableUsers,
eventType,
allRRHosts: eventType.hosts.filter((host) => !host.isFixed), // todo: only use hosts from virtual queue
allRRHosts: eventTypeHosts.filter((host) => !host.isFixed), // todo: only use hosts from virtual queue
routingFormResponse: null,
});
@@ -312,6 +320,10 @@ export const roundRobinReassignment = async ({
},
});
const organizerWithCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
user: { ...organizer, credentials },
});
const { evtWithAdditionalInfo } = await handleRescheduleEventManager({
evt,
rescheduleUid: booking.uid,
@@ -319,7 +331,8 @@ export const roundRobinReassignment = async ({
changedOrganizer: hasOrganizerChanged,
previousHostDestinationCalendar: previousHostDestinationCalendar ? [previousHostDestinationCalendar] : [],
initParams: {
user: { ...organizer, credentials: [...credentials] },
user: organizerWithCredentials,
eventType,
},
bookingId,
bookingLocation,