refactor: Migrate getRoutedUrl from @calcom/lib to @calcom/features (#23666)
* mkdir * update imports * chore: update platform libraries --------- Co-authored-by: Lauris Skraucis <[email protected]> Co-authored-by: supalarry <[email protected]>
This commit is contained in:
7 files changed
+9
-9
No files matched your search
@@ -0,0 +1,327 @@
|
||||
import "@calcom/lib/__mocks__/logger";
|
||||
|
||||
import { createHash } from "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";
|
||||
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 { getUrlSearchParamsToForward } from "@calcom/app-store/routing-forms/pages/routing-link/getUrlSearchParamsToForward";
|
||||
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { isAuthorizedToViewFormOnOrgDomain } from "@calcom/features/routing-forms/lib/isAuthorizedToViewForm";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { PrismaRoutingFormRepository } from "@calcom/lib/server/repository/PrismaRoutingFormRepository";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
|
||||
import { getRoutedUrl } from "./getRoutedUrl";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("@calcom/lib/checkRateLimitAndThrowError");
|
||||
vi.mock("@calcom/app-store/routing-forms/lib/handleResponse");
|
||||
vi.mock("@calcom/lib/server/repository/PrismaRoutingFormRepository");
|
||||
vi.mock("@calcom/lib/server/repository/user", () => {
|
||||
return {
|
||||
UserRepository: vi.fn().mockImplementation(() => ({
|
||||
enrichUserWithItsProfile: vi.fn(),
|
||||
})),
|
||||
};
|
||||
});
|
||||
vi.mock("@calcom/features/ee/organizations/lib/orgDomains");
|
||||
vi.mock("@calcom/features/routing-forms/lib/isAuthorizedToViewForm");
|
||||
vi.mock("@calcom/app-store/routing-forms/lib/getSerializableForm");
|
||||
vi.mock("@calcom/app-store/routing-forms/lib/getResponseToStore");
|
||||
vi.mock("@calcom/app-store/routing-forms/lib/processRoute");
|
||||
vi.mock("@calcom/app-store/routing-forms/lib/substituteVariables");
|
||||
vi.mock("@calcom/app-store/routing-forms/pages/routing-link/getUrlSearchParamsToForward");
|
||||
vi.mock("@calcom/app-store/routing-forms/getEventTypeRedirectUrl");
|
||||
vi.mock("@calcom/app-store/routing-forms/enrichFormWithMigrationData", () => ({
|
||||
enrichFormWithMigrationData: vi.fn((form) => form),
|
||||
}));
|
||||
vi.mock("@calcom/lib/sentryWrapper", () => ({
|
||||
withReporting: (fn: unknown) => fn,
|
||||
}));
|
||||
|
||||
const mockForm = {
|
||||
id: "form-id",
|
||||
user: { id: 1, name: "Test User" },
|
||||
team: null,
|
||||
name: "Test Form",
|
||||
fields: [],
|
||||
routes: [],
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
description: null,
|
||||
enabled: true,
|
||||
isDefault: false,
|
||||
fieldsOrder: [],
|
||||
position: 0,
|
||||
slug: "test-form",
|
||||
};
|
||||
|
||||
const mockSerializableForm = {
|
||||
id: "form-id",
|
||||
fields: [{ id: "email", type: "email", label: "Email", identifier: "email" }],
|
||||
routes: [],
|
||||
user: { id: 1 },
|
||||
};
|
||||
|
||||
const mockContext = (
|
||||
query: Record<string, unknown>,
|
||||
url = "/link/form-id"
|
||||
): Pick<GetServerSidePropsContext, "query" | "req"> => ({
|
||||
query: { form: "form-id", ...query },
|
||||
req: { url },
|
||||
});
|
||||
|
||||
describe("getRoutedUrl", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
// Provide default mock implementations
|
||||
vi.mocked(orgDomainConfig).mockReturnValue({ currentOrgDomain: null, isValidOrgDomain: false });
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(null);
|
||||
|
||||
const mockEnrichUserWithItsProfile = vi.fn().mockImplementation(async ({ user }) => user);
|
||||
const mockUserRepository = vi.mocked(UserRepository);
|
||||
if (mockUserRepository && typeof mockUserRepository.mockImplementation === "function") {
|
||||
mockUserRepository.mockImplementation(
|
||||
() =>
|
||||
({
|
||||
enrichUserWithItsProfile: mockEnrichUserWithItsProfile,
|
||||
} as any)
|
||||
);
|
||||
}
|
||||
vi.mocked(isAuthorizedToViewFormOnOrgDomain).mockReturnValue(true);
|
||||
vi.mocked(getSerializableForm).mockResolvedValue(mockSerializableForm as never);
|
||||
vi.mocked(findMatchingRoute).mockReturnValue(null);
|
||||
vi.mocked(handleResponse).mockResolvedValue({
|
||||
teamMembersMatchingAttributeLogic: null,
|
||||
formResponse: { id: 1 },
|
||||
queuedFormResponse: null,
|
||||
attributeRoutingConfig: null,
|
||||
timeTaken: {},
|
||||
crmContactOwnerEmail: null,
|
||||
crmContactOwnerRecordType: null,
|
||||
crmAppSlug: null,
|
||||
isPreview: false,
|
||||
});
|
||||
vi.mocked(substituteVariables).mockImplementation((value) => value);
|
||||
vi.mocked(getUrlSearchParamsToForward).mockReturnValue(new URLSearchParams());
|
||||
vi.mocked(getAbsoluteEventTypeRedirectUrlWithEmbedSupport).mockImplementation(
|
||||
({ eventTypeRedirectUrl }) => eventTypeRedirectUrl
|
||||
);
|
||||
vi.mocked(getResponseToStore).mockReturnValue({ email: "[email protected]" });
|
||||
});
|
||||
|
||||
it("should return notFound if query params are invalid", async () => {
|
||||
const context = {
|
||||
query: { wrong_param: "value" }, // 'form' is missing
|
||||
req: { url: "/link/form-id" },
|
||||
};
|
||||
// @ts-expect-error we are testing invalid input
|
||||
const result = await getRoutedUrl(context);
|
||||
expect(result).toEqual({ notFound: true });
|
||||
});
|
||||
|
||||
it("should return notFound if form is not found", async () => {
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(null);
|
||||
const context = mockContext({});
|
||||
|
||||
const result = await getRoutedUrl(context);
|
||||
expect(result).toEqual({ notFound: true });
|
||||
expect(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).toHaveBeenCalledWith("form-id");
|
||||
});
|
||||
|
||||
it("should return notFound if user is not authorized", async () => {
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(
|
||||
mockForm as never
|
||||
);
|
||||
vi.mocked(isAuthorizedToViewFormOnOrgDomain).mockReturnValue(false);
|
||||
|
||||
const context = mockContext({});
|
||||
const result = await getRoutedUrl(context);
|
||||
|
||||
expect(result).toEqual({ notFound: true });
|
||||
expect(isAuthorizedToViewFormOnOrgDomain).toHaveBeenCalledWith({
|
||||
user: mockForm.user,
|
||||
team: mockForm.team,
|
||||
currentOrgDomain: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw an error if no matching route is found", async () => {
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(
|
||||
mockForm as never
|
||||
);
|
||||
vi.mocked(getSerializableForm).mockResolvedValue(mockSerializableForm as never);
|
||||
vi.mocked(findMatchingRoute).mockReturnValue(null);
|
||||
|
||||
const context = mockContext({});
|
||||
await expect(getRoutedUrl(context)).rejects.toThrow("No matching route could be found");
|
||||
expect(findMatchingRoute).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
form: mockSerializableForm,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should return props with a message for customPageMessage action", async () => {
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(
|
||||
mockForm as never
|
||||
);
|
||||
const message = "This is a custom message";
|
||||
const mockRoute = { id: "route1", action: { type: "customPageMessage", value: message } };
|
||||
vi.mocked(findMatchingRoute).mockReturnValue(mockRoute as never);
|
||||
|
||||
const context = mockContext({});
|
||||
const result = await getRoutedUrl(context);
|
||||
|
||||
expect(result).toEqual({
|
||||
props: {
|
||||
isEmbed: false,
|
||||
form: mockSerializableForm,
|
||||
message: message,
|
||||
errorMessage: null,
|
||||
},
|
||||
});
|
||||
expect(handleResponse).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
form: mockSerializableForm,
|
||||
})
|
||||
);
|
||||
expect(findMatchingRoute).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
form: mockSerializableForm,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should return a redirect for eventTypeRedirectUrl action and substitute variables", async () => {
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(
|
||||
mockForm as never
|
||||
);
|
||||
const redirectUrl = "test-user/30min/{email}";
|
||||
const mockRoute = { id: "route1", action: { type: "eventTypeRedirectUrl", value: redirectUrl } };
|
||||
vi.mocked(findMatchingRoute).mockReturnValue(mockRoute as never);
|
||||
const substitutedUrl = "test-user/30min/[email protected]";
|
||||
vi.mocked(substituteVariables).mockReturnValue(substitutedUrl);
|
||||
vi.mocked(getAbsoluteEventTypeRedirectUrlWithEmbedSupport).mockReturnValue(`/${substitutedUrl}`);
|
||||
|
||||
const context = mockContext({ email: "[email protected]" });
|
||||
const result = await getRoutedUrl(context);
|
||||
|
||||
expect(substituteVariables).toHaveBeenCalledWith(
|
||||
redirectUrl,
|
||||
{ email: "[email protected]" },
|
||||
mockSerializableForm.fields
|
||||
);
|
||||
expect(getUrlSearchParamsToForward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
searchParams: expect.any(URLSearchParams),
|
||||
formResponse: { email: "[email protected]" },
|
||||
fields: mockSerializableForm.fields,
|
||||
})
|
||||
);
|
||||
expect(getAbsoluteEventTypeRedirectUrlWithEmbedSupport).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
eventTypeRedirectUrl: substitutedUrl,
|
||||
})
|
||||
);
|
||||
expect(result).toEqual({
|
||||
redirect: {
|
||||
destination: `/${substitutedUrl}`,
|
||||
permanent: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should return a redirect for externalRedirectUrl action", async () => {
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(
|
||||
mockForm as never
|
||||
);
|
||||
const redirectUrl = "https://example.com";
|
||||
const mockRoute = { id: "route1", action: { type: "externalRedirectUrl", value: redirectUrl } };
|
||||
vi.mocked(findMatchingRoute).mockReturnValue(mockRoute as never);
|
||||
|
||||
const context = mockContext({ email: "[email protected]" });
|
||||
const result = await getRoutedUrl(context);
|
||||
|
||||
const searchParams = new URLSearchParams({
|
||||
...(context.query as Record<string, string>),
|
||||
"cal.action": "externalRedirectUrl",
|
||||
});
|
||||
expect(result).toEqual({
|
||||
redirect: {
|
||||
destination: `${redirectUrl}?${searchParams.toString()}`,
|
||||
permanent: false,
|
||||
},
|
||||
});
|
||||
expect(findMatchingRoute).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
form: mockSerializableForm,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should call handleResponse with correct response prop obtained from getResponseToStore", async () => {
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(
|
||||
mockForm as never
|
||||
);
|
||||
const redirectUrl = "test-user/30min";
|
||||
const mockRoute = { id: "route1", action: { type: "eventTypeRedirectUrl", value: redirectUrl } };
|
||||
vi.mocked(findMatchingRoute).mockReturnValue(mockRoute as never);
|
||||
vi.mocked(getAbsoluteEventTypeRedirectUrlWithEmbedSupport).mockReturnValue(`/${redirectUrl}`);
|
||||
vi.mocked(getResponseToStore).mockReturnValue({ "xxx-xxx": { value: "[email protected]" } } as never);
|
||||
|
||||
const context = mockContext({ email: "[email protected]" });
|
||||
await getRoutedUrl(context);
|
||||
|
||||
expect(getResponseToStore).toHaveBeenCalledWith({
|
||||
formFields: mockSerializableForm.fields,
|
||||
fieldsResponses: { email: "[email protected]" },
|
||||
});
|
||||
|
||||
expect(handleResponse).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ response: { "xxx-xxx": { value: "[email protected]" } } })
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw an error if rate limit is exceeded", async () => {
|
||||
vi.mocked(checkRateLimitAndThrowError).mockRejectedValue(new Error("Rate limit exceeded"));
|
||||
const context = mockContext({ email: "[email protected]" });
|
||||
const expectedHash = createHash("sha256")
|
||||
.update(JSON.stringify({ email: "[email protected]" }))
|
||||
.digest("hex");
|
||||
|
||||
await expect(getRoutedUrl(context)).rejects.toThrow("Rate limit exceeded");
|
||||
expect(checkRateLimitAndThrowError).toHaveBeenCalledWith({
|
||||
identifier: `form:form-id:hash:${expectedHash}`,
|
||||
});
|
||||
});
|
||||
|
||||
describe("Dry Run", () => {
|
||||
it("should call handleResponse with isPreview:true", async () => {
|
||||
vi.mocked(PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg).mockResolvedValue(
|
||||
mockForm as never
|
||||
);
|
||||
const redirectUrl = "test-user/30min";
|
||||
const mockRoute = { id: "route1", action: { type: "eventTypeRedirectUrl", value: redirectUrl } };
|
||||
vi.mocked(findMatchingRoute).mockReturnValue(mockRoute as never);
|
||||
vi.mocked(getAbsoluteEventTypeRedirectUrlWithEmbedSupport).mockReturnValue(`/${redirectUrl}`);
|
||||
|
||||
const context = mockContext({ "cal.isBookingDryRun": "true" });
|
||||
await getRoutedUrl(context);
|
||||
|
||||
expect(handleResponse).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
isPreview: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
// !IMPORTANT! changes to this file requires publishing new version of platform libraries in order for the changes to be applied to APIV2
|
||||
import { createHash } from "crypto";
|
||||
import type { GetServerSidePropsContext } from "next";
|
||||
import { stringify } from "querystring";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import z from "zod";
|
||||
|
||||
import { enrichFormWithMigrationData } from "@calcom/app-store/routing-forms/enrichFormWithMigrationData";
|
||||
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 { 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 { getUrlSearchParamsToForward } from "@calcom/app-store/routing-forms/pages/routing-link/getUrlSearchParamsToForward";
|
||||
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 { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
import { PrismaRoutingFormRepository } from "@calcom/lib/server/repository/PrismaRoutingFormRepository";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[routing-forms]", "[router]"] });
|
||||
const querySchema = z
|
||||
.object({
|
||||
form: z.string(),
|
||||
})
|
||||
.catchall(z.string().or(z.array(z.string())));
|
||||
|
||||
const getDeterministicHashForResponse = (fieldsResponses: Record<string, unknown>) => {
|
||||
const sortedFields = Object.keys(fieldsResponses)
|
||||
.sort()
|
||||
.reduce((obj: Record<string, unknown>, key) => {
|
||||
obj[key] = fieldsResponses[key];
|
||||
return obj;
|
||||
}, {});
|
||||
const paramsString = JSON.stringify(sortedFields);
|
||||
const hash = createHash("sha256").update(paramsString).digest("hex");
|
||||
return hash;
|
||||
};
|
||||
|
||||
export function hasEmbedPath(pathWithQuery: string) {
|
||||
const onlyPath = pathWithQuery.split("?")[0];
|
||||
return onlyPath.endsWith("/embed") || onlyPath.endsWith("/embed/");
|
||||
}
|
||||
|
||||
// We have fetchCrm as configurable temporarily to allow us to test the CRM logic in the APIV2. Soon after we would hardcode it to true
|
||||
const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" | "req">, fetchCrm = false) => {
|
||||
const queryParsed = querySchema.safeParse(context.query);
|
||||
const isEmbed = hasEmbedPath(context.req.url || "");
|
||||
const pageProps = {
|
||||
isEmbed,
|
||||
};
|
||||
|
||||
if (!queryParsed.success) {
|
||||
log.warn("Error parsing query", { issues: queryParsed.error.issues });
|
||||
return {
|
||||
notFound: true,
|
||||
};
|
||||
}
|
||||
|
||||
// TODO: Known params reserved by Cal.com are form, embed, layout and other cal. prefixed params. We should exclude all of them from fieldsResponses.
|
||||
// But they must be present in `paramsToBeForwardedAsIs` as they could be needed by Booking Page as well.
|
||||
const {
|
||||
form: formId,
|
||||
"cal.isBookingDryRun": isBookingDryRunParam,
|
||||
"cal.queueFormResponse": queueFormResponseParam,
|
||||
...fieldsResponses
|
||||
} = queryParsed.data;
|
||||
|
||||
const responseHash = getDeterministicHashForResponse(fieldsResponses);
|
||||
|
||||
await checkRateLimitAndThrowError({
|
||||
identifier: `form:${formId}:hash:${responseHash}`,
|
||||
});
|
||||
|
||||
const isBookingDryRun = isBookingDryRunParam === "true";
|
||||
const shouldQueueFormResponse = queueFormResponseParam === "true";
|
||||
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),
|
||||
};
|
||||
|
||||
const { currentOrgDomain } = orgDomainConfig(context.req);
|
||||
|
||||
let timeTaken: Record<string, number | null> = {};
|
||||
|
||||
const formQueryStart = performance.now();
|
||||
const form = await PrismaRoutingFormRepository.findFormByIdIncludeUserTeamAndOrg(formId);
|
||||
timeTaken.formQuery = performance.now() - formQueryStart;
|
||||
|
||||
if (!form) {
|
||||
return {
|
||||
notFound: true,
|
||||
};
|
||||
}
|
||||
|
||||
const profileEnrichmentStart = performance.now();
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const formWithUserProfile = {
|
||||
...form,
|
||||
user: await userRepo.enrichUserWithItsProfile({ user: form.user }),
|
||||
};
|
||||
timeTaken.profileEnrichment = performance.now() - profileEnrichmentStart;
|
||||
|
||||
if (
|
||||
!isAuthorizedToViewFormOnOrgDomain({ user: formWithUserProfile.user, currentOrgDomain, team: form.team })
|
||||
) {
|
||||
return {
|
||||
notFound: true,
|
||||
};
|
||||
}
|
||||
|
||||
const getSerializableFormStart = performance.now();
|
||||
const serializableForm = await getSerializableForm({
|
||||
form: enrichFormWithMigrationData(formWithUserProfile),
|
||||
});
|
||||
timeTaken.getSerializableForm = performance.now() - getSerializableFormStart;
|
||||
|
||||
if (!serializableForm.fields) {
|
||||
throw new Error("Form has no fields");
|
||||
}
|
||||
const response: FormResponse = getResponseToStore({
|
||||
formFields: serializableForm.fields,
|
||||
fieldsResponses,
|
||||
});
|
||||
|
||||
const matchingRoute = findMatchingRoute({ form: serializableForm, response });
|
||||
if (!matchingRoute) {
|
||||
throw new Error("No matching route could be found");
|
||||
}
|
||||
|
||||
const decidedAction = matchingRoute.action;
|
||||
|
||||
let teamMembersMatchingAttributeLogic = null;
|
||||
let formResponseId = null;
|
||||
let attributeRoutingConfig = null;
|
||||
let crmContactOwnerEmail: string | null = null;
|
||||
let crmContactOwnerRecordType: string | null = null;
|
||||
let crmAppSlug: string | null = null;
|
||||
let queuedFormResponseId;
|
||||
try {
|
||||
const result = await handleResponse({
|
||||
form: serializableForm,
|
||||
formFillerId: uuidv4(),
|
||||
response: response,
|
||||
identifierKeyedResponse: fieldsResponses,
|
||||
chosenRouteId: matchingRoute.id,
|
||||
isPreview: isBookingDryRun,
|
||||
queueFormResponse: shouldQueueFormResponse,
|
||||
fetchCrm,
|
||||
});
|
||||
teamMembersMatchingAttributeLogic = result.teamMembersMatchingAttributeLogic;
|
||||
formResponseId = result.formResponse?.id;
|
||||
queuedFormResponseId = result.queuedFormResponse?.id;
|
||||
attributeRoutingConfig = result.attributeRoutingConfig;
|
||||
timeTaken = {
|
||||
...timeTaken,
|
||||
...result.timeTaken,
|
||||
};
|
||||
crmContactOwnerEmail = result.crmContactOwnerEmail;
|
||||
crmContactOwnerRecordType = result.crmContactOwnerRecordType;
|
||||
crmAppSlug = result.crmAppSlug;
|
||||
} catch (e) {
|
||||
if (e instanceof TRPCError) {
|
||||
return {
|
||||
props: {
|
||||
...pageProps,
|
||||
form: serializableForm,
|
||||
message: null,
|
||||
errorMessage: e.message,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
log.error("Error handling the response", safeStringify(e));
|
||||
throw new Error("Error handling the response");
|
||||
}
|
||||
|
||||
// TODO: To be done using sentry tracing
|
||||
console.log("Server-Timing", getServerTimingHeader(timeTaken));
|
||||
|
||||
//TODO: Maybe take action after successful mutation
|
||||
if (decidedAction.type === "customPageMessage") {
|
||||
return {
|
||||
props: {
|
||||
...pageProps,
|
||||
form: serializableForm,
|
||||
message: decidedAction.value,
|
||||
errorMessage: null,
|
||||
},
|
||||
};
|
||||
} else if (decidedAction.type === "eventTypeRedirectUrl") {
|
||||
const eventTypeUrlWithResolvedVariables = substituteVariables(
|
||||
decidedAction.value,
|
||||
response,
|
||||
serializableForm.fields
|
||||
);
|
||||
return {
|
||||
redirect: {
|
||||
destination: getAbsoluteEventTypeRedirectUrlWithEmbedSupport({
|
||||
eventTypeRedirectUrl: eventTypeUrlWithResolvedVariables,
|
||||
form: serializableForm,
|
||||
allURLSearchParams: getUrlSearchParamsToForward({
|
||||
formResponse: response,
|
||||
fields: serializableForm.fields,
|
||||
searchParams: new URLSearchParams(
|
||||
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,
|
||||
}),
|
||||
isEmbed: pageProps.isEmbed,
|
||||
}),
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
} else if (decidedAction.type === "externalRedirectUrl") {
|
||||
return {
|
||||
redirect: {
|
||||
destination: `${decidedAction.value}?${stringify(context.query)}&cal.action=externalRedirectUrl`,
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// TODO: Consider throwing error here as there is no value of decidedAction.type that would cause the flow to be here
|
||||
return {
|
||||
props: {
|
||||
...pageProps,
|
||||
form: serializableForm,
|
||||
message: null,
|
||||
errorMessage: "Unhandled type of action",
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const getRoutedUrl = withReporting(_getRoutedUrl, "getRoutedUrl");
|
||||
Reference in new issue
Block a user