refactor: Move attribute and routing-forms code from app-store/lib to features (#26025)

* mv

* wip

* wip

* wip

* wip

* plural

* fix: resolve TypeScript type errors for attribute refactoring

- Add TransformedAttributeOption type to handle transformed contains field
- Update imports to use routing-forms Attribute type where needed
- Fix getValueOfAttributeOption to use TransformedAttributeOption type
- Update AttributeOptionValueWithType to use TransformedAttributeOption
- Fix pre-existing lint warnings (any -> unknown, proper type casting)

Co-Authored-By: [email protected] <[email protected]>

* fix

* cleanup

* cleanup

* fix

* fix

* fix

* fix

* fix

* fix: add explicit type annotation to reduce callback in getAttributes.ts

Co-Authored-By: [email protected] <[email protected]>

* fix: use RouterOutputs from @calcom/trpc/react for consistent type inference

- Update AppPage.tsx to use RouterOutputs from @calcom/trpc/react instead of inferRouterOutputs<AppRouter>
- Update MultiDisconnectIntegration.tsx to use the same RouterOutputs type source
- Add eslint-disable comments for pre-existing warnings (useEffect deps, img elements)

Co-Authored-By: [email protected] <[email protected]>

* fix: explicitly type attribute property in AttributeOptionAssignment

The attribute property from Pick<AttributeOption, 'attribute'> was typed as
'unknown' because Prisma relations don't have explicit types when picked.
This explicitly defines the attribute shape with id, type, and isLocked
properties that are used in assignValueToUser.ts.

Co-Authored-By: [email protected] <[email protected]>

* fix: remove unused assignedUsers from AttributeOptionAssignment Pick

The assignedUsers property was not being used in the code but was required
by the Pick type, causing a type mismatch when the actual data from the
database query didn't include it.

Co-Authored-By: [email protected] <[email protected]>

* fix: update import path for AttributeOptionAssignment and BulkAttributeAssigner types

The types.d.ts file was moved from packages/lib/service/attribute/ to
packages/app-store/routing-forms/types/. Updated the import path in utils.ts
to point to the new location.

Co-Authored-By: [email protected] <[email protected]>

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2025-12-29 21:51:06 -03:00
1 parent 5f0e408d2f
commit 00e5770273
37 files changed
+130 -136

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,459 @@
import async from "async";
import type { ImmutableTree, JsonLogicResult, JsonTree } from "react-awesome-query-builder";
import type { Config } from "react-awesome-query-builder/lib";
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 { RaqbLogicResult } from "@calcom/lib/raqb/evaluateRaqbLogic";
import jsonLogic from "@calcom/lib/raqb/jsonLogic";
import type { dynamicFieldValueOperands, AttributesQueryValue } from "@calcom/lib/raqb/types";
const {
getAttributesData: getAttributes,
getAttributesQueryBuilderConfigHavingListofLabels,
getAttributesQueryValue,
} = acrossQueryValueCompatiblity;
type TeamMemberWithAttributeOptionValuePerAttribute = Awaited<
ReturnType<typeof getAttributesAssignmentData>
>["attributesAssignedToTeamMembersWithOptions"][number];
type RunAttributeLogicData = {
attributesQueryValue: AttributesQueryValue | null;
attributesData: {
attributesOfTheOrg: Attribute[];
teamMembersWithAttributeOptionValuePerAttribute: TeamMemberWithAttributeOptionValuePerAttribute[];
};
dynamicFieldValueOperands?: dynamicFieldValueOperands;
};
type RunAttributeLogicOptions = {
concurrency: number;
enablePerf: boolean;
isPreview: boolean;
enableTroubleshooter: boolean;
};
export const enum TroubleshooterCase {
IS_A_ROUTER = "is-a-router",
NO_LOGIC_FOUND = "no-logic-found",
MATCH_RESULTS_READY = "match-results-ready",
MATCH_RESULTS_READY_WITH_FALLBACK = "match-results-ready-with-fallback",
MATCHES_ALL_MEMBERS_BECAUSE_OF_EMPTY_QUERY_VALUE = "matches-all-members-because-of-empty-query-value",
MATCHES_ALL_MEMBERS = "matches-all-members",
}
/**
* Performance wrapper for async functions
*/
async function asyncPerf<ReturnValue>(fn: () => Promise<ReturnValue>): Promise<[ReturnValue, number | null]> {
const start = performance.now();
const result = await fn();
const end = performance.now();
return [result, end - start];
}
/**
* Performance wrapper for sync functions
*/
function perf<ReturnValue>(fn: () => ReturnValue): [ReturnValue, number | null] {
const start = performance.now();
const result = fn();
const end = performance.now();
return [result, end - start];
}
function getErrorsFromImmutableTree(tree: ImmutableTree) {
const validatedQueryValue = QbUtils.getTree(tree);
if (!raqbQueryValueUtils.isQueryValueARuleGroup(validatedQueryValue)) {
return [];
}
if (!validatedQueryValue.children1) {
return [];
}
const errors: string[][] = [];
Object.values(validatedQueryValue.children1).map((rule) => {
if (rule.type !== "rule") {
return;
}
const valueError = rule.properties.valueError;
if (valueError) {
// Sometimes there are null values in it.
errors.push(valueError.filter(Boolean));
}
});
return errors;
}
function getJsonLogic({
attributesQueryValue,
attributesQueryBuilderConfig,
}: {
attributesQueryValue: AttributesQueryValue;
attributesQueryBuilderConfig: Config;
}) {
const state = {
tree: QbUtils.checkTree(
QbUtils.loadTree(attributesQueryValue as JsonTree),
// We know that attributesQueryBuilderConfig is a Config because getAttributesQueryBuilderConfigHavingListofLabels returns a Config. So, asserting it.
attributesQueryBuilderConfig as unknown as Config
),
config: attributesQueryBuilderConfig as unknown as Config,
};
const jsonLogicQuery = QbUtils.jsonLogicFormat(state.tree, state.config);
const logic = jsonLogicQuery.logic;
// Considering errors as warnings as we want to continue with the flow without throwing actual errors
// We expect fallback logic to take effect in case of errors in main logic
const warnings = getErrorsFromImmutableTree(state.tree).flat();
if (!logic) {
// If children1 is not empty, it means that some rules were added by use
if (attributesQueryValue.children1 && Object.keys(attributesQueryValue.children1).length > 0) {
// Possible reasons for this
// 1. The attribute option value used is not in the options list. Happens if 'Value of field' value is chosen and that field's response value doesn't exist in attribute options list.
return { logic, warnings: ["There is some error building the logic, please check the routes."] };
}
}
return { logic, warnings };
}
function buildTroubleshooterData({ type, data }: { type: TroubleshooterCase; data: Record<string, any> }) {
return {
troubleshooter: {
type,
data,
},
};
}
async function getLogicResultForAllMembers(
{
teamMembersWithAttributeOptionValuePerAttribute,
attributeJsonLogic,
attributesQueryValue,
}: {
teamMembersWithAttributeOptionValuePerAttribute: TeamMemberWithAttributeOptionValuePerAttribute[];
attributeJsonLogic: NonNullable<JsonLogicResult["logic"]>;
attributesQueryValue: AttributesQueryValue;
},
config: {
concurrency?: number;
enableTroubleshooter?: boolean;
} = {}
) {
const { concurrency = 2 } = config;
const teamMembersMatchingAttributeLogicMap = new Map<number, RaqbLogicResult>();
const attributesDataPerUser = new Map<number, ReturnType<typeof getAttributes>>();
await async.mapLimit<TeamMemberWithAttributeOptionValuePerAttribute, Promise<void>>(
teamMembersWithAttributeOptionValuePerAttribute,
concurrency,
async (member: TeamMemberWithAttributeOptionValuePerAttribute) => {
const attributesData = getAttributes({
attributesData: member.attributes,
attributesQueryValue,
});
attributesDataPerUser.set(member.userId, attributesData);
const result = jsonLogic.apply(attributeJsonLogic as any, attributesData)
? RaqbLogicResult.MATCH
: RaqbLogicResult.NO_MATCH;
if (result !== RaqbLogicResult.MATCH) {
return;
}
teamMembersMatchingAttributeLogicMap.set(member.userId, result);
}
);
return {
teamMembersMatchingAttributeLogicMap,
attributesDataPerUser,
};
}
async function runAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
const {
attributesQueryValue: _attributesQueryValue,
attributesData: { attributesOfTheOrg, teamMembersWithAttributeOptionValuePerAttribute },
dynamicFieldValueOperands,
} = data;
const { concurrency, enablePerf, enableTroubleshooter } = options;
const attributesQueryValue = getAttributesQueryValue({
attributesQueryValue: _attributesQueryValue ?? null,
attributes: attributesOfTheOrg,
dynamicFieldValueOperands,
});
// TODO: Do we really need to do !attributesQueryValue check separately?
if (!attributesQueryValue || raqbQueryValueUtils.isQueryValueEmpty(attributesQueryValue as JsonTree)) {
return {
logicBuildingWarnings: null,
teamMembersMatchingAttributeLogic: null,
timeTaken: null,
...buildTroubleshooterData({
type: TroubleshooterCase.MATCHES_ALL_MEMBERS_BECAUSE_OF_EMPTY_QUERY_VALUE,
data: { attributesQueryValue },
}),
};
}
const [attributesQueryBuilderConfig, ttgetAttributesQueryBuilderConfigHavingListofLabels] = pf(() =>
getAttributesQueryBuilderConfigHavingListofLabels({
dynamicFieldValueOperands,
attributes: attributesOfTheOrg,
})
);
const { logic, warnings: logicBuildingWarnings } = getJsonLogic({
attributesQueryValue,
attributesQueryBuilderConfig: attributesQueryBuilderConfig as unknown as Config,
});
if (!logic) {
return {
teamMembersMatchingAttributeLogic: null,
logicBuildingWarnings: null,
timeTaken: {
ttgetAttributesQueryBuilderConfigHavingListofLabels,
},
...buildTroubleshooterData({
type: TroubleshooterCase.NO_LOGIC_FOUND,
data: {
attributesQueryValue,
attributesQueryBuilderConfig,
teamMembersWithAttributeOptionValuePerAttribute,
},
}),
};
}
const [
{ teamMembersMatchingAttributeLogicMap, attributesDataPerUser },
ttTeamMembersMatchingAttributeLogic,
] = await aPf(async () =>
getLogicResultForAllMembers(
{
teamMembersWithAttributeOptionValuePerAttribute,
attributeJsonLogic: logic,
attributesQueryValue,
},
{
concurrency,
enableTroubleshooter,
}
)
);
const teamMembersMatchingAttributeLogic = Array.from(teamMembersMatchingAttributeLogicMap).map((item) => ({
userId: item[0],
result: item[1],
}));
return {
teamMembersMatchingAttributeLogic,
logicBuildingWarnings,
timeTaken: {
ttgetAttributesQueryBuilderConfigHavingListofLabels,
ttTeamMembersMatchingAttributeLogic,
},
...buildTroubleshooterData({
type: TroubleshooterCase.MATCH_RESULTS_READY,
data: {
attributesDataPerUser,
attributesQueryValue,
attributesQueryBuilderConfig,
logic,
attributesOfTheOrg,
},
}),
};
function pf<ReturnValue>(fn: () => ReturnValue): [ReturnValue, number | null] {
if (!enablePerf) {
return [fn(), null];
}
return perf(fn);
}
async function aPf<ReturnValue>(fn: () => Promise<ReturnValue>): Promise<[ReturnValue, number | null]> {
if (!enablePerf) {
return [await fn(), null];
}
return asyncPerf(fn);
}
}
async function runMainAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
const { teamMembersMatchingAttributeLogic, ...rest } = await runAttributeLogic(data, options);
return {
teamMembersMatchingMainAttributeLogic: teamMembersMatchingAttributeLogic,
...rest,
};
}
async function runFallbackAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
const { teamMembersMatchingAttributeLogic, ...rest } = await runAttributeLogic(data, options);
return {
teamMembersMatchingFallbackLogic: teamMembersMatchingAttributeLogic,
...rest,
};
}
export async function getAttributesForLogic({ teamId, orgId }: { teamId: number; orgId: number }) {
const [result, ttAttributes] = await asyncPerf(async () => {
return getAttributesAssignmentData({ teamId, orgId });
});
return {
attributesOfTheOrg: result.attributesOfTheOrg,
teamMembersWithAttributeOptionValuePerAttribute: result.attributesAssignedToTeamMembersWithOptions,
timeTaken: ttAttributes,
};
}
export async function findTeamMembersMatchingAttributeLogic(
data: {
teamId: number;
orgId: number;
attributesQueryValue: AttributesQueryValue | null;
fallbackAttributesQueryValue?: AttributesQueryValue | null;
dynamicFieldValueOperands?: dynamicFieldValueOperands;
isPreview?: boolean;
},
options: {
enablePerf?: boolean;
concurrency?: number;
enableTroubleshooter?: boolean;
} = {}
) {
// 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;
// Any explicit value being passed should cause fallback to be considered. Even undefined
const considerFallback = "fallbackAttributesQueryValue" in data;
const {
teamId,
orgId,
attributesQueryValue,
fallbackAttributesQueryValue,
dynamicFieldValueOperands,
isPreview,
} = data;
const {
attributesOfTheOrg,
teamMembersWithAttributeOptionValuePerAttribute,
timeTaken: ttGetAttributesForLogic,
} = await getAttributesForLogic({
teamId,
orgId,
});
const runAttributeLogicOptions = {
concurrency,
enablePerf,
isPreview: !!isPreview,
enableTroubleshooter,
};
const runAttributeLogicData: Omit<RunAttributeLogicData, "attributesQueryValue"> = {
// Change it as per the main/fallback query
attributesData: {
attributesOfTheOrg,
teamMembersWithAttributeOptionValuePerAttribute,
},
dynamicFieldValueOperands,
};
const {
teamMembersMatchingMainAttributeLogic,
timeTaken: teamMembersMatchingMainAttributeLogicTimeTaken,
troubleshooter,
logicBuildingWarnings: mainAttributeLogicBuildingWarnings,
} = await runMainAttributeLogic(
{
...runAttributeLogicData,
attributesQueryValue: attributesQueryValue,
},
runAttributeLogicOptions
);
// 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) {
return {
teamMembersMatchingAttributeLogic: null,
checkedFallback: false,
mainAttributeLogicBuildingWarnings,
fallbackAttributeLogicBuildingWarnings: [],
timeTaken: {
...teamMembersMatchingMainAttributeLogicTimeTaken,
ttGetAttributesForLogic,
},
...(enableTroubleshooter
? buildTroubleshooterData({
...troubleshooter,
})
: null),
};
}
const noMatchingMembersFound = !teamMembersMatchingMainAttributeLogic.length;
if (noMatchingMembersFound && considerFallback) {
const {
teamMembersMatchingFallbackLogic,
timeTaken: teamMembersMatchingFallbackLogicTimeTaken,
troubleshooter,
logicBuildingWarnings: fallbackAttributeLogicBuildingWarnings,
} = await runFallbackAttributeLogic(
{
...runAttributeLogicData,
attributesQueryValue: fallbackAttributesQueryValue ?? null,
},
runAttributeLogicOptions
);
return {
teamMembersMatchingAttributeLogic: teamMembersMatchingFallbackLogic,
checkedFallback: true,
fallbackAttributeLogicBuildingWarnings,
mainAttributeLogicBuildingWarnings,
timeTaken: {
...teamMembersMatchingFallbackLogicTimeTaken,
ttGetAttributesForLogic,
},
...(enableTroubleshooter
? buildTroubleshooterData({
...troubleshooter,
type: TroubleshooterCase.MATCH_RESULTS_READY_WITH_FALLBACK,
})
: null),
};
}
return {
teamMembersMatchingAttributeLogic: teamMembersMatchingMainAttributeLogic,
checkedFallback: false,
mainAttributeLogicBuildingWarnings,
fallbackAttributeLogicBuildingWarnings: [],
timeTaken: {
...teamMembersMatchingMainAttributeLogicTimeTaken,
ttGetAttributesForLogic,
},
...(enableTroubleshooter
? buildTroubleshooterData({
...troubleshooter,
type: TroubleshooterCase.MATCH_RESULTS_READY,
data: {
...troubleshooter.data,
attributesOfTheOrg,
},
})
: null),
};
}
@@ -7,7 +7,6 @@ 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";
import { handleResponse } from "@calcom/app-store/routing-forms/lib/handleResponse";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { substituteVariables } from "@calcom/app-store/routing-forms/lib/substituteVariables";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
@@ -18,11 +17,12 @@ import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowE
import { getRoutedUrl } from "./getRoutedUrl";
import { getUrlSearchParamsToForward } from "./getUrlSearchParamsToForward";
import { handleResponse } from "./handleResponse";
// Mock dependencies
vi.mock("./getUrlSearchParamsToForward");
vi.mock("./handleResponse");
vi.mock("@calcom/lib/checkRateLimitAndThrowError");
vi.mock("@calcom/app-store/routing-forms/lib/handleResponse");
vi.mock("@calcom/features/routing-forms/repositories/PrismaRoutingFormRepository");
vi.mock("@calcom/features/users/repositories/UserRepository", () => {
return {
@@ -10,7 +10,6 @@ import { getAbsoluteEventTypeRedirectUrlWithEmbedSupport } from "@calcom/app-sto
import { getResponseToStore } from "@calcom/app-store/routing-forms/lib/getResponseToStore";
import { getSerializableForm } from "@calcom/app-store/routing-forms/lib/getSerializableForm";
import { getServerTimingHeader } from "@calcom/app-store/routing-forms/lib/getServerTimingHeader";
import { handleResponse } from "@calcom/app-store/routing-forms/lib/handleResponse";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { substituteVariables } from "@calcom/app-store/routing-forms/lib/substituteVariables";
import type { FormResponse } from "@calcom/app-store/routing-forms/types/types";
@@ -28,6 +27,7 @@ import prisma from "@calcom/prisma";
import { TRPCError } from "@trpc/server";
import { getUrlSearchParamsToForward } from "./getUrlSearchParamsToForward";
import { handleResponse } from "./handleResponse";
const log = logger.getSubLogger({ prefix: ["[routing-forms]", "[router]"] });
const querySchema = z
@@ -0,0 +1,345 @@
import "@calcom/lib/__mocks__/logger";
import { prisma } from "@calcom/prisma/__mocks__/prisma";
import { beforeEach, describe, expect, it, vi } from "vitest";
import routerGetCrmContactOwnerEmail from "@calcom/app-store/routing-forms/lib/crmRouting/routerGetCrmContactOwnerEmail";
import type { TargetRoutingFormForResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
import { onSubmissionOfFormResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
import isRouter from "@calcom/app-store/routing-forms/lib/isRouter";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { findTeamMembersMatchingAttributeLogic } from "./findTeamMembersMatchingAttributeLogic";
import { handleResponse } from "./handleResponse";
vi.mock("./findTeamMembersMatchingAttributeLogic", () => ({
findTeamMembersMatchingAttributeLogic: vi.fn(),
}));
vi.mock("@calcom/lib/server/repository/formResponse");
const mockRoutingFormResponseRepository = {
recordQueuedFormResponse: vi.fn(),
recordFormResponse: vi.fn(),
};
vi.mock("@calcom/app-store/routing-forms/lib/crmRouting/routerGetCrmContactOwnerEmail", () => ({
default: vi.fn(),
}));
vi.mock("@calcom/app-store/routing-forms/lib/formSubmissionUtils", () => ({
onSubmissionOfFormResponse: vi.fn(),
}));
vi.mock("@calcom/app-store/routing-forms/lib/isRouter", () => ({
default: vi.fn(),
}));
vi.mock("@calcom/lib/sentryWrapper", () => ({
withReporting: (fn: unknown) => fn,
}));
vi.mock("@calcom/prisma", () => ({
prisma,
}));
const mockForm: TargetRoutingFormForResponse = {
id: "form-id",
name: "Test Form",
fields: [
{
id: "name",
label: "Name",
type: "text" as const,
required: true,
identifier: "name",
placeholder: undefined,
selectText: undefined,
deleted: false,
},
{
id: "email",
label: "Email",
type: "email" as const,
required: true,
identifier: "email",
placeholder: undefined,
selectText: undefined,
deleted: false,
},
{
id: "guests",
label: "Guests",
type: "text" as const,
required: false,
identifier: "guests",
placeholder: undefined,
selectText: undefined,
deleted: false,
},
],
routes: [],
userId: 1,
teamId: 1,
user: {
id: 1,
email: "[email protected]",
timeFormat: null,
locale: null,
},
team: {
parentId: 2,
},
createdAt: "2023-01-01T00:00:00.000Z",
updatedAt: "2023-01-01T00:00:00.000Z",
description: null,
disabled: false,
settings: {
emailOwnerOnSubmission: false,
},
connectedForms: [],
routers: [],
teamMembers: [],
position: 0,
updatedById: null,
};
const mockResponse: Record<
string,
{
value: (string | number | string[]) & (string | number | string[] | undefined);
label: string;
identifier?: string | undefined;
}
> = {
name: { value: "John Doe", label: "Name" },
email: { value: "[email protected]", label: "Email" },
};
describe("handleResponse", () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(RoutingFormResponseRepository).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
() => mockRoutingFormResponseRepository as any
);
});
it("should throw an Error for missing required fields", async () => {
await expect(
handleResponse({
response: { email: { value: "[email protected]", label: "Email" } }, // Name is missing
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: false,
})
).rejects.toThrow(/Missing required fields Name/);
});
it("should throw an Error for invalid email", async () => {
await expect(
handleResponse({
response: {
name: { value: "John Doe", label: "Name" },
email: { value: "invalid-email", label: "Email" },
},
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: false,
})
).rejects.toThrow(/Invalid value for fields 'Email' with value 'invalid-email' should be valid email/);
});
it("should record form response when not in preview and not queued", async () => {
const dbFormResponse = {
id: 1,
uuid: "d8b4b7d2-3f45-4f67-9aa1-98c4b49cf283",
formId: mockForm.id,
response: mockResponse,
chosenRouteId: null,
formFillerId: "user1",
routedToBookingUid: null,
createdAt: new Date(),
updatedAt: new Date(),
};
vi.mocked(mockRoutingFormResponseRepository.recordFormResponse).mockResolvedValue(dbFormResponse);
const result = await handleResponse({
response: mockResponse,
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: false,
});
expect(mockRoutingFormResponseRepository.recordFormResponse).toHaveBeenCalledWith({
formId: mockForm.id,
response: mockResponse,
chosenRouteId: null,
});
expect(onSubmissionOfFormResponse).toHaveBeenCalledWith({
form: mockForm,
formResponseInDb: dbFormResponse,
chosenRouteAction: null,
});
expect(result.formResponse).toEqual(dbFormResponse);
expect(result.queuedFormResponse).toBeNull();
});
it("should queue form response when queueFormResponse is true", async () => {
const queuedResponse = {
id: "queued-id",
formId: mockForm.id,
response: mockResponse,
chosenRouteId: null,
actualResponseId: null,
createdAt: new Date(),
updatedAt: new Date(),
};
vi.mocked(mockRoutingFormResponseRepository.recordQueuedFormResponse).mockResolvedValue(queuedResponse);
const result = await handleResponse({
response: mockResponse,
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: false,
queueFormResponse: true,
});
expect(mockRoutingFormResponseRepository.recordQueuedFormResponse).toHaveBeenCalledWith({
formId: mockForm.id,
response: mockResponse,
chosenRouteId: null,
});
expect(mockRoutingFormResponseRepository.recordFormResponse).not.toHaveBeenCalled();
expect(onSubmissionOfFormResponse).not.toHaveBeenCalled();
expect(result.queuedFormResponse).toEqual(queuedResponse);
expect(result.formResponse).toBeNull();
});
describe("Preview mode", () => {
it("should send formResponse with id=0 and quueueFormResponse isn't true", async () => {
const result = await handleResponse({
response: mockResponse,
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: true,
});
expect(mockRoutingFormResponseRepository.recordFormResponse).not.toHaveBeenCalled();
expect(onSubmissionOfFormResponse).not.toHaveBeenCalled();
expect(result.isPreview).toBe(true);
expect(result.formResponse).toBeDefined();
expect(result.formResponse?.id).toBe(0);
});
it("should send queuedFormResponse with id=00000000-0000-0000-0000-000000000000 when queueFormResponse is true", async () => {
const result = await handleResponse({
response: mockResponse,
form: mockForm,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: null,
isPreview: true,
queueFormResponse: true,
});
expect(mockRoutingFormResponseRepository.recordQueuedFormResponse).not.toHaveBeenCalled();
expect(result.isPreview).toBe(true);
expect(result.queuedFormResponse).toBeDefined();
expect(result.queuedFormResponse?.id).toBe("00000000-0000-0000-0000-000000000000");
expect(result.formResponse).toBeUndefined();
});
});
it("should handle chosen route and call routing logic", async () => {
const chosenRoute = {
id: "route1",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
queryValue: { type: "group", children1: {} } as any,
action: {
type: "customPageMessage" as const,
value: "Thank you for your submission!",
},
attributeRoutingConfig: null,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
attributesQueryValue: { type: "group", children1: {} } as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fallbackAttributesQueryValue: { type: "group", children1: {} } as any,
isFallback: false,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const formWithRoute: TargetRoutingFormForResponse = { ...mockForm, routes: [chosenRoute as any] };
vi.mocked(routerGetCrmContactOwnerEmail).mockResolvedValue({
email: "[email protected]",
recordType: "contact",
crmAppSlug: "hubspot",
recordId: "123",
});
vi.mocked(findTeamMembersMatchingAttributeLogic).mockResolvedValue({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
teamMembersMatchingAttributeLogic: [{ userId: 123, result: "MATCH" as any }],
checkedFallback: false,
fallbackAttributeLogicBuildingWarnings: [],
mainAttributeLogicBuildingWarnings: [],
timeTaken: {
ttGetAttributesForLogic: 50,
},
});
const result = await handleResponse({
response: mockResponse,
form: formWithRoute,
formFillerId: "user1",
chosenRouteId: "route1",
isPreview: false,
identifierKeyedResponse: {
name: "John Doe",
email: "[email protected]",
},
fetchCrm: true,
});
expect(routerGetCrmContactOwnerEmail).toHaveBeenCalled();
expect(findTeamMembersMatchingAttributeLogic).toHaveBeenCalled();
expect(result.crmContactOwnerEmail).toBe("[email protected]");
expect(result.teamMembersMatchingAttributeLogic).toEqual([123]);
});
it("should throw error if chosen route is a router", async () => {
const chosenRoute = {
id: "route1",
name: "A router",
description: "Router description",
isRouter: true as const,
routes: [],
};
vi.mocked(isRouter).mockReturnValue(true);
const formWithRoute: TargetRoutingFormForResponse = {
...mockForm,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
routes: [chosenRoute as any],
};
await expect(
handleResponse({
response: mockResponse,
form: formWithRoute,
identifierKeyedResponse: null,
formFillerId: "user1",
chosenRouteId: "route1",
isPreview: false,
})
).rejects.toThrow(/Chosen route is a router/);
});
});
@@ -0,0 +1,244 @@
import { z } from "zod";
import routerGetCrmContactOwnerEmail from "@calcom/app-store/routing-forms/lib/crmRouting/routerGetCrmContactOwnerEmail";
import {
onSubmissionOfFormResponse,
type TargetRoutingFormForResponse,
} from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
import isRouter from "@calcom/app-store/routing-forms/lib/isRouter";
import { emailSchema } from "@calcom/lib/emailSchema";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
import { prisma } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import { findTeamMembersMatchingAttributeLogic } from "./findTeamMembersMatchingAttributeLogic";
const moduleLogger = logger.getSubLogger({ prefix: ["routing-forms/lib/handleResponse"] });
const _handleResponse = async ({
response,
identifierKeyedResponse,
form,
// Unused but probably should be used
// formFillerId,
chosenRouteId,
isPreview,
queueFormResponse,
fetchCrm,
}: {
response: Record<
string,
{
value: string | number | string[];
label: string;
identifier?: string;
}
>;
identifierKeyedResponse: Record<string, string | string[]> | null;
form: TargetRoutingFormForResponse;
formFillerId: string;
chosenRouteId: string | null;
isPreview: boolean;
queueFormResponse?: boolean;
fetchCrm?: boolean;
}) => {
try {
if (!form.fields) {
// There is no point in submitting a form that doesn't have fields defined
throw new HttpError({ statusCode: 400 });
}
const formTeamId = form.teamId;
const formOrgId = form.team?.parentId ?? null;
const serializableFormWithFields = {
...form,
fields: form.fields,
};
const missingFields = serializableFormWithFields.fields
.filter((field) => !(field.required ? response[field.id]?.value : true))
.map((f) => f.label);
if (missingFields.length) {
throw new HttpError({
statusCode: 400,
message: `Missing required fields ${missingFields.join(", ")}`,
});
}
const invalidFields = serializableFormWithFields.fields
.filter((field) => {
const fieldValue = response[field.id]?.value;
// The field isn't required at this point. Validate only if it's set
if (!fieldValue) {
return false;
}
let schema;
if (field.type === "email") {
schema = emailSchema;
} else if (field.type === "phone") {
schema = z.any();
} else {
schema = z.any();
}
return !schema.safeParse(fieldValue).success;
})
.map((f) => ({ label: f.label, type: f.type, value: response[f.id]?.value }));
if (invalidFields.length) {
throw new HttpError({
statusCode: 400,
message: `Invalid value for fields ${invalidFields
.map((f) => `'${f.label}' with value '${f.value}' should be valid ${f.type}`)
.join(", ")}`,
});
}
const chosenRoute = serializableFormWithFields.routes?.find((route) => route.id === chosenRouteId);
let teamMemberIdsMatchingAttributeLogic: number[] | null = null;
let crmContactOwnerEmail: string | null = null;
let crmContactOwnerRecordType: string | null = null;
let crmAppSlug: string | null = null;
let crmRecordId: string | null = null;
let timeTaken: Record<string, number | null> = {};
if (chosenRoute) {
if (isRouter(chosenRoute)) {
throw new HttpError({
statusCode: 400,
message: "Chosen route is a router",
});
}
const getRoutedMembers = async () =>
await Promise.all([
(async () => {
const contactOwnerQuery =
identifierKeyedResponse && fetchCrm
? await routerGetCrmContactOwnerEmail({
attributeRoutingConfig: chosenRoute.attributeRoutingConfig,
identifierKeyedResponse,
action: chosenRoute.action,
})
: null;
crmContactOwnerEmail = contactOwnerQuery?.email ?? null;
crmContactOwnerRecordType = contactOwnerQuery?.recordType ?? null;
crmAppSlug = contactOwnerQuery?.crmAppSlug ?? null;
crmRecordId = contactOwnerQuery?.recordId ?? null;
})(),
(async () => {
const teamMembersMatchingAttributeLogicWithResult =
formTeamId && formOrgId
? await findTeamMembersMatchingAttributeLogic(
{
dynamicFieldValueOperands: {
response,
fields: form.fields || [],
},
attributesQueryValue: chosenRoute.attributesQueryValue ?? null,
fallbackAttributesQueryValue: chosenRoute.fallbackAttributesQueryValue,
teamId: formTeamId,
orgId: formOrgId,
},
{
enablePerf: true,
}
)
: null;
moduleLogger.debug(
"teamMembersMatchingAttributeLogic",
safeStringify({ teamMembersMatchingAttributeLogicWithResult })
);
teamMemberIdsMatchingAttributeLogic =
teamMembersMatchingAttributeLogicWithResult?.teamMembersMatchingAttributeLogic
? teamMembersMatchingAttributeLogicWithResult.teamMembersMatchingAttributeLogic.map(
(member) => member.userId
)
: null;
timeTaken = teamMembersMatchingAttributeLogicWithResult?.timeTaken ?? {};
})(),
]);
await withReporting(getRoutedMembers, "getRoutedMembers")();
} else {
// It currently happens for a Router route. Such a route id isn't present in the form.routes
}
let dbFormResponse, queuedFormResponse;
if (!isPreview) {
const formResponseRepo = new RoutingFormResponseRepository(prisma);
if (queueFormResponse) {
queuedFormResponse = await formResponseRepo.recordQueuedFormResponse({
formId: form.id,
response,
chosenRouteId,
});
dbFormResponse = null;
} else {
dbFormResponse = await formResponseRepo.recordFormResponse({
formId: form.id,
response,
chosenRouteId,
});
queuedFormResponse = null;
await onSubmissionOfFormResponse({
form: serializableFormWithFields,
formResponseInDb: dbFormResponse,
chosenRouteAction: chosenRoute ? ("action" in chosenRoute ? chosenRoute.action : null) : null,
});
}
} else {
moduleLogger.debug("Dry run mode - Form response not stored and also webhooks and emails not sent");
if (queueFormResponse) {
queuedFormResponse = {
id: "00000000-0000-0000-0000-000000000000",
formId: form.id,
response,
};
} else {
// Create a mock response for dry run
dbFormResponse = {
id: 0,
formId: form.id,
response,
chosenRouteId,
createdAt: new Date(),
updatedAt: new Date(),
};
}
}
return {
isPreview: !!isPreview,
formResponse: dbFormResponse,
queuedFormResponse,
teamMembersMatchingAttributeLogic: teamMemberIdsMatchingAttributeLogic,
crmContactOwnerEmail,
crmContactOwnerRecordType,
crmAppSlug,
crmRecordId,
attributeRoutingConfig: chosenRoute
? "attributeRoutingConfig" in chosenRoute
? chosenRoute.attributeRoutingConfig
: null
: null,
timeTaken,
};
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === "P2002") {
throw new HttpError({
statusCode: 409,
message: "Form response already exists",
});
}
}
throw e;
}
};
export const handleResponse = withReporting(_handleResponse, "handleResponse");