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
@@ -108,7 +108,7 @@ async function handler(req: NextApiRequest) {
|
||||
// ^ Workaround for the select in `create` not working
|
||||
|
||||
if (createCalendarResources) {
|
||||
const calendar = await getCalendar(credential);
|
||||
const calendar = await getCalendar({ ...credential, delegatedTo: null });
|
||||
if (!calendar) throw new HttpError({ message: "Calendar missing for credential", statusCode: 500 });
|
||||
const calendars = await calendar.listCalendars();
|
||||
const calendarToCreate = calendars.find((calendar) => calendar.primary) || calendars[0];
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Prisma } from "@prisma/client";
|
||||
import type { NextApiRequest } from "next";
|
||||
import type { z } from "zod";
|
||||
|
||||
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
|
||||
import { getCalendarCredentialsWithoutDwd, getConnectedCalendars } from "@calcom/core/CalendarManager";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import prisma from "@calcom/prisma";
|
||||
@@ -185,7 +185,7 @@ async function verifyCredentialsAndGetId({
|
||||
currentCredentialId: number | null;
|
||||
}) {
|
||||
if (parsedBody.integration && parsedBody.externalId) {
|
||||
const calendarCredentials = getCalendarCredentials(userCredentials);
|
||||
const calendarCredentials = getCalendarCredentialsWithoutDwd(userCredentials);
|
||||
|
||||
const { connectedCalendars } = await getConnectedCalendars(
|
||||
calendarCredentials,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
|
||||
import { getCalendarCredentialsWithoutDwd, getConnectedCalendars } from "@calcom/core/CalendarManager";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import prisma from "@calcom/prisma";
|
||||
@@ -82,7 +82,7 @@ async function postHandler(req: NextApiRequest) {
|
||||
message: "Bad request, credential id invalid",
|
||||
});
|
||||
|
||||
const calendarCredentials = getCalendarCredentials(userCredentials);
|
||||
const calendarCredentials = getCalendarCredentialsWithoutDwd(userCredentials);
|
||||
|
||||
const { connectedCalendars } = await getConnectedCalendars(calendarCredentials, [], parsedBody.externalId);
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
"@axiomhq/winston": "^1.2.0",
|
||||
"@calcom/platform-constants": "*",
|
||||
"@calcom/platform-enums": "*",
|
||||
"@calcom/platform-libraries": "npm:@calcom/[email protected]1",
|
||||
"@calcom/platform-libraries": "npm:@calcom/[email protected]3",
|
||||
"@calcom/platform-libraries-0.0.2": "npm:@calcom/[email protected]",
|
||||
"@calcom/platform-types": "*",
|
||||
"@calcom/platform-utils": "*",
|
||||
|
||||
@@ -127,6 +127,11 @@ class Primary {
|
||||
@IsInt()
|
||||
@ApiProperty()
|
||||
credentialId!: number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiPropertyOptional({ type: String, nullable: true })
|
||||
domainWideDelegationCredentialId?: string | null;
|
||||
}
|
||||
|
||||
export class Calendar {
|
||||
@@ -165,6 +170,11 @@ export class Calendar {
|
||||
@IsInt()
|
||||
@ApiProperty()
|
||||
credentialId!: number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiPropertyOptional({ type: String, nullable: true })
|
||||
domainWideDelegationCredentialId?: string | null;
|
||||
}
|
||||
|
||||
export class ConnectedCalendar {
|
||||
@@ -177,6 +187,11 @@ export class ConnectedCalendar {
|
||||
@ApiProperty()
|
||||
credentialId!: number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiPropertyOptional({ type: String, nullable: true })
|
||||
domainWideDelegationCredentialId?: string | null;
|
||||
|
||||
@ValidateNested()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
@@ -220,6 +235,11 @@ class DestinationCalendar {
|
||||
@ApiProperty({ type: Number, nullable: true })
|
||||
credentialId!: number | null;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiPropertyOptional({ type: String, nullable: true })
|
||||
domainWideDelegationCredentialId?: string | null;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiPropertyOptional({ type: String, nullable: true })
|
||||
|
||||
@@ -39,6 +39,16 @@ export class CalendarsService {
|
||||
private readonly selectedCalendarsRepository: SelectedCalendarsRepository
|
||||
) {}
|
||||
|
||||
private buildNonDwdCredentials<TCredential>(credentials: TCredential[]) {
|
||||
return credentials
|
||||
.map((credential) => ({
|
||||
...credential,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
}))
|
||||
.filter((credential) => !!credential);
|
||||
}
|
||||
|
||||
async getCalendars(userId: number) {
|
||||
const userWithCalendars = await this.usersRepository.findByIdWithCalendars(userId);
|
||||
if (!userWithCalendars) {
|
||||
@@ -73,7 +83,7 @@ export class CalendarsService {
|
||||
);
|
||||
try {
|
||||
const calendarBusyTimes = await getBusyCalendarTimes(
|
||||
credentials,
|
||||
this.buildNonDwdCredentials(credentials),
|
||||
dateFrom,
|
||||
dateTo,
|
||||
composedSelectedCalendars
|
||||
|
||||
@@ -210,6 +210,7 @@ export class EventTypesAtomService {
|
||||
credentials = credentials.concat(teamAppCredentials);
|
||||
}
|
||||
}
|
||||
//TODO: enrich credentials for DWD
|
||||
const enabledApps = await getEnabledAppsFromCredentials(credentials, {
|
||||
where: { slug },
|
||||
});
|
||||
|
||||
@@ -196,10 +196,10 @@ export class ConferencingController {
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@ApiOperation({ summary: "Set your default conferencing application" })
|
||||
async default(
|
||||
@GetUser("id") userId: number,
|
||||
@GetUser() user: UserWithProfile,
|
||||
@Param("app") app: string
|
||||
): Promise<SetDefaultConferencingAppOutputResponseDto> {
|
||||
await this.conferencingService.setDefaultConferencingApp(userId, app);
|
||||
await this.conferencingService.setDefaultConferencingApp(user, app);
|
||||
return { status: SUCCESS_STATUS };
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,12 @@ import { BadRequestException, InternalServerErrorException, Logger } from "@nest
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { CONFERENCING_APPS, CAL_VIDEO } from "@calcom/platform-constants";
|
||||
import { userMetadata, handleDeleteCredential } from "@calcom/platform-libraries";
|
||||
import {
|
||||
userMetadata,
|
||||
handleDeleteCredential,
|
||||
getApps,
|
||||
getUsersCredentials,
|
||||
} from "@calcom/platform-libraries";
|
||||
|
||||
@Injectable()
|
||||
export class ConferencingService {
|
||||
@@ -25,20 +30,24 @@ export class ConferencingService {
|
||||
return userMetadata.parse(user?.metadata)?.defaultConferencingApp;
|
||||
}
|
||||
|
||||
async checkAppIsValidAndConnected(userId: number, app: string) {
|
||||
if (!CONFERENCING_APPS.includes(app)) {
|
||||
async checkAppIsValidAndConnected(user: UserWithProfile, appSlug: string) {
|
||||
if (!CONFERENCING_APPS.includes(appSlug)) {
|
||||
throw new BadRequestException("Invalid app, available apps are: ", CONFERENCING_APPS.join(", "));
|
||||
}
|
||||
const credential = await this.conferencingRepository.findConferencingApp(userId, app);
|
||||
const credentials = await getUsersCredentials(user);
|
||||
|
||||
if (!credential) {
|
||||
throw new BadRequestException(`${app} not connected.`);
|
||||
const foundApp = getApps(credentials, true).filter((app) => app.slug === appSlug)[0];
|
||||
|
||||
const appLocation = foundApp?.appData?.location;
|
||||
|
||||
if (!foundApp || !appLocation) {
|
||||
throw new BadRequestException(`${appSlug} not connected.`);
|
||||
}
|
||||
return credential;
|
||||
return foundApp.credential;
|
||||
}
|
||||
|
||||
async disconnectConferencingApp(user: UserWithProfile, app: string) {
|
||||
const credential = await this.checkAppIsValidAndConnected(user.id, app);
|
||||
const credential = await this.checkAppIsValidAndConnected(user, app);
|
||||
return handleDeleteCredential({
|
||||
userId: user.id,
|
||||
userMetadata: user?.metadata,
|
||||
@@ -46,13 +55,13 @@ export class ConferencingService {
|
||||
});
|
||||
}
|
||||
|
||||
async setDefaultConferencingApp(userId: number, app: string) {
|
||||
async setDefaultConferencingApp(user: UserWithProfile, app: string) {
|
||||
// cal-video is global, so we can skip this check
|
||||
if (app !== CAL_VIDEO) {
|
||||
await this.checkAppIsValidAndConnected(userId, app);
|
||||
await this.checkAppIsValidAndConnected(user, app);
|
||||
}
|
||||
const user = await this.usersRepository.setDefaultConferencingApp(userId, app);
|
||||
const metadata = user.metadata as { defaultConferencingApp?: { appSlug?: string } };
|
||||
const updatedUser = await this.usersRepository.setDefaultConferencingApp(user.id, app);
|
||||
const metadata = updatedUser.metadata as { defaultConferencingApp?: { appSlug?: string } };
|
||||
if (metadata?.defaultConferencingApp?.appSlug !== app) {
|
||||
throw new InternalServerErrorException(`Could not set ${app} as default conferencing app`);
|
||||
}
|
||||
|
||||
+3
-2
@@ -29,11 +29,12 @@ export class DestinationCalendarsController {
|
||||
@Body() input: DestinationCalendarsInputBodyDto,
|
||||
@GetUser() user: UserWithProfile
|
||||
): Promise<DestinationCalendarsOutputResponseDto> {
|
||||
const { integration, externalId } = input;
|
||||
const { integration, externalId, domainWideDelegationCredentialId } = input;
|
||||
const updatedDestinationCalendar = await this.destinationCalendarsService.updateDestinationCalendars(
|
||||
integration,
|
||||
externalId,
|
||||
user.id
|
||||
user.id,
|
||||
domainWideDelegationCredentialId
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -8,21 +8,25 @@ export class DestinationCalendarsRepository {
|
||||
async updateCalendar(
|
||||
integration: string,
|
||||
externalId: string,
|
||||
credentialId: number,
|
||||
|
||||
userId: number,
|
||||
primaryEmail: string | null
|
||||
primaryEmail: string | null,
|
||||
credentialId?: number,
|
||||
domainWideDelegationCredentialId?: string
|
||||
) {
|
||||
return await this.dbWrite.prisma.destinationCalendar.upsert({
|
||||
update: {
|
||||
integration,
|
||||
externalId,
|
||||
credentialId,
|
||||
...(credentialId ? { credentialId } : {}),
|
||||
...(domainWideDelegationCredentialId ? { domainWideDelegationCredentialId } : {}),
|
||||
primaryEmail,
|
||||
},
|
||||
create: {
|
||||
integration,
|
||||
externalId,
|
||||
credentialId,
|
||||
...(credentialId ? { credentialId } : {}),
|
||||
...(domainWideDelegationCredentialId ? { domainWideDelegationCredentialId } : {}),
|
||||
primaryEmail,
|
||||
userId,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Expose } from "class-transformer";
|
||||
import { IsString, IsEnum } from "class-validator";
|
||||
import { IsString, IsEnum, IsOptional } from "class-validator";
|
||||
|
||||
import {
|
||||
APPLE_CALENDAR_TYPE,
|
||||
@@ -33,4 +33,9 @@ export class DestinationCalendarsInputBodyDto {
|
||||
required: true,
|
||||
})
|
||||
readonly externalId!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@ApiPropertyOptional()
|
||||
readonly domainWideDelegationCredentialId?: string;
|
||||
}
|
||||
+29
-7
@@ -10,9 +10,16 @@ export class DestinationCalendarsService {
|
||||
private readonly destinationCalendarsRepository: DestinationCalendarsRepository
|
||||
) {}
|
||||
|
||||
async updateDestinationCalendars(integration: string, externalId: string, userId: number) {
|
||||
async updateDestinationCalendars(
|
||||
integration: string,
|
||||
externalId: string,
|
||||
userId: number,
|
||||
domainWideDelegationCredentialId?: string
|
||||
) {
|
||||
// note(Lauris): todo remove the log but leaving this now to confirm domainWideDelegationCredentialId is received
|
||||
console.log("debug: domainWideDelegationCredentialId", domainWideDelegationCredentialId);
|
||||
const userCalendars = await this.calendarsService.getCalendars(userId);
|
||||
const allCalendars = userCalendars.connectedCalendars
|
||||
const allCalendars: Calendar[] = userCalendars.connectedCalendars
|
||||
.map((cal: ConnectedCalendar) => cal.calendars ?? [])
|
||||
.flat();
|
||||
const credentialId = allCalendars.find(
|
||||
@@ -20,12 +27,26 @@ export class DestinationCalendarsService {
|
||||
cal.externalId === externalId && cal.integration === integration && cal.readOnly === false
|
||||
)?.credentialId;
|
||||
|
||||
if (!credentialId) {
|
||||
if (!domainWideDelegationCredentialId && !credentialId) {
|
||||
throw new NotFoundException(`Could not find calendar ${externalId}`);
|
||||
}
|
||||
|
||||
const primaryEmail =
|
||||
allCalendars.find((cal: Calendar) => cal.primary && cal.credentialId === credentialId)?.email ?? null;
|
||||
const dwdCalendar = domainWideDelegationCredentialId
|
||||
? allCalendars.find(
|
||||
(cal: Calendar) =>
|
||||
cal.externalId === externalId &&
|
||||
cal.integration === integration &&
|
||||
cal.domainWideDelegationCredentialId === domainWideDelegationCredentialId
|
||||
)
|
||||
: undefined;
|
||||
|
||||
if (domainWideDelegationCredentialId && !dwdCalendar) {
|
||||
throw new NotFoundException(`Could not find calendar ${externalId}`);
|
||||
}
|
||||
|
||||
const primaryEmail = dwdCalendar
|
||||
? (dwdCalendar.primary && dwdCalendar?.email) || undefined
|
||||
: allCalendars.find((cal: Calendar) => cal.primary && cal.credentialId === credentialId)?.email;
|
||||
|
||||
const {
|
||||
integration: updatedCalendarIntegration,
|
||||
@@ -35,9 +56,10 @@ export class DestinationCalendarsService {
|
||||
} = await this.destinationCalendarsRepository.updateCalendar(
|
||||
integration,
|
||||
externalId,
|
||||
credentialId,
|
||||
userId,
|
||||
primaryEmail
|
||||
primaryEmail ?? null,
|
||||
dwdCalendar ? undefined : credentialId,
|
||||
dwdCalendar ? domainWideDelegationCredentialId : undefined
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
GoogleServiceAccountKeyInput,
|
||||
ServiceAccountKeyValidator,
|
||||
MicrosoftServiceAccountKeyInput,
|
||||
} from "@/modules/organizations/dwd/inputs/service-account-key.input";
|
||||
import { ApiProperty, getSchemaPath } from "@nestjs/swagger";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsString, IsNotEmpty, ValidateNested, Validate } from "class-validator";
|
||||
|
||||
export class CreateDwdInput {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
workspacePlatformSlug!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
@Expose()
|
||||
domain!: string;
|
||||
|
||||
@Validate(ServiceAccountKeyValidator)
|
||||
@ApiProperty({
|
||||
type: [GoogleServiceAccountKeyInput, MicrosoftServiceAccountKeyInput],
|
||||
oneOf: [
|
||||
{ $ref: getSchemaPath(GoogleServiceAccountKeyInput) },
|
||||
{ $ref: getSchemaPath(MicrosoftServiceAccountKeyInput) },
|
||||
],
|
||||
})
|
||||
@Expose()
|
||||
@Type(() => Object)
|
||||
serviceAccountKey!: GoogleServiceAccountKeyInput | MicrosoftServiceAccountKeyInput;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { Type, plainToClass, Expose } from "class-transformer";
|
||||
import {
|
||||
IsString,
|
||||
IsNotEmpty,
|
||||
ValidationOptions,
|
||||
ValidatorConstraint,
|
||||
ValidatorConstraintInterface,
|
||||
validateSync,
|
||||
} from "class-validator";
|
||||
|
||||
export class MicrosoftServiceAccountKeyInput {
|
||||
@Expose()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
private_key!: string;
|
||||
|
||||
@Expose()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
tenant_id!: string;
|
||||
|
||||
@Expose()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
client_id!: string;
|
||||
}
|
||||
|
||||
export class GoogleServiceAccountKeyInput {
|
||||
@Expose()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
private_key!: string;
|
||||
|
||||
@Expose()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
client_email!: string;
|
||||
|
||||
@Expose()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@ApiProperty()
|
||||
client_id!: string;
|
||||
}
|
||||
|
||||
@ValidatorConstraint({ name: "isServiceAccountKey", async: false })
|
||||
export class ServiceAccountKeyValidator implements ValidatorConstraintInterface {
|
||||
validate(value: any) {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
|
||||
if ("client_email" in value) {
|
||||
const googleKey = plainToClass(GoogleServiceAccountKeyInput, value, {
|
||||
excludeExtraneousValues: true,
|
||||
});
|
||||
const googleErrors = validateSync(googleKey, {
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
skipMissingProperties: false,
|
||||
});
|
||||
|
||||
if (googleErrors.length === 0) return true;
|
||||
this.errors = googleErrors;
|
||||
return false;
|
||||
}
|
||||
|
||||
if ("tenant_id" in value) {
|
||||
const msKey = plainToClass(MicrosoftServiceAccountKeyInput, value, {
|
||||
excludeExtraneousValues: true,
|
||||
});
|
||||
const msErrors = validateSync(msKey, {
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
skipMissingProperties: false,
|
||||
});
|
||||
|
||||
if (msErrors.length === 0) return true;
|
||||
this.errors = msErrors;
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private errors?: any[];
|
||||
|
||||
defaultMessage() {
|
||||
if (this.errors?.length) {
|
||||
return this.errors.map((error) => Object.values(error.constraints || {}).join(", ")).join("; ");
|
||||
}
|
||||
|
||||
return "Service account key must be either a Google service account key (with client_email, private_key, client_id) or Microsoft service account key (with tenant_id, private_key, client_id)";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
GoogleServiceAccountKeyInput,
|
||||
MicrosoftServiceAccountKeyInput,
|
||||
ServiceAccountKeyValidator,
|
||||
} from "@/modules/organizations/dwd/inputs/service-account-key.input";
|
||||
import { ApiPropertyOptional, getSchemaPath } from "@nestjs/swagger";
|
||||
import { Expose, plainToClass, Transform, Type } from "class-transformer";
|
||||
import { IsBoolean, IsOptional, Validate, ValidateNested } from "class-validator";
|
||||
|
||||
export class UpdateDwdInput {
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
@ApiPropertyOptional()
|
||||
@Expose()
|
||||
enabled?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@Validate(ServiceAccountKeyValidator)
|
||||
@ApiPropertyOptional({
|
||||
type: [GoogleServiceAccountKeyInput, MicrosoftServiceAccountKeyInput],
|
||||
oneOf: [
|
||||
{ $ref: getSchemaPath(GoogleServiceAccountKeyInput) },
|
||||
{ $ref: getSchemaPath(MicrosoftServiceAccountKeyInput) },
|
||||
],
|
||||
})
|
||||
@Expose()
|
||||
@Type(() => Object)
|
||||
serviceAccountKey?: GoogleServiceAccountKeyInput | MicrosoftServiceAccountKeyInput;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator";
|
||||
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
|
||||
import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.guard";
|
||||
import { IsAdminAPIEnabledGuard } from "@/modules/auth/guards/organizations/is-admin-api-enabled.guard";
|
||||
import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
|
||||
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
|
||||
import { UpdateDwdInput } from "@/modules/organizations/dwd/inputs/update-dwd.input";
|
||||
import { CreateDwdOutput } from "@/modules/organizations/dwd/outputs/create-dwd.output";
|
||||
import { DwdOutput } from "@/modules/organizations/dwd/outputs/dwd.output";
|
||||
import { UpdateDwdOutput } from "@/modules/organizations/dwd/outputs/update-dwd.output";
|
||||
import { OrganizationsDwdService } from "@/modules/organizations/dwd/services/organizations-dwd.service";
|
||||
import {
|
||||
Controller,
|
||||
UseGuards,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Post,
|
||||
Body,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Patch,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
|
||||
import { User } from "@prisma/client";
|
||||
import { plainToClass } from "class-transformer";
|
||||
|
||||
import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
|
||||
import { CreateDwdInput } from "./inputs/create-dwd.input";
|
||||
|
||||
@Controller({
|
||||
path: "/v2/organizations/:orgId/delegation-credentials",
|
||||
version: API_VERSIONS_VALUES,
|
||||
})
|
||||
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, PlatformPlanGuard, IsAdminAPIEnabledGuard)
|
||||
@DocsTags("Orgs / Delegation Credentials")
|
||||
export class OrganizationsDwdController {
|
||||
constructor(private readonly dwdService: OrganizationsDwdService) {}
|
||||
|
||||
@Post("/")
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@Roles("ORG_ADMIN")
|
||||
@PlatformPlan("SCALE")
|
||||
@ApiOperation({ summary: "Save delegation credentials for your organization." })
|
||||
async createDwd(
|
||||
@Param("orgId", ParseIntPipe) orgId: number,
|
||||
@GetUser() dwdServiceAccountUser: User,
|
||||
@Body() body: CreateDwdInput
|
||||
): Promise<CreateDwdOutput> {
|
||||
const dwd = await this.dwdService.createDwd(orgId, dwdServiceAccountUser, body);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: plainToClass(DwdOutput, dwd, { strategy: "excludeAll" }),
|
||||
};
|
||||
}
|
||||
|
||||
@Patch("/:credentialId")
|
||||
@Roles("ORG_ADMIN")
|
||||
@PlatformPlan("SCALE")
|
||||
@ApiOperation({ summary: "Update delegation credentials of your organization." })
|
||||
async updateDwd(
|
||||
@Param("orgId", ParseIntPipe) orgId: number,
|
||||
@GetUser() dwdServiceAccountUser: User,
|
||||
@Body() body: UpdateDwdInput,
|
||||
@Param("credentialId") credentialId: string
|
||||
): Promise<UpdateDwdOutput> {
|
||||
const dwd = await this.dwdService.updateDwd(orgId, credentialId, dwdServiceAccountUser, body);
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: plainToClass(DwdOutput, dwd, { strategy: "excludeAll" }),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { MembershipsModule } from "@/modules/memberships/memberships.module";
|
||||
import { OrganizationsDwdController } from "@/modules/organizations/dwd/organizations-dwd.controller";
|
||||
import { OrganizationsDwdRepository } from "@/modules/organizations/dwd/organizations-dwd.repository";
|
||||
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { RedisModule } from "@/modules/redis/redis.module";
|
||||
import { StripeModule } from "@/modules/stripe/stripe.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
import { OrganizationsDwdService } from "./services/organizations-dwd.service";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, StripeModule, RedisModule, MembershipsModule],
|
||||
providers: [OrganizationsDwdService, OrganizationsDwdRepository, OrganizationsRepository],
|
||||
controllers: [OrganizationsDwdController],
|
||||
})
|
||||
export class OrganizationsDwdModule {}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
import { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
@Injectable()
|
||||
export class OrganizationsDwdRepository {
|
||||
constructor(private readonly dbRead: PrismaReadService) {}
|
||||
|
||||
async findById(dwdId: string) {
|
||||
return this.dbRead.prisma.domainWideDelegation.findUnique({ where: { id: dwdId } });
|
||||
}
|
||||
|
||||
async findByIdWithWorkspacePlatform(dwdId: string) {
|
||||
return this.dbRead.prisma.domainWideDelegation.findUnique({
|
||||
where: { id: dwdId },
|
||||
include: { workspacePlatform: true },
|
||||
});
|
||||
}
|
||||
|
||||
async updateIncludeWorkspacePlatform(dwdId: string, data: Prisma.DomainWideDelegationUncheckedUpdateInput) {
|
||||
return this.dbRead.prisma.domainWideDelegation.update({
|
||||
where: { id: dwdId },
|
||||
data,
|
||||
include: { workspacePlatform: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { DwdOutput } from "@/modules/organizations/dwd/outputs/dwd.output";
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
|
||||
|
||||
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
|
||||
|
||||
export class CreateDwdOutput {
|
||||
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
|
||||
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
|
||||
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
|
||||
|
||||
@ApiProperty({
|
||||
type: DwdOutput,
|
||||
})
|
||||
@IsNotEmptyObject()
|
||||
@ValidateNested()
|
||||
@Type(() => DwdOutput)
|
||||
data!: DwdOutput;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { Expose, Type } from "class-transformer";
|
||||
import { IsBoolean, IsDate, IsInt, IsObject, IsString, ValidateNested } from "class-validator";
|
||||
|
||||
class WorkspacePlatformDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@Expose()
|
||||
name!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@Expose()
|
||||
slug!: string;
|
||||
}
|
||||
|
||||
export class DwdOutput {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@Expose()
|
||||
id!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsBoolean()
|
||||
@Expose()
|
||||
enabled!: boolean;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@Expose()
|
||||
domain!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsInt()
|
||||
@Expose()
|
||||
organizationId!: number;
|
||||
|
||||
@ApiProperty({ type: WorkspacePlatformDto })
|
||||
@Type(() => WorkspacePlatformDto)
|
||||
@IsObject()
|
||||
@ValidateNested()
|
||||
@Expose()
|
||||
workspacePlatform!: WorkspacePlatformDto;
|
||||
|
||||
@ApiProperty()
|
||||
@Type(() => Date)
|
||||
@IsDate()
|
||||
@Expose()
|
||||
createdAt!: Date;
|
||||
|
||||
@ApiProperty()
|
||||
@Type(() => Date)
|
||||
@IsDate()
|
||||
@Expose()
|
||||
updatedAt!: Date;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { DwdOutput } from "@/modules/organizations/dwd/outputs/dwd.output";
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
|
||||
|
||||
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
|
||||
|
||||
export class UpdateDwdOutput {
|
||||
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
|
||||
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
|
||||
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
|
||||
|
||||
@ApiProperty({
|
||||
type: DwdOutput,
|
||||
})
|
||||
@IsNotEmptyObject()
|
||||
@ValidateNested()
|
||||
@Type(() => DwdOutput)
|
||||
data!: DwdOutput;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { CreateDwdInput } from "@/modules/organizations/dwd/inputs/create-dwd.input";
|
||||
import {
|
||||
GoogleServiceAccountKeyInput,
|
||||
MicrosoftServiceAccountKeyInput,
|
||||
} from "@/modules/organizations/dwd/inputs/service-account-key.input";
|
||||
import { UpdateDwdInput } from "@/modules/organizations/dwd/inputs/update-dwd.input";
|
||||
import { OrganizationsDwdRepository } from "@/modules/organizations/dwd/organizations-dwd.repository";
|
||||
import { DwdOutput } from "@/modules/organizations/dwd/outputs/dwd.output";
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { User } from "@prisma/client";
|
||||
|
||||
import { addDwd, toggleDwdEnabled, encryptServiceAccountKey } from "@calcom/platform-libraries";
|
||||
|
||||
@Injectable()
|
||||
export class OrganizationsDwdService {
|
||||
constructor(private readonly organizationsDwdRepository: OrganizationsDwdRepository) {}
|
||||
async createDwd(orgId: number, dwdServiceAccountUser: User, body: CreateDwdInput) {
|
||||
console.log("asap body", JSON.stringify(body, null, 2));
|
||||
const dwd = await addDwd({
|
||||
input: body,
|
||||
ctx: { user: { id: dwdServiceAccountUser.id, organizationId: orgId } },
|
||||
});
|
||||
return dwd;
|
||||
}
|
||||
|
||||
async updateDwd(orgId: number, dwdId: string, dwdServiceAccountUser: User, body: UpdateDwdInput) {
|
||||
if (body.enabled !== undefined) {
|
||||
await this.updateDwdEnabled(orgId, dwdId, dwdServiceAccountUser, body.enabled);
|
||||
}
|
||||
if (body.serviceAccountKey !== undefined) {
|
||||
await this.updateDwdServiceAccountKey(dwdId, body.serviceAccountKey);
|
||||
}
|
||||
const dwd = await this.organizationsDwdRepository.findByIdWithWorkspacePlatform(dwdId);
|
||||
if (!dwd) {
|
||||
throw new NotFoundException(`DWD with id ${dwdId} not found`);
|
||||
}
|
||||
|
||||
return dwd;
|
||||
}
|
||||
|
||||
async updateDwdEnabled(orgId: number, dwdId: string, dwdServiceAccountUser: User, enabled: boolean) {
|
||||
const handlerUser = {
|
||||
id: dwdServiceAccountUser.id,
|
||||
email: dwdServiceAccountUser.email,
|
||||
organizationId: orgId,
|
||||
};
|
||||
const handlerBody = { id: dwdId, enabled };
|
||||
const dwd = await toggleDwdEnabled(handlerUser, handlerBody);
|
||||
return dwd;
|
||||
}
|
||||
|
||||
async updateDwdServiceAccountKey(
|
||||
dwdId: string,
|
||||
serviceAccountKey: GoogleServiceAccountKeyInput | MicrosoftServiceAccountKeyInput
|
||||
) {
|
||||
const encryptedServiceAccountKey = encryptServiceAccountKey(serviceAccountKey);
|
||||
const dwd = await this.organizationsDwdRepository.updateIncludeWorkspacePlatform(dwdId, {
|
||||
serviceAccountKey: encryptedServiceAccountKey,
|
||||
});
|
||||
return dwd;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { OrganizationAttributesService } from "@/modules/organizations/attribute
|
||||
import { OrganizationAttributeOptionRepository } from "@/modules/organizations/attributes/options/organization-attribute-options.repository";
|
||||
import { OrganizationsAttributesOptionsController } from "@/modules/organizations/attributes/options/organizations-attributes-options.controller";
|
||||
import { OrganizationAttributeOptionService } from "@/modules/organizations/attributes/options/services/organization-attributes-option.service";
|
||||
import { OrganizationsDwdModule } from "@/modules/organizations/dwd/organizations-dwd.module";
|
||||
import { OrganizationsEventTypesController } from "@/modules/organizations/event-types/organizations-event-types.controller";
|
||||
import { OrganizationsEventTypesRepository } from "@/modules/organizations/event-types/organizations-event-types.repository";
|
||||
import { OutputTeamEventTypesResponsePipe } from "@/modules/organizations/event-types/pipes/team-event-types-response.transformer";
|
||||
@@ -64,6 +65,7 @@ import { Module } from "@nestjs/common";
|
||||
EventTypesModule_2024_06_14,
|
||||
TeamsEventTypesModule,
|
||||
TeamsModule,
|
||||
OrganizationsDwdModule,
|
||||
OrganizationsOrganizationsModule,
|
||||
OrganizationsTeamsRoutingFormsModule,
|
||||
],
|
||||
|
||||
+8
-26
@@ -1,5 +1,3 @@
|
||||
import { CalendarsRepository } from "@/ee/calendars/calendars.repository";
|
||||
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
@@ -11,7 +9,7 @@ import {
|
||||
SelectedCalendarOutputResponseDto,
|
||||
SelectedCalendarOutputDto,
|
||||
} from "@/modules/selected-calendars/outputs/selected-calendars.output";
|
||||
import { SelectedCalendarsRepository } from "@/modules/selected-calendars/selected-calendars.repository";
|
||||
import { SelectedCalendarsService } from "@/modules/selected-calendars/services/selected-calendars.service";
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { Body, Controller, Post, UseGuards, Delete, Query } from "@nestjs/common";
|
||||
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
|
||||
@@ -25,11 +23,7 @@ import { SUCCESS_STATUS } from "@calcom/platform-constants";
|
||||
})
|
||||
@DocsTags("Selected Calendars")
|
||||
export class SelectedCalendarsController {
|
||||
constructor(
|
||||
private readonly calendarsRepository: CalendarsRepository,
|
||||
private readonly selectedCalendarsRepository: SelectedCalendarsRepository,
|
||||
private readonly calendarsService: CalendarsService
|
||||
) {}
|
||||
constructor(private readonly selectedCalendarsService: SelectedCalendarsService) {}
|
||||
|
||||
@Post("/")
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@@ -38,36 +32,24 @@ export class SelectedCalendarsController {
|
||||
@Body() input: SelectedCalendarsInputDto,
|
||||
@GetUser() user: UserWithProfile
|
||||
): Promise<SelectedCalendarOutputResponseDto> {
|
||||
const { integration, externalId, credentialId } = input;
|
||||
await this.calendarsService.checkCalendarCredentials(Number(credentialId), user.id);
|
||||
|
||||
const newlyAddedCalendarEntry = await this.selectedCalendarsRepository.addUserSelectedCalendar(
|
||||
user.id,
|
||||
integration,
|
||||
externalId,
|
||||
credentialId
|
||||
);
|
||||
const selectedCalendar = await this.selectedCalendarsService.addSelectedCalendar(user, input);
|
||||
|
||||
return {
|
||||
status: SUCCESS_STATUS,
|
||||
data: plainToClass(SelectedCalendarOutputDto, newlyAddedCalendarEntry, { strategy: "excludeAll" }),
|
||||
data: plainToClass(SelectedCalendarOutputDto, selectedCalendar, { strategy: "excludeAll" }),
|
||||
};
|
||||
}
|
||||
|
||||
@Delete("/")
|
||||
@UseGuards(ApiAuthGuard)
|
||||
@ApiOperation({ summary: "Delete a selected calendar" })
|
||||
async removeSelectedCalendar(
|
||||
async deleteSelectedCalendar(
|
||||
@Query() queryParams: SelectedCalendarsQueryParamsInputDto,
|
||||
@GetUser() user: UserWithProfile
|
||||
): Promise<SelectedCalendarOutputResponseDto> {
|
||||
const { integration, externalId, credentialId } = queryParams;
|
||||
await this.calendarsService.checkCalendarCredentials(Number(credentialId), user.id);
|
||||
|
||||
const removedCalendarEntry = await this.selectedCalendarsRepository.removeUserSelectedCalendar(
|
||||
user.id,
|
||||
integration,
|
||||
externalId
|
||||
const removedCalendarEntry = await this.selectedCalendarsService.deleteSelectedCalendar(
|
||||
queryParams,
|
||||
user
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { IsInt, IsString } from "class-validator";
|
||||
import { IsInt, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class SelectedCalendarsInputDto {
|
||||
@IsString()
|
||||
@@ -9,6 +9,10 @@ export class SelectedCalendarsInputDto {
|
||||
|
||||
@IsInt()
|
||||
readonly credentialId!: number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
readonly domainWideDelegationCredentialId?: string;
|
||||
}
|
||||
|
||||
export class SelectedCalendarsQueryParamsInputDto {
|
||||
@@ -20,4 +24,8 @@ export class SelectedCalendarsQueryParamsInputDto {
|
||||
|
||||
@IsString()
|
||||
readonly credentialId!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
readonly domainWideDelegationCredentialId?: string;
|
||||
}
|
||||
@@ -2,9 +2,13 @@ import { CalendarsRepository } from "@/ee/calendars/calendars.repository";
|
||||
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||
import { AppsRepository } from "@/modules/apps/apps.repository";
|
||||
import { CredentialsRepository } from "@/modules/credentials/credentials.repository";
|
||||
import { OrganizationsDwdRepository } from "@/modules/organizations/dwd/organizations-dwd.repository";
|
||||
import { OrganizationsMembershipRepository } from "@/modules/organizations/memberships/organizations-membership.repository";
|
||||
import { OrganizationsMembershipService } from "@/modules/organizations/memberships/services/organizations-membership.service";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { SelectedCalendarsController } from "@/modules/selected-calendars/controllers/selected-calendars.controller";
|
||||
import { SelectedCalendarsRepository } from "@/modules/selected-calendars/selected-calendars.repository";
|
||||
import { SelectedCalendarsService } from "@/modules/selected-calendars/services/selected-calendars.service";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@@ -17,6 +21,10 @@ import { Module } from "@nestjs/common";
|
||||
UsersRepository,
|
||||
CredentialsRepository,
|
||||
AppsRepository,
|
||||
OrganizationsMembershipService,
|
||||
OrganizationsDwdRepository,
|
||||
OrganizationsMembershipRepository,
|
||||
SelectedCalendarsService,
|
||||
],
|
||||
controllers: [SelectedCalendarsController],
|
||||
exports: [SelectedCalendarsRepository],
|
||||
|
||||
@@ -85,13 +85,19 @@ export class SelectedCalendarsRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async removeUserSelectedCalendar(userId: number, integration: string, externalId: string) {
|
||||
async removeUserSelectedCalendar(
|
||||
userId: number,
|
||||
integration: string,
|
||||
externalId: string,
|
||||
domainWideDelegationCredentialId?: string
|
||||
) {
|
||||
// Using deleteMany because userId_externalId_integration_eventTypeId is a unique constraint but with eventTypeId being nullable, causing it to be not used as a unique constraint
|
||||
const records = await this.dbWrite.prisma.selectedCalendar.findMany({
|
||||
where: {
|
||||
userId,
|
||||
externalId,
|
||||
integration,
|
||||
domainWideDelegationCredentialId,
|
||||
...ensureUserLevelWhere,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
|
||||
import { OrganizationsDwdRepository } from "@/modules/organizations/dwd/organizations-dwd.repository";
|
||||
import { OrganizationsMembershipService } from "@/modules/organizations/memberships/services/organizations-membership.service";
|
||||
import {
|
||||
SelectedCalendarsInputDto,
|
||||
SelectedCalendarsQueryParamsInputDto,
|
||||
} from "@/modules/selected-calendars/inputs/selected-calendars.input";
|
||||
import { SelectedCalendarsRepository } from "@/modules/selected-calendars/selected-calendars.repository";
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
|
||||
import { SelectedCalendarRepository } from "@calcom/platform-libraries";
|
||||
|
||||
type SelectedCalendarsInputDwd = SelectedCalendarsInputDto & { domainWideDelegationCredentialId: string };
|
||||
|
||||
@Injectable()
|
||||
export class SelectedCalendarsService {
|
||||
constructor(
|
||||
private readonly calendarsService: CalendarsService,
|
||||
private readonly selectedCalendarsRepository: SelectedCalendarsRepository,
|
||||
private readonly organizationsMembershipService: OrganizationsMembershipService,
|
||||
private readonly organizationsDwdRepository: OrganizationsDwdRepository
|
||||
) {}
|
||||
|
||||
async addSelectedCalendar(user: UserWithProfile, input: SelectedCalendarsInputDto) {
|
||||
if (input.domainWideDelegationCredentialId) {
|
||||
const dwdInput = {
|
||||
...input,
|
||||
domainWideDelegationCredentialId: input.domainWideDelegationCredentialId,
|
||||
};
|
||||
return this.addSelectedCalendarDwd(user, dwdInput);
|
||||
}
|
||||
return this.addSelectedCalendarUser(user, input);
|
||||
}
|
||||
|
||||
private async addSelectedCalendarUser(user: UserWithProfile, selectedCalendar: SelectedCalendarsInputDto) {
|
||||
const { integration, externalId, credentialId } = selectedCalendar;
|
||||
await this.calendarsService.checkCalendarCredentials(Number(credentialId), user.id);
|
||||
|
||||
const userSelectedCalendar = await this.selectedCalendarsRepository.addUserSelectedCalendar(
|
||||
user.id,
|
||||
integration,
|
||||
externalId,
|
||||
credentialId
|
||||
);
|
||||
|
||||
return userSelectedCalendar;
|
||||
}
|
||||
|
||||
private async addSelectedCalendarDwd(user: UserWithProfile, selectedCalendar: SelectedCalendarsInputDwd) {
|
||||
const isMemberOfOrganization = await this.isMemberOfDwdOrganization(
|
||||
user.id,
|
||||
selectedCalendar.domainWideDelegationCredentialId
|
||||
);
|
||||
if (!isMemberOfOrganization) {
|
||||
throw new NotFoundException("User is not a member of the organization that owns the DWD credential");
|
||||
}
|
||||
|
||||
const { integration, externalId, credentialId, domainWideDelegationCredentialId } = selectedCalendar;
|
||||
const dwdSelectedCalendar = await SelectedCalendarRepository.upsert({
|
||||
userId: user.id,
|
||||
integration,
|
||||
externalId,
|
||||
credentialId,
|
||||
domainWideDelegationCredentialId,
|
||||
eventTypeId: null,
|
||||
});
|
||||
return dwdSelectedCalendar;
|
||||
}
|
||||
|
||||
private async isMemberOfDwdOrganization(userId: number, domainWideDelegationCredentialId: string) {
|
||||
const dwd = await this.organizationsDwdRepository.findById(domainWideDelegationCredentialId);
|
||||
if (!dwd) {
|
||||
throw new NotFoundException("DWD with provided domainWideDelegationCredentialId not found");
|
||||
}
|
||||
|
||||
const isMemberOfOrganization = await this.organizationsMembershipService.getOrgMembershipByUserId(
|
||||
dwd.organizationId,
|
||||
userId
|
||||
);
|
||||
|
||||
return isMemberOfOrganization;
|
||||
}
|
||||
|
||||
async deleteSelectedCalendar(
|
||||
selectedCalendar: SelectedCalendarsQueryParamsInputDto,
|
||||
user: UserWithProfile
|
||||
) {
|
||||
const { integration, externalId, credentialId, domainWideDelegationCredentialId } = selectedCalendar;
|
||||
|
||||
if (!domainWideDelegationCredentialId) {
|
||||
await this.calendarsService.checkCalendarCredentials(Number(credentialId), user.id);
|
||||
} else {
|
||||
const isMemberOfOrganization = await this.isMemberOfDwdOrganization(
|
||||
user.id,
|
||||
domainWideDelegationCredentialId
|
||||
);
|
||||
if (!isMemberOfOrganization) {
|
||||
throw new NotFoundException("User is not a member of the organization that owns the DWD credential");
|
||||
}
|
||||
}
|
||||
|
||||
const removedCalendarEntry = await this.selectedCalendarsRepository.removeUserSelectedCalendar(
|
||||
user.id,
|
||||
integration,
|
||||
externalId,
|
||||
domainWideDelegationCredentialId
|
||||
);
|
||||
|
||||
return removedCalendarEntry;
|
||||
}
|
||||
}
|
||||
@@ -1091,6 +1091,96 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/organizations/{orgId}/delegation-credentials": {
|
||||
"post": {
|
||||
"operationId": "OrganizationsDwdController_createDwd",
|
||||
"summary": "Save delegation credentials for your organization.",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "orgId",
|
||||
"required": true,
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"type": "number"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/CreateDwdInput"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/CreateDwdOutput"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"Orgs / Delegation Credentials"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/organizations/{orgId}/delegation-credentials/{credentialId}": {
|
||||
"patch": {
|
||||
"operationId": "OrganizationsDwdController_updateDwd",
|
||||
"summary": "Update delegation credentials of your organization.",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "orgId",
|
||||
"required": true,
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "credentialId",
|
||||
"required": true,
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UpdateDwdInput"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UpdateDwdOutput"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"Orgs / Delegation Credentials"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/v2/organizations/{orgId}/teams/{teamId}/event-types": {
|
||||
"post": {
|
||||
"operationId": "OrganizationsEventTypesController_createTeamEventType",
|
||||
@@ -5819,7 +5909,7 @@
|
||||
]
|
||||
},
|
||||
"delete": {
|
||||
"operationId": "SelectedCalendarsController_removeSelectedCalendar",
|
||||
"operationId": "SelectedCalendarsController_deleteSelectedCalendar",
|
||||
"summary": "Delete a selected calendar",
|
||||
"parameters": [
|
||||
{
|
||||
@@ -5845,6 +5935,14 @@
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "domainWideDelegationCredentialId",
|
||||
"required": false,
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -7980,7 +8078,9 @@
|
||||
"example": "cal-video",
|
||||
"enum": [
|
||||
"cal-video",
|
||||
"google-meet"
|
||||
"google-meet",
|
||||
"office365-video",
|
||||
"zoom"
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -11374,6 +11474,9 @@
|
||||
},
|
||||
"credentialId": {
|
||||
"type": "number"
|
||||
},
|
||||
"domainWideDelegationCredentialId": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -15018,6 +15121,167 @@
|
||||
"data"
|
||||
]
|
||||
},
|
||||
"GoogleServiceAccountKeyInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"private_key": {
|
||||
"type": "string"
|
||||
},
|
||||
"client_email": {
|
||||
"type": "string"
|
||||
},
|
||||
"client_id": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"private_key",
|
||||
"client_email",
|
||||
"client_id"
|
||||
]
|
||||
},
|
||||
"CreateDwdInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"workspacePlatformSlug": {
|
||||
"type": "string"
|
||||
},
|
||||
"domain": {
|
||||
"type": "string"
|
||||
},
|
||||
"serviceAccountKey": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"oneOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/GoogleServiceAccountKeyInput"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/MicrosoftServiceAccountKeyInput"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"workspacePlatformSlug",
|
||||
"domain",
|
||||
"serviceAccountKey"
|
||||
]
|
||||
},
|
||||
"WorkspacePlatformDto": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"slug": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"slug"
|
||||
]
|
||||
},
|
||||
"DwdOutput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"domain": {
|
||||
"type": "string"
|
||||
},
|
||||
"organizationId": {
|
||||
"type": "number"
|
||||
},
|
||||
"workspacePlatform": {
|
||||
"$ref": "#/components/schemas/WorkspacePlatformDto"
|
||||
},
|
||||
"createdAt": {
|
||||
"format": "date-time",
|
||||
"type": "string"
|
||||
},
|
||||
"updatedAt": {
|
||||
"format": "date-time",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"enabled",
|
||||
"domain",
|
||||
"organizationId",
|
||||
"workspacePlatform",
|
||||
"createdAt",
|
||||
"updatedAt"
|
||||
]
|
||||
},
|
||||
"CreateDwdOutput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"example": "success",
|
||||
"enum": [
|
||||
"success",
|
||||
"error"
|
||||
]
|
||||
},
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/DwdOutput"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"data"
|
||||
]
|
||||
},
|
||||
"UpdateDwdInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"serviceAccountKey": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"oneOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/GoogleServiceAccountKeyInput"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/MicrosoftServiceAccountKeyInput"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"UpdateDwdOutput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"example": "success",
|
||||
"enum": [
|
||||
"success",
|
||||
"error"
|
||||
]
|
||||
},
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/DwdOutput"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"data"
|
||||
]
|
||||
},
|
||||
"CreateOrganizationInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -15619,6 +15883,10 @@
|
||||
},
|
||||
"credentialId": {
|
||||
"type": "number"
|
||||
},
|
||||
"domainWideDelegationCredentialId": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -15656,6 +15924,10 @@
|
||||
},
|
||||
"credentialId": {
|
||||
"type": "number"
|
||||
},
|
||||
"domainWideDelegationCredentialId": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -15674,6 +15946,10 @@
|
||||
"credentialId": {
|
||||
"type": "number"
|
||||
},
|
||||
"domainWideDelegationCredentialId": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"primary": {
|
||||
"$ref": "#/components/schemas/Primary"
|
||||
},
|
||||
@@ -15717,6 +15993,10 @@
|
||||
"type": "number",
|
||||
"nullable": true
|
||||
},
|
||||
"domainWideDelegationCredentialId": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
@@ -18072,6 +18352,9 @@
|
||||
"type": "string",
|
||||
"example": "https://caldav.icloud.com/26962146906/calendars/1644422A-1945-4438-BBC0-4F0Q23A57R7S/",
|
||||
"description": "Unique identifier used to represent the specfic calendar, as returned by the /calendars endpoint"
|
||||
},
|
||||
"domainWideDelegationCredentialId": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
+20
-8
@@ -109,10 +109,6 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
|
||||
name: "admin_api",
|
||||
href: "https://cal.com/docs/enterprise-features/api/api-reference/bookings#admin-access",
|
||||
},
|
||||
// {
|
||||
// name: "domain_wide_delegation",
|
||||
// href: "/settings/organizations/domain-wide-delegation",
|
||||
// },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -166,9 +162,16 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
|
||||
// The following keys are assigned to admin only
|
||||
const adminRequiredKeys = ["admin"];
|
||||
const organizationRequiredKeys = ["organization"];
|
||||
const organizationAdminKeys = ["privacy", "billing", "OAuth Clients", "SSO", "directory_sync"];
|
||||
const organizationAdminKeys = [
|
||||
"privacy",
|
||||
"billing",
|
||||
"OAuth Clients",
|
||||
"SSO",
|
||||
"directory_sync",
|
||||
"domain_wide_delegation",
|
||||
];
|
||||
|
||||
const useTabs = () => {
|
||||
const useTabs = ({ isDwdEnabled }: { isDwdEnabled: boolean }) => {
|
||||
const session = useSession();
|
||||
const { data: user } = trpc.viewer.me.useQuery({ includePasswordAdded: true });
|
||||
const orgBranding = useOrgBranding();
|
||||
@@ -199,6 +202,14 @@ const useTabs = () => {
|
||||
});
|
||||
}
|
||||
|
||||
// Add domain-wide-delegation menu item only if feature flag is enabled
|
||||
if (isDwdEnabled) {
|
||||
newArray.push({
|
||||
name: "domain_wide_delegation",
|
||||
href: "/settings/organizations/domain-wide-delegation",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
...tab,
|
||||
children: newArray,
|
||||
@@ -232,7 +243,7 @@ const useTabs = () => {
|
||||
if (isAdmin) return true;
|
||||
return !adminRequiredKeys.includes(tab.name);
|
||||
});
|
||||
}, [isAdmin, orgBranding, isOrgAdminOrOwner, user]);
|
||||
}, [isAdmin, orgBranding, isOrgAdminOrOwner, user, isDwdEnabled]);
|
||||
|
||||
return processTabsMemod;
|
||||
};
|
||||
@@ -418,7 +429,6 @@ const SettingsSidebarContainer = ({
|
||||
}: SettingsSidebarContainerProps) => {
|
||||
const searchParams = useCompatSearchParams();
|
||||
const { t } = useLocale();
|
||||
const tabsWithPermissions = useTabs();
|
||||
const [otherTeamMenuState, setOtherTeamMenuState] = useState<
|
||||
{
|
||||
teamId: number | undefined;
|
||||
@@ -430,6 +440,8 @@ const SettingsSidebarContainer = ({
|
||||
enabled: !!session.data?.user?.org && !currentOrgProp,
|
||||
});
|
||||
|
||||
const tabsWithPermissions = useTabs({ isDwdEnabled: !!_currentOrg?.features?.domainWideDelegation });
|
||||
|
||||
const { data: _otherTeams } = trpc.viewer.organizations.listOtherTeams.useQuery(undefined, {
|
||||
enabled: !!session.data?.user?.org && !otherTeamsProp,
|
||||
});
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
## Version 1.0
|
||||
### Release Plan
|
||||
1. Read the document(domain-wide-delegation.md) and acknowledge it.
|
||||
3. Deploy:
|
||||
1. Follow "Setting up Domain-Wide Delegation for Google Calendar API" in domain-wide-delegation.md to create Service Account and create a workspace.
|
||||
2. Merge PR(without Calendar Cache Support) and then deploy.
|
||||
4. Enable for i.cal.com:
|
||||
1. Disable Calendar Cache for i.cal.com
|
||||
2. Enable DWD for i.cal.com first and then test there
|
||||
3. Wait for 1-2 days and keep monitoring the errors in Sentry and Axiom.
|
||||
5. Merge & Deploy the Calendar Cache support(with DWD) PR
|
||||
1. Enable Calendar Cache back for i.cal.com
|
||||
2. Observe the errors in Sentry and Axiom.
|
||||
6. Enable for a big customer:
|
||||
1. Wait for a week and keep monitoring the errors in Sentry and Axiom.
|
||||
7. Use delegatedCredentialsFirst instead of delegatedCredentialsLast in EventManager.ts
|
||||
- Observe errors in Sentry and Axiom.
|
||||
|
||||
## Manual Testing
|
||||
- V2/V1 APIs - There could be problem if DWD credentials aren't supported there. Because as organization enables DWD and new users won't need to connect their calendars in the old way. e.g. getBusyCalendarTimes seem to be used there in V2.
|
||||
- [x] Request reshedule - cancellation of meeting in calendar verification
|
||||
- [x] Isolation of DWD credentials for different organizations
|
||||
- [x] Using same domain name for different organization isn't allowed. It is restricted during creation of DWD.
|
||||
- [x] Location Change of a booking to Google Meet(from Cal Video)
|
||||
- [x] Google Meet/Google Calendar
|
||||
- [x] Shows up installed on apps/google-meet and apps/instaled/conferencing
|
||||
- [x] Can't remove the app
|
||||
- [x] Seated Event
|
||||
- [x] Seat cancellation removes calendar invite
|
||||
- [x] Onboarding
|
||||
- [x] When DWD is not enabled, the flow works.
|
||||
- [x] When DWD is enabled, Google Calendar is pre-installed and Destination Calendar and Selected Calendar are configurable. On next step, Google Meet is pre-installed and shown at the top and could be set as default.
|
||||
- [x] User Level Selected Calendar and Destination Calendars are honored - verified through booking the user.
|
||||
- [ ] Event Type Selected Calendar and Destination Calendar
|
||||
- [ ] Dynamic Group Booking
|
||||
- [x] Owner must have verified email to enable DWD
|
||||
- [x] RR Team Event
|
||||
- [x] Booking
|
||||
- Unavailable slot isn't available for booking. Unavailable user isn't used.
|
||||
- [x] Reroute
|
||||
- [x] Reassign
|
||||
- [x] Troubleshooter
|
||||
- [x] Shows busy times from Calendar
|
||||
- [ ] Calendar Cache[TO BE TESTED LATER]
|
||||
- [ ] Event Type Selected Calendar caching test
|
||||
- [ ] User Selected Calendar caching test
|
||||
|
||||
### Important
|
||||
- **Performance**
|
||||
- There could be 100s of users in an organization with already connected calendars. Enabling DWD adds a duplicate credential(in-memory) for each of them.
|
||||
- Because a credential isn't aware of which externalIds it has access to(without connecting with Google Calendar API itself), we can't identify which credential is for which SelectedCalendar and thus we can't de-duplicate them. This has an impact on fetching the availability and thus for a team event with x participants, we could have 2x requests to Google Calendar API. Because for big value of x, user might be using routing already with team members and thus the actual value of x might be much lower. So, we could be fine. Also, we would have Calendar Cache enabled there already to reduce the requests.
|
||||
- Bugs
|
||||
- [x] For RR event, if I am able to see the slots for a blocked day in calendar(by temporarily unselecting the calendar), and then we enable the calendar back, the blocked day can be booked.
|
||||
- [x] Not using Goole Meet with Default conferencing app.
|
||||
- [x] Duplicate Calendar Events in Google Calendar when choosing non-primary calendar as destination. No idea why this is happening.
|
||||
- The issue was in getAttendees in Google CalendarService not using externalCalendarId.
|
||||
- [x] Restrict toggling based on email verified
|
||||
- [x] Duplicate Calendar connections in 'apps/installed' if a user already had connected calendar and DWD is enabled.
|
||||
- [x] Calendar Cache has credentialId column which isn't applicable for DWD(Solution: Added userId there)
|
||||
- [x] Troubleshooter
|
||||
- [x] Shows busy times from Claendar
|
||||
- [x] If a user has connected a calendar, and then DWD is enabled.
|
||||
- Tested various scenarios for it
|
||||
- [x] Inviting a new user.
|
||||
- Verified that Google Calendar is shown pre-installed.
|
||||
- How about Google Meet(which depends on Google Calendar) - Correctly shows up as installed.
|
||||
- TODO:
|
||||
- [ ] Add experimental/Beta flag in DWD
|
||||
- [ ] Consideration of multiple domains email in a single team event. We might need to consider all the member's domains in the team event when fetching availabilituy.
|
||||
- [x] Performance
|
||||
- [x] Available Slots and booking flow shouldn't slow down. Right now the querying logic is not optimized. We query per team member, we should do one query - This is fixed and took quite a refactor but it is cleaner code now.
|
||||
- [ ] Tag all DWD related logs and errors with "DWD:"
|
||||
- [x] Troubleshooter
|
||||
- [x] Google CalendarService unit tests to verify that if DWD credential is provided it uses impersonation to access API otherwise it uses regular user credential API.
|
||||
- [x] setDestinationCalendar.handler.ts tests to verify that when DWD is enabled it still correctly sets the destination calendar.
|
||||
- [x] getConnectedDestinationCalendars tests.
|
||||
- [x] Creating DWD shouldn't immediately enable it. Enabling has separate check to confirm if it is actually configured in google workspace
|
||||
- [x] Added check to avoid adding same domain for a workspace platform in another organization if it is already enabled in some other organization
|
||||
- [x] Don't show dwd in menu for non-org-admin users - It errors with something_went_wrong right now
|
||||
- [x] Don't allow disabled platform to be selected in the UI for creation.
|
||||
- We have disabled coming the disabled platform to be coming into the list that effectively disables edit of existing dwd and creation of new dwd for that platform.
|
||||
- [x] Where should we show the user the client ID to enable domain wide delegation?
|
||||
- [x] It must be shown to the organization owner/admin only
|
||||
- [x] There could be multiple checkboxes per domain to enable domain wide delegation for a domain
|
||||
- [x] Which domain to allow
|
||||
- Any domain can be added by a user
|
||||
- [x] Support multiple domains in DomainWideDelegation schema for an organization
|
||||
- [x] Use the domain as well to identify if the domain wide delegation is enabled
|
||||
- [x] Before enabling Domain-wide delegation, there should be a check to ensure that the clientID has been added to the Workspace Platform
|
||||
- [x] We should allow setting default conferencing app during onboarding
|
||||
|
||||
### Follow-up release
|
||||
- [ ] Confirmation for DwD toggling off
|
||||
- [ ] Confirmation for DwD deletion - Deletion isn't there at the moment.
|
||||
- [ ] Make Google Meet "show up" as default conferencing app when DWD for Google is enabled.
|
||||
- [ ] Profile pic from Google with DWD might not be working - Fix it.
|
||||
|
||||
### Security
|
||||
- [x] We don't let any one user see the added service account key from UI.
|
||||
- [ ] We intend to implement Workload Identity Federation in the future.
|
||||
|
||||
### Documentation
|
||||
- After enabling domain-wide delegation, the credential is shown pre-installed and the connection can't be removed(or the app can't be uninstalled by user)
|
||||
- Steps
|
||||
- App admin will first create a Workspace Platform and then organization owner/admin can enable domain-wide delegation for a domain
|
||||
- As soon as domain-wide delegation is created, it would start taking preference over the personal credentials of the organization members and it would be used for that.
|
||||
|
||||
Version-2.0
|
||||
- Workload Identity Federation to ensure that the service account key is never stored in DB.
|
||||
|
||||
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
## Setting up Domain-Wide Delegation for Google Calendar API
|
||||
|
||||
Step 1: Create a Google Cloud Project
|
||||
|
||||
Before you can create a service account, you'll need to set up a Google Cloud project.
|
||||
|
||||
1. Create a Google Cloud Project:
|
||||
- Go to the Google Cloud Console
|
||||
- Select Create Project
|
||||
- Give your project a name and select your billing account (if applicable)
|
||||
- Click Create
|
||||
2. Enable the Google Calendar API:
|
||||
1. Go to the Google Cloud Console
|
||||
2. Select API & Services → Library
|
||||
3. Search for "Google Calendar API"
|
||||
4. Click Enable
|
||||
|
||||
Step 2: Create a Service Account
|
||||
|
||||
A service account is needed to act on behalf of users
|
||||
|
||||
1. Navigate to the Service Accounts page:
|
||||
- In the Google Cloud Console, go to IAM & Admin → Service Accounts
|
||||
2. Create a New Service Account:
|
||||
- Click on Create Service Account
|
||||
- Give your service account a name and description
|
||||
- Click Create and Continue
|
||||
|
||||
Step 3: To Be taken by Cal.com instance admin:
|
||||
- Create a Workspace Platform with slug="google". Slug has to be exactly this. This is how we know we need to use Google Calendar and Google Meet.
|
||||
|
||||
Last Step (To Be Taken By Cal.com organization Owner/Admin): Assign Specific API Permissions via OAuth Scopes:
|
||||
- Create DWD with workspace platform "google"
|
||||
- User must be a member of the Google Workspace to be able to enable DWD as there is a validation if the user's calendar can be accessed through the service account
|
||||
- Get the Client ID from there
|
||||
- Go to your Google Admin Console (admin-google-com)
|
||||
- Navigate to Security → Access and Data Controls -> API controls -> Manage Domain-Wide Delegation
|
||||
- Here, you'll authorize the Client ID(Unique ID) to access the Google Calendar API
|
||||
- Add the necessary API scopes for Google Calendar(Full access to Google Calendar)
|
||||
https://www.googleapis.com/auth/calendar
|
||||
|
||||
|
||||
## Onboarding Improvement
|
||||
- Just adding a member to the organization would do the following:
|
||||
- Member to receive events in their calendar, even if they don't login to their account and complete the onboarding process.
|
||||
- The booking location would be Google Meet, even if the user hasn't set it as default(Though Cal Video would show up as default, but we still use Google Meet in this case. We will fix it later.)
|
||||
- It would still not use their calendar for conflict checking, but user can complete the onboarding(just select one calendar there for conflict checking)
|
||||
- Onboarding process: Google Calendar is pre-installed for any new member of the organization(assuming the user has an email of the DWD domain) and Destination Calendar and Selected Calendar are configurable. On next step, Google Meet is pre-installed and shown at the top and could be set as default.
|
||||
|
||||
## Restrictions after enabling DWD
|
||||
- Enabling DWD for a particular workspace in Cal.com(only google supported at the moment) disables the user from disconnecting that credential.
|
||||
|
||||
## Who can create DWD and enable it?
|
||||
- Only the owner/admin of the organization can create DWD
|
||||
- Only the owner/admin of the organization can enable the created DWD. Following additional requirements are there:
|
||||
- The client ID must be added to the Google Admin Console
|
||||
- The user's email must be a member of the Google Workspace
|
||||
- The user's email must be verified.
|
||||
|
||||
## Disabling DWD
|
||||
- Disabling DWD maintains the user's preferences in terms of SelectedCalendars and DestinationCalendar.
|
||||
|
||||
## Developer Notes
|
||||
### Terminology
|
||||
- DWD Credential: A DWD service account key along with user's email becomes the DWD Credential which is an alternative to regular Credential in DB.
|
||||
- DWD: Domain Wide Delegation
|
||||
- non-dwd credential: Regular credentials that are stored in Credentials table
|
||||
|
||||
### How DWD works
|
||||
- We use the Cal.com user's email to impersonate that user using DWD Credential(which is just a service account key at the moment)
|
||||
- That gives us read/write permission to get availability of the user and create new events in their calendar.
|
||||
|
||||
### What is a DWD Credential?
|
||||
- A DWD service account key along with user's email becomes the DWD Credential which is an alternative to regular Credential in DB.
|
||||
- DWD doesn't completely replace the regular credentials. DWD Credential gives access to the cal.com user's email in Google Calendar. So, if the user needs to connect to some other email's calendar, we need to use the regular credentials.
|
||||
|
||||
### Important Points
|
||||
- No Credential table entry is created when enabling DWD. The workspace platform's related apps will be considered as "installed" for the users with email matching dwd domain. An in-memory credential like object is created for this purpose. It allows avoiding creation of thousands of records for all the members of the organization when dwd is enabled.
|
||||
- DWD Credential is applicable to Users only.
|
||||
- For team, we don't use dwd credential as you can impersonate a user and not team through Dwd credential. Currently supported apps(Google Calendar and Google Meet) don't support team installation, so we could simply allow enabling DWD without any issues.
|
||||
- Disabling a workspace platform stops it from being used for any new organizations and also disables any DWD using the workspace platform from being edited.
|
||||
- It still all existing DWDs to keep on working
|
||||
- Adding any number of DWDs for a particular workspace always gives the same Client ID as DWD uses the workspace's default Service Account.
|
||||
- We should disable DWD and not delete it when we want to stop using it temporarily. Deleting DWD also removes all the seletedCalendar entries connected to it.
|
||||
|
||||
### How apps/installed loads the credentials
|
||||
1. Identify the logged in user's email
|
||||
2. Identify the domainWideDelegations for that email's domain
|
||||
3. Build in-memory credentials for the domainWideDelegations and use them along with the actual credentials(that user might have connected) of the user
|
||||
4. We don't show the non-dwd connected calendar(if there is a corresponding dwd connected calendar). Though we use the non-dwd credentials to identify the selected calendars, for the dwd connected calendar.
|
||||
|
||||
### Impact on existing users booking flow
|
||||
- There should be no impact on availability on enabling DWD because we keep on using the existing credentials along with new DWD credential.
|
||||
- When booking the event, we sort the credentials with DWD credentials last, so there should be no impact on creating calendar events.
|
||||
- NOTE: We will followup with sorting the credentials with DWD credentials first in a followup PR(They are preferred because they don't expire)
|
||||
|
||||
### Impact on APIs - [ To Verify ]
|
||||
- We don't support DWD through APIs yet. So, all existing APIs would continue to work with non-dwd credentials only.
|
||||
|
||||
### Notes when testing locally
|
||||
- You need to enable the feature through feature flag.
|
||||
- You could use Acme org and login as owner1-acme@example.com
|
||||
- Make sure to change the email of the user above to your workspace owner's email(other member's email might also work). This is necessary otherwise you won't be able to enable DWD for the organization.
|
||||
- Note: After changing the email, you would have to logout and login again as required by NextAuth
|
||||
@@ -17,6 +17,7 @@ const selectedCalendarSelectSchema = z.object({
|
||||
integration: z.string(),
|
||||
externalId: z.string(),
|
||||
credentialId: z.coerce.number(),
|
||||
domainWideDelegationCredentialId: z.string().nullish().default(null),
|
||||
eventTypeId: z.coerce.number().nullish(),
|
||||
});
|
||||
|
||||
@@ -62,14 +63,17 @@ async function getHandler() {
|
||||
|
||||
async function postHandler(req: NextRequest) {
|
||||
const user = await authMiddleware();
|
||||
|
||||
const body = await req.json();
|
||||
const { integration, externalId, credentialId, eventTypeId } = selectedCalendarSelectSchema.parse(body);
|
||||
const { integration, externalId, credentialId, eventTypeId, domainWideDelegationCredentialId } =
|
||||
selectedCalendarSelectSchema.parse(body);
|
||||
|
||||
await SelectedCalendarRepository.upsert({
|
||||
userId: user.id,
|
||||
integration,
|
||||
externalId,
|
||||
credentialId,
|
||||
domainWideDelegationCredentialId,
|
||||
eventTypeId: eventTypeId ?? null,
|
||||
});
|
||||
|
||||
|
||||
@@ -80,12 +80,14 @@ export const AppPage = ({
|
||||
const searchParams = useCompatSearchParams();
|
||||
|
||||
const hasDescriptionItems = descriptionItems && descriptionItems.length > 0;
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const mutation = useAddAppMutation(null, {
|
||||
onSuccess: (data) => {
|
||||
onSuccess: async (data) => {
|
||||
if (data?.setupPending) return;
|
||||
setIsLoading(false);
|
||||
showToast(t("app_successfully_installed"), "success");
|
||||
showToast(data?.message || t("app_successfully_installed"), "success");
|
||||
await utils.viewer.appCredentialsByType.invalidate({ appType: type });
|
||||
},
|
||||
onError: (error) => {
|
||||
if (error instanceof Error) showToast(error.message || t("app_could_not_be_installed"), "error");
|
||||
@@ -170,6 +172,7 @@ export const AppPage = ({
|
||||
|
||||
// variant not other allows, an app to be shown in calendar category without requiring an actual calendar connection e.g. vimcal
|
||||
// Such apps, can only be installed once.
|
||||
|
||||
const allowedMultipleInstalls = categories.indexOf("calendar") > -1 && variant !== "other";
|
||||
useEffect(() => {
|
||||
if (searchParams?.get("defaultInstall") === "true") {
|
||||
|
||||
@@ -36,10 +36,10 @@ export const InstallAppButtonChild = ({
|
||||
return (
|
||||
<Button
|
||||
data-testid="install-app-button"
|
||||
{...props}
|
||||
disabled={shouldDisableInstallation}
|
||||
color="primary"
|
||||
size="base"
|
||||
{...props}>
|
||||
size="base">
|
||||
{multiInstall ? t("install_another") : t("install_app")}
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -52,6 +52,15 @@ export function MultiDisconnectIntegration({ credentials, onSuccess }: Props) {
|
||||
},
|
||||
});
|
||||
|
||||
const getUserDisplayName = (user: (typeof credentials)[number]["user"]) => {
|
||||
if (!user) return null;
|
||||
// Check if 'name' property exists on user
|
||||
if ("name" in user) return user.name;
|
||||
// Otherwise use email if available
|
||||
if ("email" in user) return user.email;
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dropdown>
|
||||
@@ -73,12 +82,12 @@ export function MultiDisconnectIntegration({ credentials, onSuccess }: Props) {
|
||||
setCredentialToDelete({
|
||||
id: cred.id,
|
||||
teamId: cred.teamId,
|
||||
name: cred.team?.name || cred.user?.name || null,
|
||||
name: cred.team?.name || getUserDisplayName(cred.user) || null,
|
||||
});
|
||||
setConfirmationDialogOpen(true);
|
||||
}}>
|
||||
<div className="flex flex-col text-left">
|
||||
<span>{cred.team?.name || cred.user?.name || t("unnamed")}</span>
|
||||
<span>{cred.team?.name || getUserDisplayName(cred.user) || t("unnamed")}</span>
|
||||
</div>
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
|
||||
@@ -24,11 +24,19 @@ interface IAppConnectionItem {
|
||||
const AppConnectionItem = (props: IAppConnectionItem) => {
|
||||
const { title, logo, type, installed, isDefault, defaultInstall, slug } = props;
|
||||
const { t } = useLocale();
|
||||
const setDefaultConferencingApp = trpc.viewer.appsRouter.setDefaultConferencingApp.useMutation();
|
||||
const utils = trpc.useUtils();
|
||||
const setDefaultConferencingApp = trpc.viewer.appsRouter.setDefaultConferencingApp.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.viewer.me.invalidate();
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(t("something_went_wrong"), "error");
|
||||
console.error(error);
|
||||
},
|
||||
});
|
||||
const dependency = props.dependencyData?.find((data) => !data.installed);
|
||||
|
||||
const [isInstalling, setInstalling] = useState(false);
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
return (
|
||||
<div className="flex flex-row items-center justify-between p-5">
|
||||
@@ -37,72 +45,90 @@ const AppConnectionItem = (props: IAppConnectionItem) => {
|
||||
<p className="text-sm font-bold">{title}</p>
|
||||
{isDefault && <Badge variant="green">{t("default")}</Badge>}
|
||||
</div>
|
||||
<InstallAppButtonWithoutPlanCheck
|
||||
type={type}
|
||||
options={{
|
||||
onSuccess: () => {
|
||||
if (defaultInstall && slug) {
|
||||
setDefaultConferencingApp.mutate({ slug });
|
||||
}
|
||||
setInstalling(false);
|
||||
utils.viewer.integrations.invalidate();
|
||||
showToast(t("app_successfully_installed"), "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
if (error instanceof Error) showToast(error.message || t("app_could_not_be_installed"), "error");
|
||||
},
|
||||
}}
|
||||
render={(buttonProps) => (
|
||||
<Button
|
||||
{...buttonProps}
|
||||
color="secondary"
|
||||
disabled={installed || !!dependency}
|
||||
type="button"
|
||||
loading={isInstalling || buttonProps?.loading}
|
||||
tooltip={
|
||||
dependency ? (
|
||||
<div className="items-start space-x-2.5">
|
||||
<div className="flex items-start">
|
||||
<div>
|
||||
<Icon name="circle-alert" className="mr-2 mt-1 font-semibold" />
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-xs font-semibold">
|
||||
{t("this_app_requires_connected_account", {
|
||||
appName: title,
|
||||
dependencyName: dependency.name,
|
||||
})}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<InstallAppButtonWithoutPlanCheck
|
||||
type={type}
|
||||
options={{
|
||||
onSuccess: () => {
|
||||
if (defaultInstall && slug) {
|
||||
setDefaultConferencingApp.mutate({ slug });
|
||||
}
|
||||
setInstalling(false);
|
||||
utils.viewer.integrations.invalidate();
|
||||
showToast(t("app_successfully_installed"), "success");
|
||||
},
|
||||
onError: (error) => {
|
||||
if (error instanceof Error)
|
||||
showToast(error.message || t("app_could_not_be_installed"), "error");
|
||||
},
|
||||
}}
|
||||
render={(buttonProps) => (
|
||||
<Button
|
||||
{...buttonProps}
|
||||
color="secondary"
|
||||
disabled={installed || !!dependency}
|
||||
type="button"
|
||||
loading={isInstalling || buttonProps?.loading}
|
||||
tooltip={
|
||||
dependency ? (
|
||||
<div className="items-start space-x-2.5">
|
||||
<div className="flex items-start">
|
||||
<div>
|
||||
<Icon name="circle-alert" className="mr-2 mt-1 font-semibold" />
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-xs font-semibold">
|
||||
{t("this_app_requires_connected_account", {
|
||||
appName: title,
|
||||
dependencyName: dependency.name,
|
||||
})}
|
||||
</span>
|
||||
|
||||
<div>
|
||||
<>
|
||||
<Link
|
||||
href={`${WEBAPP_URL}/getting-started/connected-calendar`}
|
||||
className="flex items-center text-xs underline">
|
||||
<span className="mr-1">
|
||||
{t("connect_app", { dependencyName: dependency.name })}
|
||||
</span>
|
||||
<Icon name="arrow-right" className="inline-block h-3 w-3" />
|
||||
</Link>
|
||||
</>
|
||||
<div>
|
||||
<>
|
||||
<Link
|
||||
href={`${WEBAPP_URL}/getting-started/connected-calendar`}
|
||||
className="flex items-center text-xs underline">
|
||||
<span className="mr-1">
|
||||
{t("connect_app", { dependencyName: dependency.name })}
|
||||
</span>
|
||||
<Icon name="arrow-right" className="inline-block h-3 w-3" />
|
||||
</Link>
|
||||
</>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
onClick={(event) => {
|
||||
// Save cookie key to return url step
|
||||
document.cookie = `return-to=${window.location.href};path=/;max-age=3600;SameSite=Lax`;
|
||||
buttonProps && buttonProps.onClick && buttonProps?.onClick(event);
|
||||
setInstalling(true);
|
||||
) : undefined
|
||||
}
|
||||
onClick={(event) => {
|
||||
// Save cookie key to return url step
|
||||
document.cookie = `return-to=${window.location.href};path=/;max-age=3600;SameSite=Lax`;
|
||||
buttonProps && buttonProps.onClick && buttonProps?.onClick(event);
|
||||
setInstalling(true);
|
||||
}}>
|
||||
{installed ? t("installed") : t("connect")}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
{/* It is possible that app is already installed here during onboarding due to Domain Wide Delegation enabled at organization level. We allow the user to set it as default */}
|
||||
{installed && !isDefault && (
|
||||
<Button
|
||||
color="secondary"
|
||||
className="ml-2"
|
||||
type="button"
|
||||
loading={setDefaultConferencingApp.isPending}
|
||||
onClick={() => {
|
||||
if (slug) {
|
||||
setDefaultConferencingApp.mutate({ slug });
|
||||
}
|
||||
}}>
|
||||
{installed ? t("installed") : t("connect")}
|
||||
{t("set_as_default")}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ interface IConnectedCalendarItem {
|
||||
userId?: number | undefined;
|
||||
integration?: string | undefined;
|
||||
externalId: string;
|
||||
domainWideDelegationCredentialId: string | null;
|
||||
}[];
|
||||
}
|
||||
|
||||
@@ -61,6 +62,7 @@ const ConnectedCalendarItem = (prop: IConnectedCalendarItem) => {
|
||||
type={integrationType}
|
||||
isChecked={calendar.isSelected}
|
||||
isLastItemInList={i === calendars.length - 1}
|
||||
domainWideDelegationCredentialId={calendar.domainWideDelegationCredentialId}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -17,7 +17,16 @@ const ConnectedVideoStep = (props: ConnectedAppStepProps) => {
|
||||
const { data: queryConnectedVideoApps, isPending } = trpc.viewer.integrations.useQuery({
|
||||
variant: "conferencing",
|
||||
onlyInstalled: false,
|
||||
|
||||
/**
|
||||
* Both props together sort by most popular first, then by installed first.
|
||||
* So, installed apps are always shown at the top, followed by remaining apps sorted by descending popularity.
|
||||
*
|
||||
* This is done because there could be not so popular app already installed by the admin(e.g. through Domain-Wide Delegation)
|
||||
* and we want to show it at the top so that user can set it as default if he wants to.
|
||||
*/
|
||||
sortByMostPopular: true,
|
||||
sortByInstalledFirst: true,
|
||||
});
|
||||
const { data } = useMeQuery();
|
||||
const { t } = useLocale();
|
||||
|
||||
@@ -4,8 +4,8 @@ import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
|
||||
import handleNewBooking from "@calcom/features/bookings/lib/handleNewBooking";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import getIP from "@calcom/lib/getIP";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import { checkCfTurnstileToken } from "@calcom/lib/server/checkCfTurnstileToken";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import { CreationSource } from "@calcom/prisma/enums";
|
||||
|
||||
async function handler(req: NextApiRequest & { userId?: number }) {
|
||||
|
||||
@@ -5,8 +5,8 @@ import { handleNewRecurringBooking } from "@calcom/features/bookings/lib/handleN
|
||||
import type { BookingResponse } from "@calcom/features/bookings/types";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import getIP from "@calcom/lib/getIP";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import { checkCfTurnstileToken } from "@calcom/lib/server/checkCfTurnstileToken";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
|
||||
// @TODO: Didn't look at the contents of this function in order to not break old booking page.
|
||||
|
||||
|
||||
@@ -2743,6 +2743,26 @@
|
||||
"limit_team_booking_frequency_description": "Limit how many times members can be booked across all team event types",
|
||||
"booking_limits_updated_successfully": "Booking limits updated successfully",
|
||||
"you_are_unauthorized_to_make_this_change_to_the_booking": "You are unauthorized to make this change to the booking",
|
||||
"add_client_id_in_google_workspace_with_below_scope": "Add this Client Id in Google Workspace with the scope below",
|
||||
"domain_wide_delegation": "Domain-wide delegation",
|
||||
"domain_wide_delegation_enabled": "Domain-wide delegation enabled",
|
||||
"domain_wide_delegation_disabled": "Domain-wide delegation disabled",
|
||||
"domain_wide_delegation_description": "Domain-wide delegation allows you to manage access to Google Workspace calendars for your organization.",
|
||||
"add_domain_wide_delegation": "Add domain-wide delegation",
|
||||
"edit_domain_wide_delegation": "Edit domain-wide delegation",
|
||||
"domain": "Domain",
|
||||
"no_workspace_platforms": "No workspace platforms",
|
||||
"workspace_platform": "Workspace platform",
|
||||
"workspace_platforms": "Workspace platforms",
|
||||
"workspace_platforms_description": "Manage workspace platforms that can be used for domain-wide delegation",
|
||||
"edit_workspace_platform": "Edit workspace platform",
|
||||
"edit_service_account": "Edit service account",
|
||||
"add_workspace_platform": "Add workspace platform",
|
||||
"slug": "Slug",
|
||||
"service_account_key": "Service account key JSON",
|
||||
"edit_service_account_key": "Edit service account key JSON",
|
||||
"domain_wide_delegation_restricts_adding_more_than_one_installation": "Domain-wide delegation restricts adding more than one installation",
|
||||
"app_successfully_installed_and_is_using_delegated_credentials": "App successfully installed and is using delegated credentials",
|
||||
"matching_members": "Matching members",
|
||||
"x_matching_members": "{{x}} matching members",
|
||||
"matching_members_queue_using_attribute_weights": "Matching members queue (using attribute weights)",
|
||||
@@ -2953,6 +2973,7 @@
|
||||
"k_bar_ai_error": "An unexpected error occured. Please try again later",
|
||||
"select_oAuth_client": "Select Oauth Client",
|
||||
"on_every_instance": "On every instance",
|
||||
"domain_wide_delegation_feature_not_enabled": "Domain-wide delegation feature is not enabled for your organization",
|
||||
"internal_booking_note": "Internal Note",
|
||||
"internal_note_cancellation_reason": "Reason shared with customer (optional)",
|
||||
"internal_booking_note_description": "This note will be visible to only members of your team",
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user