refactor: remove circular dependency between appstore and trpc (#23768)

* mv PaymentPage to web

* mv 2 more components to web

* refactor

* update imports

* mv

* revert

* fix

* fix

* update

* migrate relevant test too

* move setup components to web from appstore

* move wipemycalother

* mv

* fix typechecks

* mv more routing forms components

* fix

* fix

* fix

* fix: resolve type errors in SingleForm.tsx after migration

- Updated SingleFormComponentProps type to include enriched form properties
- Added proper typing for user, team, nonOrgUsername, nonOrgTeamslug, userOrigin, teamOrigin
- Fixes type errors that occurred after migrating SingleForm.tsx from packages/app-store/routing-forms/components/
- Resolves both SingleForm.tsx and TestForm.tsx type errors

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

* delete

* refactors

* fix

* fix

* fix

* remove usage of trpc client from OmniInstallAppButton.tsx

* fix test

* import only type

* fix test

* remove trpc package from appstore package.json

* remove remaining trpc usage

* update test

* fix type checks

* fix errors

* fix

* make it error

* nit

---------

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-09-14 12:51:05 +00:00
1 parent 06fcea4116
commit 76bba1ca05
99 files changed
+728 -634

No files matched your search

@@ -1,202 +0,0 @@
"use client";
import classNames from "classnames";
import dynamic from "next/dynamic";
import type { FC } from "react";
import { useEffect, useState } from "react";
import { getSuccessPageLocationMessage } from "@calcom/app-store/locations";
import dayjs from "@calcom/dayjs";
import { sdkActionManager, useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { PayIcon } from "@calcom/features/bookings/components/event-meta/PayIcon";
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
import { APP_NAME, WEBSITE_URL } from "@calcom/lib/constants";
import { getPaymentAppData } from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useTheme from "@calcom/lib/hooks/useTheme";
import { getIs24hClockFromLocalStorage, isBrowserLocale24h } from "@calcom/lib/timeFormat";
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
import { localStorage } from "@calcom/lib/webstorage";
import type { PaymentPageProps } from "../pages/payment";
const StripePaymentComponent = dynamic(() => import("./Payment"), {
ssr: false,
});
const PaypalPaymentComponent = dynamic(
() =>
import("@calcom/app-store/paypal/components/PaypalPaymentComponent").then(
(m) => m.PaypalPaymentComponent
),
{
ssr: false,
}
);
const AlbyPaymentComponent = dynamic(
() => import("@calcom/app-store/alby/components/AlbyPaymentComponent").then((m) => m.AlbyPaymentComponent),
{
ssr: false,
}
);
const HitpayPaymentComponent = dynamic(
() =>
import("@calcom/app-store/hitpay/components/HitpayPaymentComponent").then(
(m) => m.HitpayPaymentComponent
),
{
ssr: false,
}
);
const BtcpayPaymentComponent = dynamic(
() =>
import("@calcom/app-store/btcpayserver/components/BtcpayPaymentComponent").then(
(m) => m.BtcpayPaymentComponent
),
{
ssr: false,
}
);
const PaymentPage: FC<PaymentPageProps> = (props) => {
const { t, i18n } = useLocale();
const [is24h, setIs24h] = useState(isBrowserLocale24h());
const [date, setDate] = useState(dayjs.utc(props.booking.startTime));
const [timezone, setTimezone] = useState<string | null>(null);
useTheme(props.profile.theme);
const isEmbed = useIsEmbed();
const paymentAppData = getPaymentAppData(props.eventType);
useEffect(() => {
let embedIframeWidth = 0;
const _timezone = localStorage.getItem("timeOption.preferredTimeZone") || CURRENT_TIMEZONE;
setTimezone(_timezone);
setDate(date.tz(_timezone));
setIs24h(!!getIs24hClockFromLocalStorage());
if (isEmbed) {
requestAnimationFrame(function fixStripeIframe() {
// HACK: Look for stripe iframe and center position it just above the embed content
const stripeIframeWrapper = document.querySelector(
'iframe[src*="https://js.stripe.com/v3/authorize-with-url-inner"]'
)?.parentElement;
if (stripeIframeWrapper) {
stripeIframeWrapper.style.margin = "0 auto";
stripeIframeWrapper.style.width = `${embedIframeWidth}px`;
}
requestAnimationFrame(fixStripeIframe);
});
sdkActionManager?.on("__dimensionChanged", (e) => {
embedIframeWidth = e.detail.data.iframeWidth as number;
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isEmbed]);
const eventName = props.booking.title;
return (
<div className="h-screen">
<main className="mx-auto max-w-3xl py-24">
<div className="fixed inset-0 z-50 overflow-y-auto scroll-auto">
<div className="flex min-h-screen items-end justify-center px-4 pb-20 pt-4 text-center sm:block sm:p-0">
<div className="inset-0 my-4 transition-opacity sm:my-0" aria-hidden="true">
<span className="hidden sm:inline-block sm:h-screen sm:align-middle" aria-hidden="true">
&#8203;
</span>
<div
className={classNames(
"main bg-default border-subtle inline-block transform overflow-hidden rounded-lg border px-8 pb-4 pt-5 text-left align-bottom transition-all sm:w-full sm:max-w-lg sm:py-6 sm:align-middle",
isEmbed ? "" : "sm:my-8"
)}
role="dialog"
aria-modal="true"
aria-labelledby="modal-headline">
<div>
<div className="bg-success mx-auto flex h-12 w-12 items-center justify-center rounded-full">
<PayIcon currency={paymentAppData.currency} className="h-8 w-8 text-green-600" />
</div>
<div className="mt-3 text-center sm:mt-5">
<h3 className="text-emphasis text-2xl font-semibold leading-6" id="modal-headline">
{paymentAppData.paymentOption === "HOLD" ? t("complete_your_booking") : t("payment")}
</h3>
<div className="text-default mt-4 grid grid-cols-3 border-b border-t py-4 text-left dark:border-gray-900 dark:text-gray-300">
<div className="font-medium">{t("what")}</div>
<div className="col-span-2 mb-6">{eventName}</div>
<div className="font-medium">{t("when")}</div>
<div className="col-span-2 mb-6">
{date.locale(i18n.language ?? "en").format("dddd, DD MMMM YYYY")}
<br />
{date.format(is24h ? "H:mm" : "h:mma")} - {props.eventType.length} mins{" "}
<span className="text-subtle">({timezone})</span>
</div>
{props.booking.location && (
<>
<div className="font-medium">{t("where")}</div>
<div className="col-span-2 mb-6">
{getSuccessPageLocationMessage(props.booking.location, t)}
</div>
</>
)}
<div className="font-medium">
{props.payment.paymentOption === "HOLD" ? t("no_show_fee") : t("price")}
</div>
<div className="col-span-2 mb-6 font-semibold">
<Price
currency={paymentAppData.currency}
price={paymentAppData.price}
displayAlternateSymbol={false}
/>
</div>
</div>
</div>
</div>
<div>
{props.payment.success && !props.payment.refunded && (
<div className="text-default mt-4 text-center dark:text-gray-300">{t("paid")}</div>
)}
{props.payment.appId === "stripe" && !props.payment.success && (
<StripePaymentComponent
clientSecret={props.clientSecret}
payment={props.payment}
eventType={props.eventType}
user={props.user}
location={props.booking.location}
booking={props.booking}
/>
)}
{props.payment.appId === "paypal" && !props.payment.success && (
<PaypalPaymentComponent payment={props.payment} />
)}
{props.payment.appId === "alby" && !props.payment.success && (
<AlbyPaymentComponent payment={props.payment} paymentPageProps={props} />
)}
{props.payment.appId === "hitpay" && !props.payment.success && (
<HitpayPaymentComponent payment={props.payment} />
)}
{props.payment.appId === "btcpayserver" && !props.payment.success && (
<BtcpayPaymentComponent payment={props.payment} paymentPageProps={props} />
)}
{props.payment.refunded && (
<div className="text-default mt-4 text-center dark:text-gray-300">{t("refunded")}</div>
)}
</div>
{!props.profile.hideBranding && (
<div className="text-muted dark:text-inverted mt-4 border-t pt-4 text-center text-xs dark:border-gray-900">
<a href={`${WEBSITE_URL}/signup`}>
{t("create_booking_link_with_calcom", { appName: APP_NAME })}
</a>
</div>
)}
</div>
</div>
</div>
</div>
</main>
</div>
);
};
export default PaymentPage;
@@ -25,6 +25,8 @@ export const EventAppsTab = ({ eventType }: { eventType: EventType }) => {
teamId: eventType.team?.id || eventType.parent?.teamId,
});
const utils = trpc.useUtils();
const formMethods = useFormContext<FormValues>();
const installedApps =
eventTypeApps?.items.filter((app) => app.userCredentialIds.length || app.teams.length) || [];
@@ -41,6 +43,14 @@ export const EventAppsTab = ({ eventType }: { eventType: EventType }) => {
const appsDisableProps = shouldLockDisableProps("apps", { simple: true });
const lockedText = appsDisableProps.isLocked ? "locked" : "unlocked";
const handleAppInstallSuccess = (appId: string) => () => {
utils.viewer.apps.appById.invalidate({ appId });
utils.viewer.apps.integrations.invalidate({
extendsFeature: "EventType",
...(eventType.team?.id && { teamId: eventType.team.id }),
});
};
const appsWithTeamCredentials = eventTypeApps?.items.filter((app) => app.teams.length) || [];
const cardsForAppsWithTeams = appsWithTeamCredentials.map((app) => {
const appCards = [];
@@ -58,6 +68,7 @@ export const EventAppsTab = ({ eventType }: { eventType: EventType }) => {
app={app}
eventType={eventType}
eventTypeFormMetadata={eventTypeFormMetadata}
onAppInstallSuccess={handleAppInstallSuccess(app.slug)}
/>
);
}
@@ -82,6 +93,7 @@ export const EventAppsTab = ({ eventType }: { eventType: EventType }) => {
eventType={eventType}
eventTypeFormMetadata={eventTypeFormMetadata}
disabled={shouldLockDisableProps("apps").disabled}
onAppInstallSuccess={handleAppInstallSuccess(app.slug)}
/>
);
}
@@ -147,6 +159,7 @@ export const EventAppsTab = ({ eventType }: { eventType: EventType }) => {
app={app}
eventType={eventType}
eventTypeFormMetadata={eventTypeFormMetadata}
onAppInstallSuccess={handleAppInstallSuccess(app.slug)}
/>
);
})}
@@ -180,6 +193,7 @@ export const EventAppsTab = ({ eventType }: { eventType: EventType }) => {
app={app}
eventType={eventType}
eventTypeFormMetadata={eventTypeFormMetadata}
onAppInstallSuccess={handleAppInstallSuccess(app.slug)}
/>
))}
</div>
@@ -10,7 +10,6 @@ import { getSerializableForm } from "@calcom/app-store/routing-forms/lib/getSeri
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";
@@ -18,8 +17,10 @@ import { PrismaRoutingFormRepository } from "@calcom/lib/server/repository/Prism
import { UserRepository } from "@calcom/lib/server/repository/user";
import { getRoutedUrl } from "./getRoutedUrl";
import { getUrlSearchParamsToForward } from "./getUrlSearchParamsToForward";
// Mock dependencies
vi.mock("./getUrlSearchParamsToForward");
vi.mock("@calcom/lib/checkRateLimitAndThrowError");
vi.mock("@calcom/app-store/routing-forms/lib/handleResponse");
vi.mock("@calcom/lib/server/repository/PrismaRoutingFormRepository");
@@ -36,7 +37,6 @@ 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),
@@ -13,7 +13,6 @@ import { getServerTimingHeader } from "@calcom/app-store/routing-forms/lib/getSe
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";
@@ -27,6 +26,8 @@ import prisma from "@calcom/prisma";
import { TRPCError } from "@trpc/server";
import { getUrlSearchParamsToForward } from "./getUrlSearchParamsToForward";
const log = logger.getSubLogger({ prefix: ["[routing-forms]", "[router]"] });
const querySchema = z
.object({
@@ -0,0 +1,353 @@
import { v4 as uuidv4 } from "uuid";
import { describe, it, expect } from "vitest";
import { getUrlSearchParamsToForward } from "./getUrlSearchParamsToForward";
function fromEntriesWithDuplicateKeys(entries: IterableIterator<[string, string]> | null) {
const result: Record<string, string | string[]> = {};
if (entries === null) {
return result;
}
// Consider setting atleast ES2015 as target
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
for (const [key, value] of entries) {
if (result.hasOwnProperty(key)) {
let currentValue = result[key];
if (!Array.isArray(currentValue)) {
currentValue = [currentValue];
}
currentValue.push(value);
result[key] = currentValue;
} else {
result[key] = value;
}
}
return result;
}
describe("getUrlSearchParamsToForward", () => {
it("should build query params from response correctly when identifier is present in fields", () => {
const field1Id = uuidv4();
const field2Id = uuidv4();
const formResponse = {
[field1Id]: { value: "value1", label: "Field 1" },
[field2Id]: { value: ["option1", "option2"], label: "Field 2" },
};
const fields = [
{ id: field1Id, identifier: "f1", type: "text", label: "Field 1" },
{
id: field2Id,
identifier: "f2",
label: "Field 2",
type: "multiselect",
options: [
{ id: "option1", label: "Option 1" },
{ id: "option2", label: "Option 2" },
],
},
];
const searchParams = new URLSearchParams("?query1=value1&query2=value2");
const expectedParams = {
f1: "value1",
f2: ["Option 1", "Option 2"],
query1: "value1",
query2: "value2",
"cal.routingFormResponseId": "1",
};
const result = getUrlSearchParamsToForward({
formResponse,
fields,
searchParams,
teamMembersMatchingAttributeLogic: null,
formResponseId: 1,
queuedFormResponseId: null,
attributeRoutingConfig: null,
});
expect(fromEntriesWithDuplicateKeys(result.entries())).toEqual(expectedParams);
});
it("should build query params from response correctly when identifier is not present in fields. Should fallback to label", () => {
const field1Id = uuidv4();
const field2Id = uuidv4();
const formResponse = {
[field1Id]: { value: "value1" },
[field2Id]: { value: "value2" },
};
const fields = [
{ id: field1Id, label: "Field 1", type: "text" },
{ id: field2Id, label: "Field 2", type: "text" },
];
const searchParams = new URLSearchParams("?query1=value1&query2=value2");
const expectedParams = {
"Field 1": "value1",
"Field 2": "value2",
query1: "value1",
query2: "value2",
"cal.routingFormResponseId": "1",
};
const result = getUrlSearchParamsToForward({
formResponse,
fields,
searchParams,
teamMembersMatchingAttributeLogic: null,
formResponseId: 1,
queuedFormResponseId: null,
attributeRoutingConfig: null,
});
expect(fromEntriesWithDuplicateKeys(result.entries())).toEqual(expectedParams);
});
it("should handle select fields correctly when options have id set", () => {
const field1Id = uuidv4();
const field2Id = uuidv4();
const formResponse = {
[field1Id]: { value: "Option 1" },
[field2Id]: { value: ["Option 1", "Option 2"] },
};
const fields = [
{
id: field1Id,
label: "Field 1",
type: "select",
options: [
{ id: "option1", label: "Option 1" },
{ id: "option2", label: "Option 2" },
],
},
{
id: field2Id,
label: "Field 2",
type: "multiselect",
options: [
{ id: "option1", label: "Option 1" },
{ id: "option2", label: "Option 2" },
{ id: "option3", label: "Option 3" },
],
},
];
const searchParams = new URLSearchParams("?query1=value1&query2=value2");
const expectedParams = {
"Field 1": "Option 1",
"Field 2": ["Option 1", "Option 2"],
query1: "value1",
query2: "value2",
"cal.routingFormResponseId": "1",
};
const result = getUrlSearchParamsToForward({
formResponse,
fields,
searchParams,
teamMembersMatchingAttributeLogic: null,
formResponseId: 1,
queuedFormResponseId: null,
attributeRoutingConfig: null,
});
expect(fromEntriesWithDuplicateKeys(result.entries())).toEqual(expectedParams);
});
it("should handle select fields correctly when options have no id set(Legacy options)", () => {
const field1Id = uuidv4();
const field2Id = uuidv4();
const formResponse = {
[field1Id]: { value: "Option 1" },
[field2Id]: { value: ["Option 1", "Option 2"] },
};
const fields = [
{
id: field1Id,
label: "Field 1",
type: "select",
options: [
{ id: null, label: "Option 1" },
{ id: null, label: "Option 2" },
],
},
{
id: field2Id,
label: "Field 2",
type: "multiselect",
options: [
{ id: "option1", label: "Option 1" },
{ id: "option2", label: "Option 2" },
{ id: "option3", label: "Option 3" },
],
},
];
const searchParams = new URLSearchParams("?query1=value1&query2=value2");
const expectedParams = {
"Field 1": "Option 1",
"Field 2": ["Option 1", "Option 2"],
query1: "value1",
query2: "value2",
"cal.routingFormResponseId": "1",
};
const result = getUrlSearchParamsToForward({
formResponse,
fields,
searchParams,
teamMembersMatchingAttributeLogic: null,
formResponseId: 1,
queuedFormResponseId: null,
attributeRoutingConfig: null,
});
expect(fromEntriesWithDuplicateKeys(result.entries())).toEqual(expectedParams);
});
it("should handle number values correctly", () => {
const field1Id = uuidv4();
const response = {
[field1Id]: { value: 123 },
};
const fields = [{ id: field1Id, label: "Field 1", type: "number" }];
const searchParams = new URLSearchParams("?query1=value1&query2=value2");
const expectedParams = {
"Field 1": "123",
query1: "value1",
query2: "value2",
"cal.routingFormResponseId": "1",
};
const result = getUrlSearchParamsToForward({
formResponse: response,
fields,
searchParams,
teamMembersMatchingAttributeLogic: null,
formResponseId: 1,
queuedFormResponseId: null,
attributeRoutingConfig: null,
});
expect(fromEntriesWithDuplicateKeys(result.entries())).toEqual(expectedParams);
});
it("should add cal.skipContactOwner when attributeRoutingConfig.skipContactOwner is true", () => {
const field1Id = uuidv4();
const field2Id = uuidv4();
const formResponse = {
[field1Id]: { value: "value1", label: "Field 1" },
[field2Id]: { value: ["option1", "option2"], label: "Field 2" },
};
const fields = [
{ id: field1Id, identifier: "f1", type: "text", label: "Field 1" },
{
id: field2Id,
identifier: "f2",
label: "Field 2",
type: "multiselect",
options: [
{ id: "option1", label: "Option 1" },
{ id: "option2", label: "Option 2" },
],
},
];
const searchParams = new URLSearchParams("?query1=value1&query2=value2");
const expectedParams = {
f1: "value1",
f2: ["Option 1", "Option 2"],
query1: "value1",
query2: "value2",
"cal.routingFormResponseId": "1",
"cal.skipContactOwner": "true",
};
const result = getUrlSearchParamsToForward({
formResponse,
fields,
searchParams,
teamMembersMatchingAttributeLogic: null,
formResponseId: 1,
queuedFormResponseId: null,
attributeRoutingConfig: {
skipContactOwner: true,
},
});
expect(fromEntriesWithDuplicateKeys(result.entries())).toEqual(expectedParams);
});
it("should add cal.routedTeamMemberIds to query params", () => {
const field1Id = uuidv4();
const field2Id = uuidv4();
const formResponse = {
[field1Id]: { value: "value1", label: "Field 1" },
[field2Id]: { value: ["option1", "option2"], label: "Field 2" },
};
const fields = [
{ id: field1Id, identifier: "f1", type: "text", label: "Field 1" },
{
id: field2Id,
identifier: "f2",
label: "Field 2",
type: "multiselect",
options: [
{ id: "option1", label: "Option 1" },
{ id: "option2", label: "Option 2" },
],
},
];
const searchParams = new URLSearchParams("?query1=value1&query2=value2");
const expectedParams = {
f1: "value1",
f2: ["Option 1", "Option 2"],
query1: "value1",
query2: "value2",
"cal.routingFormResponseId": "1",
"cal.routedTeamMemberIds": "1,2",
};
const result = getUrlSearchParamsToForward({
formResponse,
fields,
searchParams,
teamMembersMatchingAttributeLogic: [1, 2],
formResponseId: 1,
queuedFormResponseId: null,
attributeRoutingConfig: null,
});
expect(fromEntriesWithDuplicateKeys(result.entries())).toEqual(expectedParams);
});
describe("Dry Run", () => {
it("should add cal.routingFormResponseId=0 when formResponseId is 0", () => {
const searchParams = new URLSearchParams("?query1=value1&query2=value2");
const expectedParams = {
"cal.routingFormResponseId": "0",
query1: "value1",
query2: "value2",
};
const result = getUrlSearchParamsToForward({
formResponse: {},
fields: [],
searchParams,
teamMembersMatchingAttributeLogic: null,
formResponseId: 0,
queuedFormResponseId: null,
attributeRoutingConfig: null,
});
expect(fromEntriesWithDuplicateKeys(result.entries())).toEqual(expectedParams);
});
});
});
@@ -0,0 +1,204 @@
import { ROUTING_FORM_RESPONSE_ID_QUERY_STRING } from "@calcom/app-store/routing-forms/lib/constants";
import getFieldIdentifier from "@calcom/app-store/routing-forms/lib/getFieldIdentifier";
import type { FormResponse, LocalRoute } from "@calcom/app-store/routing-forms/types/types";
type FormResponseValueOnly = { [key: string]: { value: FormResponse[keyof FormResponse]["value"] } };
type AttributeRoutingConfig = NonNullable<LocalRoute["attributeRoutingConfig"]>;
type GetUrlSearchParamsToForwardOptions = {
formResponse: Record<
string,
{
value: number | string | string[];
}
>;
fields: {
id: string;
type: string;
label: string;
options?: {
id: string | null;
label: string;
}[];
identifier?: string;
}[];
searchParams: URLSearchParams;
formResponseId: number | null;
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;
};
export function getUrlSearchParamsToForward({
formResponse,
fields,
searchParams,
teamMembersMatchingAttributeLogic,
formResponseId,
queuedFormResponseId,
attributeRoutingConfig,
reroutingFormResponses,
teamId,
orgId,
crmContactOwnerEmail,
crmContactOwnerRecordType,
crmAppSlug,
}: GetUrlSearchParamsToForwardOptions) {
type Params = Record<string, string | string[]>;
const paramsFromResponse: Params = {};
const paramsFromCurrentUrl: Params = {};
// Build query params from response
Object.entries(formResponse).forEach(([key, fieldResponse]) => {
const foundField = fields.find((f) => f.id === key);
if (!foundField) {
// If for some reason, the field isn't there, let's just
return;
}
let valueAsStringOrStringArray =
typeof fieldResponse.value === "number" ? String(fieldResponse.value) : fieldResponse.value;
if (foundField.type === "select" || foundField.type === "multiselect") {
const options = foundField.options || [];
let arr =
valueAsStringOrStringArray instanceof Array
? valueAsStringOrStringArray
: [valueAsStringOrStringArray];
arr = arr.map((idOrLabel) => {
const foundOptionById = options.find((option) => {
return option.id === idOrLabel;
});
if (foundOptionById) {
return foundOptionById.label;
}
return idOrLabel;
});
valueAsStringOrStringArray = foundField.type === "select" ? arr[0] : arr;
}
paramsFromResponse[getFieldIdentifier(foundField) as keyof typeof paramsFromResponse] =
valueAsStringOrStringArray;
});
// Build query params from current URL. It excludes route params
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
for (const [name, value] of searchParams.entries()) {
const target = paramsFromCurrentUrl[name];
if (target instanceof Array) {
target.push(value);
} else {
paramsFromCurrentUrl[name] = [value];
}
}
const attributeRoutingConfigParams: Record<string, any> = {};
if (attributeRoutingConfig) {
for (const key of Object.keys(attributeRoutingConfig)) {
if (key === "skipContactOwner" && attributeRoutingConfig[key]) {
attributeRoutingConfigParams["cal.skipContactOwner"] = "true";
}
// TODO: How do we move this logic to their respective app packages
if (key === "salesforce") {
const salesforceData = attributeRoutingConfig[key];
if (salesforceData?.rrSkipToAccountLookupField && salesforceData.rrSKipToAccountLookupFieldName) {
attributeRoutingConfigParams["cal.salesforce.rrSkipToAccountLookupField"] = "true";
}
}
}
}
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,
...(teamMembersMatchingAttributeLogic
? { ["cal.routedTeamMemberIds"]: teamMembersMatchingAttributeLogic.join(",") }
: null),
...(typeof formResponseId === "number"
? { [ROUTING_FORM_RESPONSE_ID_QUERY_STRING]: String(formResponseId) }
: null),
...(queuedFormResponseId ? { ["cal.queuedFormResponseId"]: queuedFormResponseId } : null),
...attributeRoutingConfigParams,
...(reroutingFormResponses
? { ["cal.reroutingFormResponses"]: JSON.stringify(reroutingFormResponses) }
: null),
};
const allQueryURLSearchParams = new URLSearchParams();
// Make serializable URLSearchParams instance
Object.entries(allQueryParams).forEach(([param, value]) => {
const valueArray = value instanceof Array ? value : [value];
valueArray.forEach((v) => {
allQueryURLSearchParams.append(param, v);
});
});
return allQueryURLSearchParams;
}
export function getUrlSearchParamsToForwardForReroute({
formResponse,
formResponseId,
fields,
searchParams,
teamMembersMatchingAttributeLogic,
attributeRoutingConfig,
rescheduleUid,
reroutingFormResponses,
}: Omit<GetUrlSearchParamsToForwardOptions, "queuedFormResponseId"> & {
rescheduleUid: string;
reroutingFormResponses: FormResponseValueOnly;
}) {
searchParams.set("rescheduleUid", rescheduleUid);
searchParams.set("cal.rerouting", "true");
return getUrlSearchParamsToForward({
formResponse,
formResponseId,
// Queued form response id is not available in rerouting
queuedFormResponseId: null,
fields,
searchParams,
teamMembersMatchingAttributeLogic,
attributeRoutingConfig,
reroutingFormResponses,
});
}
export function getUrlSearchParamsToForwardForTestPreview({
formResponse,
fields,
attributeRoutingConfig,
teamMembersMatchingAttributeLogic,
}: Pick<
GetUrlSearchParamsToForwardOptions,
"formResponse" | "fields" | "attributeRoutingConfig" | "teamMembersMatchingAttributeLogic"
>) {
// There are no existing query params to forward in test preview. These are available only when doing the actual form submission
const searchParams = new URLSearchParams();
searchParams.set("cal.isTestPreviewLink", "true");
return getUrlSearchParamsToForward({
formResponse,
fields,
attributeRoutingConfig,
teamMembersMatchingAttributeLogic,
// There is no form response being stored in test preview
formResponseId: null,
// Queued form response id is not available in test preview
queuedFormResponseId: null,
searchParams,
});
}