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

@@ -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,