* 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]>
329 lines
10 KiB
TypeScript
329 lines
10 KiB
TypeScript
/**
|
|
* This route is used only by "Test Preview" button and Virtual Queues
|
|
* Also, it is applicable only for sub-teams. Regular teams and user Routing Forms don't hit this endpoint.
|
|
* Live mode uses findTeamMembersMatchingAttributeLogicOfRoute fn directly
|
|
*/
|
|
import type { App_RoutingForms_Form } from "@prisma/client";
|
|
import type { ServerResponse } from "http";
|
|
import type { NextApiResponse } from "next";
|
|
|
|
import { enrichFormWithMigrationData } from "@calcom/app-store/routing-forms/enrichFormWithMigrationData";
|
|
import { getUrlSearchParamsToForwardForTestPreview } from "@calcom/app-store/routing-forms/pages/routing-link/getUrlSearchParamsToForward";
|
|
import { enrichHostsWithDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
|
|
import { entityPrismaWhereClause } from "@calcom/lib/entityPermissionUtils";
|
|
import { fromEntriesWithDuplicateKeys } from "@calcom/lib/fromEntriesWithDuplicateKeys";
|
|
import { findTeamMembersMatchingAttributeLogic } from "@calcom/lib/raqb/findTeamMembersMatchingAttributeLogic";
|
|
import { getOrderedListOfLuckyUsers } from "@calcom/lib/server/getLuckyUser";
|
|
import { EventTypeRepository } from "@calcom/lib/server/repository/eventType";
|
|
import { UserRepository } from "@calcom/lib/server/repository/user";
|
|
import type { PrismaClient } from "@calcom/prisma";
|
|
import { getAbsoluteEventTypeRedirectUrl } from "@calcom/routing-forms/getEventTypeRedirectUrl";
|
|
import { getSerializableForm } from "@calcom/routing-forms/lib/getSerializableForm";
|
|
import { getServerTimingHeader } from "@calcom/routing-forms/lib/getServerTimingHeader";
|
|
import isRouter from "@calcom/routing-forms/lib/isRouter";
|
|
import { RouteActionType } from "@calcom/routing-forms/zod";
|
|
import { TRPCError } from "@calcom/trpc/server";
|
|
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
|
|
|
import type { TFindTeamMembersMatchingAttributeLogicOfRouteInputSchema } from "./findTeamMembersMatchingAttributeLogicOfRoute.schema";
|
|
|
|
interface FindTeamMembersMatchingAttributeLogicOfRouteHandlerOptions {
|
|
ctx: {
|
|
prisma: PrismaClient;
|
|
user: NonNullable<TrpcSessionUser>;
|
|
res: ServerResponse | NextApiResponse | undefined;
|
|
};
|
|
input: TFindTeamMembersMatchingAttributeLogicOfRouteInputSchema;
|
|
}
|
|
|
|
async function getEnrichedSerializableForm<
|
|
TForm extends App_RoutingForms_Form & {
|
|
user: {
|
|
id: number;
|
|
username: string | null;
|
|
movedToProfileId: number | null;
|
|
};
|
|
team: {
|
|
parent: {
|
|
slug: string | null;
|
|
} | null;
|
|
metadata: unknown;
|
|
} | null;
|
|
}
|
|
>(form: TForm) {
|
|
const formWithUserInfoProfile = {
|
|
...form,
|
|
user: await UserRepository.enrichUserWithItsProfile({ user: form.user }),
|
|
};
|
|
|
|
const serializableForm = await getSerializableForm({
|
|
form: enrichFormWithMigrationData(formWithUserInfoProfile),
|
|
});
|
|
|
|
return serializableForm;
|
|
}
|
|
|
|
export const findTeamMembersMatchingAttributeLogicOfRouteHandler = async ({
|
|
ctx,
|
|
input,
|
|
}: FindTeamMembersMatchingAttributeLogicOfRouteHandlerOptions) => {
|
|
const { prisma, user } = ctx;
|
|
const { getTeamMemberEmailForResponseOrContactUsingUrlQuery } = await import(
|
|
"@calcom/lib/server/getTeamMemberEmailFromCrm"
|
|
);
|
|
|
|
const { formId, response, route, isPreview, _enablePerf, _concurrency } = input;
|
|
|
|
const form = await prisma.app_RoutingForms_Form.findFirst({
|
|
where: {
|
|
id: formId,
|
|
...entityPrismaWhereClause({ userId: user.id }),
|
|
},
|
|
include: {
|
|
team: {
|
|
select: {
|
|
parentId: true,
|
|
parent: {
|
|
select: {
|
|
slug: true,
|
|
},
|
|
},
|
|
metadata: true,
|
|
},
|
|
},
|
|
user: {
|
|
select: {
|
|
id: true,
|
|
username: true,
|
|
movedToProfileId: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!form) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "Form not found",
|
|
});
|
|
}
|
|
|
|
if (!form.teamId) {
|
|
throw new TRPCError({
|
|
code: "BAD_REQUEST",
|
|
message: "This form is not associated with a team",
|
|
});
|
|
}
|
|
|
|
const formOrgId = form.team?.parentId;
|
|
if (!formOrgId) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "This form is not associated with an organization",
|
|
});
|
|
}
|
|
|
|
const beforeEnrichedForm = performance.now();
|
|
const serializableForm = await getEnrichedSerializableForm(form);
|
|
const afterEnrichedForm = performance.now();
|
|
const timeTakenToEnrichForm = afterEnrichedForm - beforeEnrichedForm;
|
|
|
|
if (!serializableForm.fields) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "Form fields not found",
|
|
});
|
|
}
|
|
|
|
if (!route) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "Route not found",
|
|
});
|
|
}
|
|
|
|
if (isRouter(route)) {
|
|
throw new TRPCError({
|
|
code: "BAD_REQUEST",
|
|
message: "This route is a global router which is not supported",
|
|
});
|
|
}
|
|
|
|
if (route.action.type !== RouteActionType.EventTypeRedirectUrl) {
|
|
return {
|
|
troubleshooter: null,
|
|
result: null,
|
|
contactOwnerEmail: null,
|
|
checkedFallback: false,
|
|
mainWarnings: [],
|
|
fallbackWarnings: [],
|
|
eventTypeRedirectUrl: null,
|
|
isUsingAttributeWeights: false,
|
|
};
|
|
}
|
|
|
|
const eventTypeId = route.action.eventTypeId;
|
|
// e.g. /team/abc/team-event-type
|
|
const eventTypeRedirectPath = route.action.value;
|
|
|
|
if (!eventTypeId) {
|
|
// If it ever happens, should automatically be fixed by saving the form again from route-builder.
|
|
// Legacy route actions do not have eventTypeId.
|
|
throw new TRPCError({
|
|
code: "BAD_REQUEST",
|
|
message: "The route action is missing eventTypeId.",
|
|
});
|
|
}
|
|
|
|
const eventType = await EventTypeRepository.findByIdIncludeHostsAndTeam({ id: eventTypeId });
|
|
|
|
if (!eventType) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "Event type not found",
|
|
});
|
|
}
|
|
|
|
const {
|
|
teamMembersMatchingAttributeLogic: matchingTeamMembersWithResult,
|
|
timeTaken: teamMembersMatchingAttributeLogicTimeTaken,
|
|
troubleshooter,
|
|
checkedFallback,
|
|
mainAttributeLogicBuildingWarnings: mainWarnings,
|
|
fallbackAttributeLogicBuildingWarnings: fallbackWarnings,
|
|
} = await findTeamMembersMatchingAttributeLogic(
|
|
{
|
|
dynamicFieldValueOperands: {
|
|
response,
|
|
fields: serializableForm.fields || [],
|
|
},
|
|
attributesQueryValue: route.attributesQueryValue ?? null,
|
|
fallbackAttributesQueryValue: route.fallbackAttributesQueryValue ?? null,
|
|
teamId: form.teamId,
|
|
orgId: formOrgId,
|
|
isPreview: !!isPreview,
|
|
},
|
|
{
|
|
enablePerf: _enablePerf,
|
|
// Reuse same flag for enabling troubleshooter. We would normally use them together
|
|
enableTroubleshooter: _enablePerf,
|
|
concurrency: _concurrency,
|
|
}
|
|
);
|
|
|
|
const urlSearchParamsToForward = getUrlSearchParamsToForwardForTestPreview({
|
|
formResponse: response,
|
|
fields: serializableForm.fields,
|
|
attributeRoutingConfig: route.attributeRoutingConfig ?? null,
|
|
teamMembersMatchingAttributeLogic: matchingTeamMembersWithResult
|
|
? matchingTeamMembersWithResult.map((member) => member.userId)
|
|
: [],
|
|
});
|
|
|
|
const eventTypeRedirectUrl = getAbsoluteEventTypeRedirectUrl({
|
|
eventTypeRedirectUrl: eventTypeRedirectPath,
|
|
form: serializableForm,
|
|
allURLSearchParams: urlSearchParamsToForward,
|
|
});
|
|
|
|
const timeBeforeCrm = performance.now();
|
|
const { email: contactOwnerEmail } = await getTeamMemberEmailForResponseOrContactUsingUrlQuery({
|
|
query: fromEntriesWithDuplicateKeys(urlSearchParamsToForward.entries()),
|
|
eventData: eventType,
|
|
chosenRoute: route,
|
|
});
|
|
const timeAfterCrm = performance.now();
|
|
|
|
const timeTaken: Record<string, number | null | undefined> = {
|
|
...teamMembersMatchingAttributeLogicTimeTaken,
|
|
crm: timeAfterCrm - timeBeforeCrm,
|
|
enrichForm: timeTakenToEnrichForm,
|
|
};
|
|
|
|
if (!matchingTeamMembersWithResult) {
|
|
return {
|
|
contactOwnerEmail,
|
|
troubleshooter,
|
|
checkedFallback,
|
|
mainWarnings,
|
|
fallbackWarnings,
|
|
eventTypeRedirectUrl,
|
|
isUsingAttributeWeights: false,
|
|
result: null,
|
|
};
|
|
}
|
|
|
|
const matchingTeamMembersIds = matchingTeamMembersWithResult.map((member) => member.userId);
|
|
const matchingTeamMembers = await UserRepository.findByIds({ ids: matchingTeamMembersIds });
|
|
const matchingHosts = await enrichHostsWithDwdCredentials({
|
|
orgId: formOrgId,
|
|
hosts: eventType.hosts.filter((host) => matchingTeamMembersIds.includes(host.user.id)),
|
|
});
|
|
|
|
if (matchingTeamMembers.length !== matchingHosts.length) {
|
|
throw new TRPCError({
|
|
code: "INTERNAL_SERVER_ERROR",
|
|
message: "Looks like not all matching team members are assigned to the event",
|
|
});
|
|
}
|
|
|
|
const timeBeforeGetOrderedLuckyUsers = performance.now();
|
|
const {
|
|
users: orderedLuckyUsers,
|
|
perUserData,
|
|
isUsingAttributeWeights,
|
|
} = matchingTeamMembers.length
|
|
? await getOrderedListOfLuckyUsers({
|
|
// Assuming all are available
|
|
availableUsers: [
|
|
{
|
|
...matchingHosts[0].user,
|
|
weight: matchingHosts[0].weight,
|
|
priority: matchingHosts[0].priority,
|
|
},
|
|
...matchingHosts.slice(1).map((host) => ({
|
|
...host.user,
|
|
weight: host.weight,
|
|
priority: host.priority,
|
|
})),
|
|
],
|
|
eventType,
|
|
allRRHosts: matchingHosts,
|
|
routingFormResponse: {
|
|
response,
|
|
form,
|
|
chosenRouteId: route.id,
|
|
},
|
|
})
|
|
: { users: [], perUserData: null, isUsingAttributeWeights: false };
|
|
const timeAfterGetOrderedLuckyUsers = performance.now();
|
|
timeTaken.getOrderedLuckyUsers = timeAfterGetOrderedLuckyUsers - timeBeforeGetOrderedLuckyUsers;
|
|
|
|
console.log("_enablePerf, _concurrency", _enablePerf, _concurrency);
|
|
if (_enablePerf) {
|
|
const serverTimingHeader = getServerTimingHeader(timeTaken);
|
|
ctx.res?.setHeader("Server-Timing", serverTimingHeader);
|
|
console.log("Server-Timing", serverTimingHeader);
|
|
}
|
|
|
|
return {
|
|
troubleshooter,
|
|
contactOwnerEmail,
|
|
checkedFallback,
|
|
mainWarnings,
|
|
fallbackWarnings,
|
|
result: {
|
|
users: orderedLuckyUsers.map((user) => ({
|
|
id: user.id,
|
|
name: user.name,
|
|
email: user.email,
|
|
})),
|
|
perUserData,
|
|
},
|
|
isUsingAttributeWeights,
|
|
eventTypeRedirectUrl,
|
|
};
|
|
};
|
|
|
|
export default findTeamMembersMatchingAttributeLogicOfRouteHandler;
|