feat: Use RoutingTraceService to write assignment reasons (#27225)
* Add DB schema * Init zod schema * Init RoutingTrace and PendingRoutingTrace repository interfaces * Create PrismaPendingRoutingTraceRepository * Init RoutingTraceService * Create RoutingTraceService container * User routing trace service in routing * Create RoutingTraceRepository and PrismaRoutingTraceRepoistory * Add findByFormResponseId and findByQueuedFormResponseId to PendingRoutingTraceRepository * Update DI containers * RoutingTraceService create process booking method * Use pending routing trace rather than URL params * Fix schema * Fix writing assignment reason for routed booking * Remove from service * Refactor RoutingTraceService to not rely on async local storage * Pass RoutingTraceService through routing call * Add attribute-logic-evaluated to routing trace step * Add routing trace to trpc endpoint * Add CRM routing trace step * Fix extracting routing trace to assignment reason * Add back CRM params to prevent refetching * test: Add unit tests for RoutingTraceService and repositories Co-Authored-By: [email protected] <[email protected]> * test: Add missing mock for RoutingTraceService in getRoutedUrl tests Also fix pre-existing lint issues in the test file: - Add explicit types to mockForm and mockSerializableForm variables - Add explicit type to url parameter in mockContext - Replace 'as any' with 'as unknown as InstanceType<typeof UserRepository>' Co-Authored-By: [email protected] <[email protected]> * Link pending form submission to routing trace * Clean up * Add lookup field assignment reasons * Rename to PendingRoutingTrace * Add migration file * fix: Update RoutingTraceService tests to use assignmentReasonRepository mock - Add getStepsCount() method back to RoutingTraceService - Add queuedFormResponseId support to processForBooking method - Update tests to use mockAssignmentReasonRepository instead of prisma mock - Remove test for missing routingTraceRepository (all deps now required) Co-Authored-By: [email protected] <[email protected]> * fix: Remove PII (organizer email) from log payload in RoutingTraceService Addresses Cubic AI review feedback with confidence 9/10. Logging PII violates sensitive information logging rules. Co-Authored-By: unknown <> * Write field values at the time of routing * Write attributes used to route * fix: Add CHECK constraint to ensure at least one response ID is set in routing trace tables Co-Authored-By: [email protected] <[email protected]> * fix: Address PR review comments for routing trace feature - Add checkedFallback to routing trace step data (Comment 11) - Extract hardcoded domain/step strings to constants (Comment 13) - Use @default(now()) for createdAt in PendingRoutingTrace and RoutingTrace (Comment 15) - Add DEFAULT CURRENT_TIMESTAMP to migration for createdAt fields Co-Authored-By: [email protected] <[email protected]> * fix: Use UTC-safe timezone expression for createdAt defaults in routing trace tables Addresses Cubic AI review feedback (confidence 9/10) to prevent timezone issues by using dbgenerated("timezone('UTC', now())") instead of bare now() for the createdAt fields in PendingRoutingTrace and RoutingTrace models. Co-Authored-By: unknown <> * fix: Align migration SQL with Prisma's expected timezone syntax Use 'UTC'::text cast in timezone() function to match Prisma's generated SQL. Co-Authored-By: unknown <> * fix: Revert migration SQL to match Prisma schema timezone syntax Remove ::text cast from timezone() function to match what Prisma generates from the schema definition. Co-Authored-By: unknown <> * fix: Use explicit ::text cast in timezone() for PostgreSQL compatibility PostgreSQL normalizes timezone('UTC', now()) to timezone('UTC'::text, now()) internally. Update both schema and migration to use the explicit cast to ensure they match and pass the migration check. Co-Authored-By: unknown <> * fix: Use CURRENT_TIMESTAMP for createdAt defaults (standard Cal.com pattern) Co-Authored-By: [email protected] <[email protected]> * fix: Use @default(now()) for createdAt in routing trace tables to match migration Co-Authored-By: [email protected] <[email protected]> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Pedro Castro <[email protected]>
This commit is contained in:
24 files changed
+2152
-71
No files matched your search
@@ -6,6 +6,11 @@ import { Utils as QbUtils } from "react-awesome-query-builder/lib";
|
||||
import { acrossQueryValueCompatiblity, raqbQueryValueUtils } from "@calcom/app-store/_utils/raqb/raqbUtils";
|
||||
import type { Attribute } from "@calcom/app-store/routing-forms/types/types";
|
||||
import { getAttributesAssignmentData } from "@calcom/features/attributes/lib/getAttributes";
|
||||
import type { RoutingTraceService } from "@calcom/features/routing-trace/services/RoutingTraceService";
|
||||
import {
|
||||
ROUTING_TRACE_DOMAINS,
|
||||
ROUTING_TRACE_STEPS,
|
||||
} from "@calcom/features/routing-trace/services/RoutingTraceService";
|
||||
import { RaqbLogicResult } from "@calcom/lib/raqb/evaluateRaqbLogic";
|
||||
import jsonLogic from "@calcom/lib/raqb/jsonLogic";
|
||||
import type { dynamicFieldValueOperands, AttributesQueryValue } from "@calcom/lib/raqb/types";
|
||||
@@ -130,6 +135,136 @@ function buildTroubleshooterData({ type, data }: { type: TroubleshooterCase; dat
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a string is a field template placeholder (e.g., "{field:uuid}")
|
||||
*/
|
||||
function isFieldTemplate(str: string): boolean {
|
||||
const trimmedStr = str.trim();
|
||||
return trimmedStr.startsWith("{field:") && trimmedStr.endsWith("}");
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts field ID from a field template string
|
||||
*/
|
||||
function extractFieldIdFromTemplate(template: string): string | null {
|
||||
const trimmedTemplate = template.trim();
|
||||
if (!isFieldTemplate(trimmedTemplate)) return null;
|
||||
return trimmedTemplate.slice(7, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a field template to its actual value from the form response
|
||||
*/
|
||||
function resolveFieldTemplateValue(
|
||||
value: string,
|
||||
dynamicFieldValueOperands?: dynamicFieldValueOperands
|
||||
): string {
|
||||
if (!isFieldTemplate(value) || !dynamicFieldValueOperands) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const fieldId = extractFieldIdFromTemplate(value);
|
||||
if (!fieldId) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const { fields, response } = dynamicFieldValueOperands;
|
||||
const field = fields.find((f) => f.id === fieldId);
|
||||
|
||||
if (!field) {
|
||||
// Field definition not found - return original template
|
||||
return value;
|
||||
}
|
||||
|
||||
const fieldResponse = response[field.id];
|
||||
if (!fieldResponse) {
|
||||
// Field not in response object - return original template
|
||||
return value;
|
||||
}
|
||||
|
||||
const fieldValue = fieldResponse.value;
|
||||
if (fieldValue === null || fieldValue === undefined || fieldValue === "") {
|
||||
return "(empty)";
|
||||
}
|
||||
|
||||
if (Array.isArray(fieldValue)) {
|
||||
return fieldValue.join(", ");
|
||||
}
|
||||
|
||||
return String(fieldValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts attribute name/value pairs from a resolved attributesQueryValue.
|
||||
* This is used to build the assignment reason string.
|
||||
*/
|
||||
function extractAttributeRoutingDetails({
|
||||
resolvedAttributesQueryValue,
|
||||
attributesOfTheOrg,
|
||||
dynamicFieldValueOperands,
|
||||
}: {
|
||||
resolvedAttributesQueryValue: AttributesQueryValue | null;
|
||||
attributesOfTheOrg: Attribute[];
|
||||
dynamicFieldValueOperands?: dynamicFieldValueOperands;
|
||||
}): Array<{ attributeName: string; attributeValue: string }> {
|
||||
if (!resolvedAttributesQueryValue) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!raqbQueryValueUtils.isQueryValueARuleGroup(resolvedAttributesQueryValue as JsonTree)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const children1 = resolvedAttributesQueryValue.children1;
|
||||
if (!children1) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const result: Array<{ attributeName: string; attributeValue: string }> = [];
|
||||
|
||||
for (const ruleId of Object.keys(children1)) {
|
||||
const rule = children1[ruleId];
|
||||
// Check if it's a rule (has properties with field)
|
||||
if (rule.type !== "rule" || !rule.properties) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const properties = rule.properties;
|
||||
const fieldId = properties.field;
|
||||
const value = properties.value;
|
||||
|
||||
if (!fieldId || !value || value[0] === null || value[0] === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attribute = attributesOfTheOrg.find((attr) => attr.id === fieldId);
|
||||
if (!attribute) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attributeValueString = (() => {
|
||||
const firstValue = value[0];
|
||||
if (Array.isArray(firstValue)) {
|
||||
// Handle array values - resolve any field templates within
|
||||
const resolvedValues = firstValue.map((v) =>
|
||||
typeof v === "string" ? resolveFieldTemplateValue(v, dynamicFieldValueOperands) : String(v)
|
||||
);
|
||||
return resolvedValues.join(", ");
|
||||
}
|
||||
const stringValue = String(firstValue);
|
||||
// Resolve field template if present
|
||||
return resolveFieldTemplateValue(stringValue, dynamicFieldValueOperands);
|
||||
})();
|
||||
|
||||
result.push({
|
||||
attributeName: attribute.name,
|
||||
attributeValue: attributeValueString,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function getLogicResultForAllMembers(
|
||||
{
|
||||
teamMembersWithAttributeOptionValuePerAttribute,
|
||||
@@ -193,6 +328,7 @@ async function runAttributeLogic(data: RunAttributeLogicData, options: RunAttrib
|
||||
return {
|
||||
logicBuildingWarnings: null,
|
||||
teamMembersMatchingAttributeLogic: null,
|
||||
resolvedAttributesQueryValue: null,
|
||||
timeTaken: null,
|
||||
...buildTroubleshooterData({
|
||||
type: TroubleshooterCase.MATCHES_ALL_MEMBERS_BECAUSE_OF_EMPTY_QUERY_VALUE,
|
||||
@@ -217,6 +353,7 @@ async function runAttributeLogic(data: RunAttributeLogicData, options: RunAttrib
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic: null,
|
||||
logicBuildingWarnings: null,
|
||||
resolvedAttributesQueryValue: attributesQueryValue,
|
||||
timeTaken: {
|
||||
ttgetAttributesQueryBuilderConfigHavingListofLabels,
|
||||
},
|
||||
@@ -256,6 +393,7 @@ async function runAttributeLogic(data: RunAttributeLogicData, options: RunAttrib
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic,
|
||||
logicBuildingWarnings,
|
||||
resolvedAttributesQueryValue: attributesQueryValue,
|
||||
timeTaken: {
|
||||
ttgetAttributesQueryBuilderConfigHavingListofLabels,
|
||||
ttTeamMembersMatchingAttributeLogic,
|
||||
@@ -322,15 +460,18 @@ export async function findTeamMembersMatchingAttributeLogic(
|
||||
fallbackAttributesQueryValue?: AttributesQueryValue | null;
|
||||
dynamicFieldValueOperands?: dynamicFieldValueOperands;
|
||||
isPreview?: boolean;
|
||||
routeName?: string;
|
||||
routeIsFallback?: boolean;
|
||||
},
|
||||
options: {
|
||||
enablePerf?: boolean;
|
||||
concurrency?: number;
|
||||
enableTroubleshooter?: boolean;
|
||||
routingTraceService?: RoutingTraceService;
|
||||
} = {}
|
||||
) {
|
||||
// Higher value of concurrency might not be performant as it might overwhelm the system. So, use a lower value as default.
|
||||
const { enablePerf = false, concurrency = 2, enableTroubleshooter = false } = options;
|
||||
const { enablePerf = false, concurrency = 2, enableTroubleshooter = false, routingTraceService } = options;
|
||||
|
||||
// Any explicit value being passed should cause fallback to be considered. Even undefined
|
||||
const considerFallback = "fallbackAttributesQueryValue" in data;
|
||||
@@ -342,6 +483,8 @@ export async function findTeamMembersMatchingAttributeLogic(
|
||||
fallbackAttributesQueryValue,
|
||||
dynamicFieldValueOperands,
|
||||
isPreview,
|
||||
routeName,
|
||||
routeIsFallback,
|
||||
} = data;
|
||||
|
||||
const {
|
||||
@@ -374,6 +517,7 @@ export async function findTeamMembersMatchingAttributeLogic(
|
||||
timeTaken: teamMembersMatchingMainAttributeLogicTimeTaken,
|
||||
troubleshooter,
|
||||
logicBuildingWarnings: mainAttributeLogicBuildingWarnings,
|
||||
resolvedAttributesQueryValue,
|
||||
} = await runMainAttributeLogic(
|
||||
{
|
||||
...runAttributeLogicData,
|
||||
@@ -382,14 +526,39 @@ export async function findTeamMembersMatchingAttributeLogic(
|
||||
runAttributeLogicOptions
|
||||
);
|
||||
|
||||
// Helper to add trace step for attribute logic evaluation
|
||||
const addTraceStep = (checkedFallback: boolean) => {
|
||||
if (routingTraceService) {
|
||||
const attributeRoutingDetails = extractAttributeRoutingDetails({
|
||||
resolvedAttributesQueryValue,
|
||||
attributesOfTheOrg,
|
||||
dynamicFieldValueOperands,
|
||||
});
|
||||
|
||||
routingTraceService.addStep({
|
||||
domain: ROUTING_TRACE_DOMAINS.ROUTING_FORM,
|
||||
step: ROUTING_TRACE_STEPS.ATTRIBUTE_LOGIC_EVALUATED,
|
||||
data: {
|
||||
routeName,
|
||||
routeIsFallback,
|
||||
checkedFallback,
|
||||
attributeRoutingDetails,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// It being null means that no logic was found and thus all members match. In such case, we don't fallback intentionally.
|
||||
// This is the case when user added no rules so, he expects to match all members
|
||||
if (!teamMembersMatchingMainAttributeLogic) {
|
||||
addTraceStep(false);
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic: null,
|
||||
checkedFallback: false,
|
||||
mainAttributeLogicBuildingWarnings,
|
||||
fallbackAttributeLogicBuildingWarnings: [],
|
||||
routeName,
|
||||
routeIsFallback,
|
||||
timeTaken: {
|
||||
...teamMembersMatchingMainAttributeLogicTimeTaken,
|
||||
ttGetAttributesForLogic,
|
||||
@@ -418,11 +587,14 @@ export async function findTeamMembersMatchingAttributeLogic(
|
||||
runAttributeLogicOptions
|
||||
);
|
||||
|
||||
addTraceStep(true);
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic: teamMembersMatchingFallbackLogic,
|
||||
checkedFallback: true,
|
||||
fallbackAttributeLogicBuildingWarnings,
|
||||
mainAttributeLogicBuildingWarnings,
|
||||
routeName,
|
||||
routeIsFallback,
|
||||
timeTaken: {
|
||||
...teamMembersMatchingFallbackLogicTimeTaken,
|
||||
ttGetAttributesForLogic,
|
||||
@@ -436,11 +608,14 @@ export async function findTeamMembersMatchingAttributeLogic(
|
||||
};
|
||||
}
|
||||
|
||||
addTraceStep(false);
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic: teamMembersMatchingMainAttributeLogic,
|
||||
checkedFallback: false,
|
||||
mainAttributeLogicBuildingWarnings,
|
||||
fallbackAttributeLogicBuildingWarnings: [],
|
||||
routeName,
|
||||
routeIsFallback,
|
||||
timeTaken: {
|
||||
...teamMembersMatchingMainAttributeLogicTimeTaken,
|
||||
ttGetAttributesForLogic,
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import "@calcom/lib/__mocks__/logger";
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import type { GetServerSidePropsContext } from "next";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { getAbsoluteEventTypeRedirectUrlWithEmbedSupport } from "@calcom/app-store/routing-forms/getEventTypeRedirectUrl";
|
||||
import { getResponseToStore } from "@calcom/app-store/routing-forms/lib/getResponseToStore";
|
||||
import { getSerializableForm } from "@calcom/app-store/routing-forms/lib/getSerializableForm";
|
||||
@@ -14,6 +11,8 @@ import { isAuthorizedToViewFormOnOrgDomain } from "@calcom/features/routing-form
|
||||
import { PrismaRoutingFormRepository } from "@calcom/features/routing-forms/repositories/PrismaRoutingFormRepository";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import type { GetServerSidePropsContext } from "next";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { getRoutedUrl } from "./getRoutedUrl";
|
||||
import { getUrlSearchParamsToForward } from "./getUrlSearchParamsToForward";
|
||||
@@ -26,9 +25,11 @@ vi.mock("@calcom/lib/checkRateLimitAndThrowError");
|
||||
vi.mock("@calcom/features/routing-forms/repositories/PrismaRoutingFormRepository");
|
||||
vi.mock("@calcom/features/users/repositories/UserRepository", () => {
|
||||
return {
|
||||
UserRepository: vi.fn().mockImplementation(function() { return {
|
||||
enrichUserWithItsProfile: vi.fn(),
|
||||
}; }),
|
||||
UserRepository: vi.fn().mockImplementation(function () {
|
||||
return {
|
||||
enrichUserWithItsProfile: vi.fn(),
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("@calcom/features/ee/organizations/lib/orgDomains");
|
||||
@@ -44,8 +45,33 @@ vi.mock("@calcom/app-store/routing-forms/enrichFormWithMigrationData", () => ({
|
||||
vi.mock("@calcom/lib/sentryWrapper", () => ({
|
||||
withReporting: (fn: unknown) => fn,
|
||||
}));
|
||||
vi.mock("@calcom/features/routing-trace/di/RoutingTraceService.container", () => ({
|
||||
getRoutingTraceService: vi.fn(() => ({
|
||||
addStep: vi.fn(),
|
||||
getStepsCount: vi.fn().mockReturnValue(0),
|
||||
savePendingRoutingTrace: vi.fn().mockResolvedValue(undefined),
|
||||
processForBooking: vi.fn().mockResolvedValue(undefined),
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockForm = {
|
||||
const mockForm: {
|
||||
id: string;
|
||||
user: { id: number; name: string };
|
||||
team: null;
|
||||
name: string;
|
||||
fields: never[];
|
||||
routes: never[];
|
||||
userId: number;
|
||||
teamId: null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
description: null;
|
||||
enabled: boolean;
|
||||
isDefault: boolean;
|
||||
fieldsOrder: never[];
|
||||
position: number;
|
||||
slug: string;
|
||||
} = {
|
||||
id: "form-id",
|
||||
user: { id: 1, name: "Test User" },
|
||||
team: null,
|
||||
@@ -64,7 +90,12 @@ const mockForm = {
|
||||
slug: "test-form",
|
||||
};
|
||||
|
||||
const mockSerializableForm = {
|
||||
const mockSerializableForm: {
|
||||
id: string;
|
||||
fields: { id: string; type: string; label: string; identifier: string }[];
|
||||
routes: never[];
|
||||
user: { id: number };
|
||||
} = {
|
||||
id: "form-id",
|
||||
fields: [{ id: "email", type: "email", label: "Email", identifier: "email" }],
|
||||
routes: [],
|
||||
@@ -73,7 +104,7 @@ const mockSerializableForm = {
|
||||
|
||||
const mockContext = (
|
||||
query: Record<string, unknown>,
|
||||
url = "/link/form-id"
|
||||
url: string = "/link/form-id"
|
||||
): Pick<GetServerSidePropsContext, "query" | "req"> => ({
|
||||
query: { form: "form-id", ...query },
|
||||
req: { url },
|
||||
@@ -92,8 +123,7 @@ describe("getRoutedUrl", () => {
|
||||
mockUserRepository.mockImplementation(function () {
|
||||
return {
|
||||
enrichUserWithItsProfile: mockEnrichUserWithItsProfile,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any;
|
||||
} as unknown as InstanceType<typeof UserRepository>;
|
||||
});
|
||||
}
|
||||
vi.mocked(isAuthorizedToViewFormOnOrgDomain).mockReturnValue(true);
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { FormResponse } from "@calcom/app-store/routing-forms/types/types";
|
||||
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { isAuthorizedToViewFormOnOrgDomain } from "@calcom/features/routing-forms/lib/isAuthorizedToViewForm";
|
||||
import { PrismaRoutingFormRepository } from "@calcom/features/routing-forms/repositories/PrismaRoutingFormRepository";
|
||||
import { getRoutingTraceService } from "@calcom/features/routing-trace/di/RoutingTraceService.container";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
@@ -36,7 +37,9 @@ const querySchema = z
|
||||
})
|
||||
.catchall(z.string().or(z.array(z.string())));
|
||||
|
||||
const getDeterministicHashForResponse = (fieldsResponses: Record<string, unknown>) => {
|
||||
const getDeterministicHashForResponse = (
|
||||
fieldsResponses: Record<string, unknown>
|
||||
) => {
|
||||
const sortedFields = Object.keys(fieldsResponses)
|
||||
.sort()
|
||||
.reduce((obj: Record<string, unknown>, key) => {
|
||||
@@ -53,7 +56,13 @@ export function hasEmbedPath(pathWithQuery: string) {
|
||||
return onlyPath.endsWith("/embed") || onlyPath.endsWith("/embed/");
|
||||
}
|
||||
|
||||
const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" | "req">, fetchCrm = true) => {
|
||||
const _getRoutedUrl = async (
|
||||
context: Pick<GetServerSidePropsContext, "query" | "req">,
|
||||
fetchCrm = true
|
||||
) => {
|
||||
// Initialize trace service for tracking routing decisions
|
||||
const routingTraceService = getRoutingTraceService();
|
||||
|
||||
const queryParsed = querySchema.safeParse(context.query);
|
||||
const isEmbed = hasEmbedPath(context.req.url || "");
|
||||
const pageProps = {
|
||||
@@ -87,7 +96,9 @@ const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" |
|
||||
const paramsToBeForwardedAsIs = {
|
||||
...fieldsResponses,
|
||||
// Must be forwarded if present to Booking Page. Setting it explicitly here as it is critical to be present in the URL.
|
||||
...(isBookingDryRunParam ? { "cal.isBookingDryRun": isBookingDryRunParam } : null),
|
||||
...(isBookingDryRunParam
|
||||
? { "cal.isBookingDryRun": isBookingDryRunParam }
|
||||
: null),
|
||||
};
|
||||
|
||||
const { currentOrgDomain } = orgDomainConfig(context.req);
|
||||
@@ -95,7 +106,8 @@ const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" |
|
||||
let timeTaken: Record<string, number | null> = {};
|
||||
|
||||
const formQueryStart = performance.now();
|
||||
const form = await PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg(formId);
|
||||
const form =
|
||||
await PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg(formId);
|
||||
timeTaken.formQuery = performance.now() - formQueryStart;
|
||||
|
||||
if (!form) {
|
||||
@@ -113,7 +125,11 @@ const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" |
|
||||
timeTaken.profileEnrichment = performance.now() - profileEnrichmentStart;
|
||||
|
||||
if (
|
||||
!isAuthorizedToViewFormOnOrgDomain({ user: formWithUserProfile.user, currentOrgDomain, team: form.team })
|
||||
!isAuthorizedToViewFormOnOrgDomain({
|
||||
user: formWithUserProfile.user,
|
||||
currentOrgDomain,
|
||||
team: form.team,
|
||||
})
|
||||
) {
|
||||
return {
|
||||
notFound: true,
|
||||
@@ -144,10 +160,10 @@ const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" |
|
||||
let teamMembersMatchingAttributeLogic = null;
|
||||
let formResponseId = null;
|
||||
let attributeRoutingConfig = null;
|
||||
let queuedFormResponseId;
|
||||
let crmContactOwnerEmail: string | null = null;
|
||||
let crmContactOwnerRecordType: string | null = null;
|
||||
let crmAppSlug: string | null = null;
|
||||
let queuedFormResponseId;
|
||||
try {
|
||||
const result = await handleResponse({
|
||||
form: serializableForm,
|
||||
@@ -158,18 +174,31 @@ const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" |
|
||||
isPreview: isBookingDryRun,
|
||||
queueFormResponse: shouldQueueFormResponse,
|
||||
fetchCrm,
|
||||
traceService: isBookingDryRun ? undefined : routingTraceService,
|
||||
});
|
||||
teamMembersMatchingAttributeLogic = result.teamMembersMatchingAttributeLogic;
|
||||
teamMembersMatchingAttributeLogic =
|
||||
result.teamMembersMatchingAttributeLogic;
|
||||
formResponseId = result.formResponse?.id;
|
||||
queuedFormResponseId = result.queuedFormResponse?.id;
|
||||
attributeRoutingConfig = result.attributeRoutingConfig;
|
||||
crmContactOwnerEmail = result.crmContactOwnerEmail;
|
||||
crmContactOwnerRecordType = result.crmContactOwnerRecordType;
|
||||
crmAppSlug = result.crmAppSlug;
|
||||
timeTaken = {
|
||||
...timeTaken,
|
||||
...result.timeTaken,
|
||||
};
|
||||
crmContactOwnerEmail = result.crmContactOwnerEmail;
|
||||
crmContactOwnerRecordType = result.crmContactOwnerRecordType;
|
||||
crmAppSlug = result.crmAppSlug;
|
||||
|
||||
// Save the pending trace (trace steps are added inside handleResponse)
|
||||
if (!isBookingDryRun) {
|
||||
if (formResponseId) {
|
||||
await routingTraceService.savePendingRoutingTrace({ formResponseId });
|
||||
} else if (queuedFormResponseId) {
|
||||
await routingTraceService.savePendingRoutingTrace({
|
||||
queuedFormResponseId,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof HttpError || e instanceof TRPCError) {
|
||||
return {
|
||||
@@ -214,17 +243,20 @@ const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" |
|
||||
formResponse: response,
|
||||
fields: serializableForm.fields,
|
||||
searchParams: new URLSearchParams(
|
||||
stringify({ ...paramsToBeForwardedAsIs, "cal.action": "eventTypeRedirectUrl" })
|
||||
stringify({
|
||||
...paramsToBeForwardedAsIs,
|
||||
"cal.action": "eventTypeRedirectUrl",
|
||||
})
|
||||
),
|
||||
teamMembersMatchingAttributeLogic,
|
||||
formResponseId: formResponseId ?? null,
|
||||
queuedFormResponseId: queuedFormResponseId ?? null,
|
||||
attributeRoutingConfig: attributeRoutingConfig ?? null,
|
||||
teamId: form?.teamId,
|
||||
orgId: form.team?.parentId,
|
||||
crmContactOwnerEmail,
|
||||
crmContactOwnerRecordType,
|
||||
crmAppSlug,
|
||||
teamId: form?.teamId,
|
||||
orgId: form.team?.parentId,
|
||||
}),
|
||||
isEmbed: pageProps.isEmbed,
|
||||
}),
|
||||
@@ -234,7 +266,9 @@ const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" |
|
||||
} else if (decidedAction.type === "externalRedirectUrl") {
|
||||
return {
|
||||
redirect: {
|
||||
destination: `${decidedAction.value}?${stringify(context.query)}&cal.action=externalRedirectUrl`,
|
||||
destination: `${decidedAction.value}?${stringify(
|
||||
context.query
|
||||
)}&cal.action=externalRedirectUrl`,
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -27,12 +27,12 @@ type GetUrlSearchParamsToForwardOptions = {
|
||||
queuedFormResponseId: string | null;
|
||||
teamMembersMatchingAttributeLogic: number[] | null;
|
||||
attributeRoutingConfig: AttributeRoutingConfig | null;
|
||||
reroutingFormResponses?: FormResponseValueOnly;
|
||||
teamId?: number | null;
|
||||
orgId?: number | null;
|
||||
crmContactOwnerEmail?: string | null;
|
||||
crmContactOwnerRecordType?: string | null;
|
||||
crmAppSlug?: string | null;
|
||||
reroutingFormResponses?: FormResponseValueOnly;
|
||||
teamId?: number | null;
|
||||
orgId?: number | null;
|
||||
};
|
||||
|
||||
export function getUrlSearchParamsToForward({
|
||||
@@ -43,12 +43,12 @@ export function getUrlSearchParamsToForward({
|
||||
formResponseId,
|
||||
queuedFormResponseId,
|
||||
attributeRoutingConfig,
|
||||
reroutingFormResponses,
|
||||
teamId,
|
||||
orgId,
|
||||
crmContactOwnerEmail,
|
||||
crmContactOwnerRecordType,
|
||||
crmAppSlug,
|
||||
reroutingFormResponses,
|
||||
teamId,
|
||||
orgId,
|
||||
}: GetUrlSearchParamsToForwardOptions) {
|
||||
type Params = Record<string, string | string[]>;
|
||||
const paramsFromResponse: Params = {};
|
||||
@@ -118,9 +118,6 @@ export function getUrlSearchParamsToForward({
|
||||
const allQueryParams: Params = {
|
||||
...(teamId && { ["cal.teamId"]: `${teamId}` }),
|
||||
...(orgId && { ["cal.orgId"]: `${orgId}` }),
|
||||
...(crmContactOwnerEmail && { ["cal.crmContactOwnerEmail"]: `${crmContactOwnerEmail}` }),
|
||||
...(crmContactOwnerRecordType && { ["cal.crmContactOwnerRecordType"]: `${crmContactOwnerRecordType}` }),
|
||||
...(crmAppSlug && { ["cal.crmAppSlug"]: `${crmAppSlug}` }),
|
||||
...paramsFromCurrentUrl,
|
||||
// In case of conflict b/w paramsFromResponse and paramsFromCurrentUrl, paramsFromResponse should win as the booker probably improved upon the prefilled value.
|
||||
...paramsFromResponse,
|
||||
@@ -132,6 +129,9 @@ export function getUrlSearchParamsToForward({
|
||||
: null),
|
||||
...(queuedFormResponseId ? { ["cal.queuedFormResponseId"]: queuedFormResponseId } : null),
|
||||
...attributeRoutingConfigParams,
|
||||
...(crmContactOwnerEmail ? { ["cal.crmContactOwnerEmail"]: crmContactOwnerEmail } : null),
|
||||
...(crmContactOwnerRecordType ? { ["cal.crmContactOwnerRecordType"]: crmContactOwnerRecordType } : null),
|
||||
...(crmAppSlug ? { ["cal.crmAppSlug"]: crmAppSlug } : null),
|
||||
...(reroutingFormResponses
|
||||
? { ["cal.reroutingFormResponses"]: JSON.stringify(reroutingFormResponses) }
|
||||
: null),
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type TargetRoutingFormForResponse,
|
||||
} from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
|
||||
import isRouter from "@calcom/app-store/routing-forms/lib/isRouter";
|
||||
import type { RoutingTraceService } from "@calcom/features/routing-trace/services/RoutingTraceService";
|
||||
import { emailSchema } from "@calcom/lib/emailSchema";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
@@ -29,6 +30,7 @@ const _handleResponse = async ({
|
||||
isPreview,
|
||||
queueFormResponse,
|
||||
fetchCrm,
|
||||
traceService,
|
||||
}: {
|
||||
response: Record<
|
||||
string,
|
||||
@@ -45,6 +47,7 @@ const _handleResponse = async ({
|
||||
isPreview: boolean;
|
||||
queueFormResponse?: boolean;
|
||||
fetchCrm?: boolean;
|
||||
traceService?: RoutingTraceService;
|
||||
}) => {
|
||||
try {
|
||||
if (!form.fields) {
|
||||
@@ -104,6 +107,7 @@ const _handleResponse = async ({
|
||||
let crmAppSlug: string | null = null;
|
||||
let crmRecordId: string | null = null;
|
||||
let timeTaken: Record<string, number | null> = {};
|
||||
let checkedFallback = false;
|
||||
if (chosenRoute) {
|
||||
if (isRouter(chosenRoute)) {
|
||||
throw new HttpError({
|
||||
@@ -121,6 +125,7 @@ const _handleResponse = async ({
|
||||
attributeRoutingConfig: chosenRoute.attributeRoutingConfig,
|
||||
identifierKeyedResponse,
|
||||
action: chosenRoute.action,
|
||||
routingTraceService: traceService,
|
||||
})
|
||||
: null;
|
||||
crmContactOwnerEmail = contactOwnerQuery?.email ?? null;
|
||||
@@ -141,9 +146,12 @@ const _handleResponse = async ({
|
||||
fallbackAttributesQueryValue: chosenRoute.fallbackAttributesQueryValue,
|
||||
teamId: formTeamId,
|
||||
orgId: formOrgId,
|
||||
routeName: chosenRoute.name,
|
||||
routeIsFallback: chosenRoute.isFallback,
|
||||
},
|
||||
{
|
||||
enablePerf: true,
|
||||
routingTraceService: traceService,
|
||||
}
|
||||
)
|
||||
: null;
|
||||
@@ -161,6 +169,7 @@ const _handleResponse = async ({
|
||||
: null;
|
||||
|
||||
timeTaken = teamMembersMatchingAttributeLogicWithResult?.timeTaken ?? {};
|
||||
checkedFallback = teamMembersMatchingAttributeLogicWithResult?.checkedFallback ?? false;
|
||||
})(),
|
||||
]);
|
||||
|
||||
@@ -226,6 +235,7 @@ const _handleResponse = async ({
|
||||
? chosenRoute.attributeRoutingConfig
|
||||
: null
|
||||
: null,
|
||||
checkedFallback,
|
||||
timeTaken,
|
||||
};
|
||||
} catch (e) {
|
||||
|
||||
Reference in new issue
Block a user