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

@@ -0,0 +1,568 @@
import { useRouter } from "next/navigation";
import { createContext, forwardRef, useContext, useState } from "react";
import { useForm } from "react-hook-form";
import { v4 as uuidv4 } from "uuid";
import getFieldIdentifier from "@calcom/app-store/routing-forms/lib/getFieldIdentifier";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { dataTableQueryParamsSerializer } from "@calcom/features/data-table/lib/serializers";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { RoutingFormEmbedButton, RoutingFormEmbedDialog } from "@calcom/features/embed/RoutingFormEmbed";
import { EmbedDialogProvider } from "@calcom/features/embed/lib/hooks/useEmbedDialogCtx";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import slugify from "@calcom/lib/slugify";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
import type { ButtonProps } from "@calcom/ui/components/button";
import { Button } from "@calcom/ui/components/button";
import {
DialogContent,
DialogFooter,
DialogClose,
ConfirmationDialogContent,
} from "@calcom/ui/components/dialog";
import {
Dropdown,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import { TextAreaField } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { Form } from "@calcom/ui/components/form";
import { Switch } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
type FormField = {
identifier?: string;
id: string;
type: string;
label: string;
routerId?: string | null;
};
type RoutingForm = {
id: string;
name: string;
disabled: boolean;
fields?: FormField[];
};
export type NewFormDialogState = { action: "new" | "duplicate"; target: string | null } | null;
export type SetNewFormDialogState = React.Dispatch<React.SetStateAction<NewFormDialogState>>;
function NewFormDialog({
appUrl,
newFormDialogState,
setNewFormDialogState,
}: {
appUrl: string;
newFormDialogState: NewFormDialogState;
setNewFormDialogState: SetNewFormDialogState;
}) {
const { t } = useLocale();
const router = useRouter();
const utils = trpc.useUtils();
const action = newFormDialogState?.action;
const target = newFormDialogState?.target;
const mutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
onSuccess: (_data, variables) => {
router.push(`${appUrl}/form-edit/${variables.id}`);
},
onError: (err) => {
showToast(err.message || t("something_went_wrong"), "error");
},
onSettled: () => {
utils.viewer.appRoutingForms.forms.invalidate();
},
});
const hookForm = useForm<{
name: string;
description: string;
shouldConnect: boolean;
}>();
const formToDuplicate = action === "duplicate" ? target : null;
const teamId = action === "new" ? Number(target) : null;
const { register } = hookForm;
return (
<Dialog open={newFormDialogState !== null} onOpenChange={(open) => !open && setNewFormDialogState(null)}>
<DialogContent className="overflow-y-auto">
<div className="mb-1">
<h3
className="text-emphasis !font-cal text-semibold leading-20 text-xl font-medium"
id="modal-title">
{teamId ? t("add_new_team_form") : t("add_new_form")}
</h3>
<div>
<p className="text-subtle text-sm">{t("form_description")}</p>
</div>
</div>
<Form
form={hookForm}
handleSubmit={(values) => {
const formId = uuidv4();
mutation.mutate({
id: formId,
...values,
addFallback: true,
teamId,
duplicateFrom: formToDuplicate,
});
}}>
<div className="mt-3 space-y-5">
<TextField label={t("title")} required placeholder={t("a_routing_form")} {...register("name")} />
<div className="mb-5">
<TextAreaField
id="description"
label={t("description")}
{...register("description")}
data-testid="description"
placeholder={t("form_description_placeholder")}
/>
</div>
{/* Disable this feature for new forms till we get it fully working with Routing Form with Attributes. This isn't much used feature */}
{/* {action === "duplicate" && (
<Controller
name="shouldConnect"
render={({ field: { value, onChange } }) => {
return (
<SettingsToggle
title={t("keep_me_connected_with_form")}
description={t("fields_in_form_duplicated")}
checked={value}
onCheckedChange={(checked) => {
onChange(checked);
}}
/>
);
}}
/>
)} */}
</div>
<DialogFooter showDivider className="mt-12">
<DialogClose />
<Button loading={mutation.isPending} data-testid="add-form" type="submit">
{t("continue")}
</Button>
</DialogFooter>
</Form>
</DialogContent>
</Dialog>
);
}
const dropdownCtx = createContext<{ dropdown: boolean }>({ dropdown: false });
export const FormActionsDropdown = ({
children,
disabled,
}: {
disabled?: boolean;
children: React.ReactNode;
}) => {
return (
<dropdownCtx.Provider value={{ dropdown: true }}>
<Dropdown>
<DropdownMenuTrigger disabled={disabled} data-testid="form-dropdown" asChild>
<Button
type="button"
variant="icon"
color="secondary"
className={classNames(disabled && "opacity-30")}
StartIcon="ellipsis"
/>
</DropdownMenuTrigger>
<DropdownMenuContent>{children}</DropdownMenuContent>
</Dropdown>
</dropdownCtx.Provider>
);
};
function Dialogs({
appUrl,
deleteDialogOpen,
setDeleteDialogOpen,
deleteDialogFormId,
newFormDialogState,
setNewFormDialogState,
}: {
appUrl: string;
deleteDialogOpen: boolean;
setDeleteDialogOpen: (open: boolean) => void;
deleteDialogFormId: string | null;
newFormDialogState: NewFormDialogState | null;
setNewFormDialogState: SetNewFormDialogState;
}) {
const utils = trpc.useUtils();
const router = useRouter();
const { t } = useLocale();
const deleteMutation = trpc.viewer.appRoutingForms.deleteForm.useMutation({
onMutate: async ({ id: formId }) => {
await utils.viewer.appRoutingForms.forms.cancel();
const previousValue = utils.viewer.appRoutingForms.forms.getData();
if (previousValue) {
const filtered = previousValue.filtered.filter(({ form: { id } }) => id !== formId);
utils.viewer.appRoutingForms.forms.setData(
{},
{
...previousValue,
filtered,
}
);
}
return { previousValue };
},
onSuccess: () => {
showToast(t("form_deleted"), "success");
setDeleteDialogOpen(false);
router.push(`${appUrl}/forms`);
},
onSettled: () => {
utils.viewer.appRoutingForms.forms.invalidate();
setDeleteDialogOpen(false);
},
onError: (err, newTodo, context) => {
if (context?.previousValue) {
utils.viewer.appRoutingForms.forms.setData({}, context.previousValue);
}
showToast(err.message || t("something_went_wrong"), "error");
},
});
return (
<div id="form-dialogs">
<RoutingFormEmbedDialog />
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<ConfirmationDialogContent
isPending={deleteMutation.isPending}
variety="danger"
title={t("delete_form")}
confirmBtnText={t("delete_form_action")}
loadingText={t("delete_form_action")}
onConfirm={(e) => {
if (!deleteDialogFormId) {
return;
}
e.preventDefault();
deleteMutation.mutate({
id: deleteDialogFormId,
});
}}>
<ul className="list-disc pl-3">
<li> {t("delete_form_confirmation")}</li>
<li> {t("delete_form_confirmation_2")}</li>
</ul>
</ConfirmationDialogContent>
</Dialog>
<NewFormDialog
appUrl={appUrl}
newFormDialogState={newFormDialogState}
setNewFormDialogState={setNewFormDialogState}
/>
</div>
);
}
const actionsCtx = createContext({
appUrl: "",
// eslint-disable-next-line @typescript-eslint/no-empty-function
setNewFormDialogState: null as SetNewFormDialogState | null,
newFormDialogState: null as NewFormDialogState,
_delete: {
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onAction: (_arg: { routingForm: RoutingForm | null }) => {},
isPending: false,
},
toggle: {
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onAction: (_arg: { routingForm: RoutingForm | null; checked: boolean }) => {},
isPending: false,
},
});
interface FormActionsProviderProps {
appUrl: string;
children: React.ReactNode;
newFormDialogState: NewFormDialogState;
setNewFormDialogState: SetNewFormDialogState;
}
export function FormActionsProvider({
appUrl,
children,
newFormDialogState,
setNewFormDialogState,
}: FormActionsProviderProps) {
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deleteDialogFormId, setDeleteDialogFormId] = useState<string | null>(null);
const { t } = useLocale();
const utils = trpc.useUtils();
const toggleMutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
onMutate: async ({ id: formId, disabled }) => {
await utils.viewer.appRoutingForms.forms.cancel();
const previousValue = utils.viewer.appRoutingForms.forms.getData();
if (previousValue) {
const formIndex = previousValue.filtered.findIndex(({ form: { id } }) => id === formId);
const previousListOfForms = [...previousValue.filtered];
if (formIndex !== -1 && previousListOfForms[formIndex] && disabled !== undefined) {
previousListOfForms[formIndex].form.disabled = disabled;
}
utils.viewer.appRoutingForms.forms.setData(
{},
{
filtered: previousListOfForms,
totalCount: previousValue.totalCount,
}
);
}
return { previousValue };
},
onSuccess: () => {
showToast(t("form_updated_successfully"), "success");
},
onSettled: (routingForm) => {
utils.viewer.appRoutingForms.forms.invalidate();
if (routingForm) {
utils.viewer.appRoutingForms.formQuery.invalidate({
id: routingForm.id,
});
}
},
onError: (err, value, context) => {
if (context?.previousValue) {
utils.viewer.appRoutingForms.forms.setData({}, context.previousValue);
}
showToast(err.message || t("something_went_wrong"), "error");
},
});
return (
<>
<EmbedDialogProvider>
<actionsCtx.Provider
value={{
appUrl,
setNewFormDialogState,
newFormDialogState,
_delete: {
onAction: ({ routingForm }) => {
if (!routingForm) {
return;
}
setDeleteDialogOpen(true);
setDeleteDialogFormId(routingForm.id);
},
isPending: false,
},
toggle: {
onAction: ({ routingForm, checked }) => {
if (!routingForm) {
return;
}
toggleMutation.mutate({
...routingForm,
disabled: !checked,
});
},
isPending: toggleMutation.isPending,
},
}}>
{children}
</actionsCtx.Provider>
<Dialogs
appUrl={appUrl}
deleteDialogFormId={deleteDialogFormId}
deleteDialogOpen={deleteDialogOpen}
setDeleteDialogOpen={setDeleteDialogOpen}
newFormDialogState={newFormDialogState}
setNewFormDialogState={setNewFormDialogState}
/>
</EmbedDialogProvider>
</>
);
}
type FormActionType =
| "preview"
| "incompleteBooking"
| "edit"
| "copyLink"
| "toggle"
| "_delete"
| "embed"
| "duplicate"
| "download"
| "copyRedirectUrl"
| "viewResponses"
| "create";
type FormActionProps<T> = {
routingForm: RoutingForm | null;
as?: T;
label?: string;
//TODO: Provide types here
action: FormActionType;
children?: React.ReactNode;
render?: (props: {
routingForm: RoutingForm | null;
className?: string;
label?: string;
disabled?: boolean | null | undefined;
}) => JSX.Element;
extraClassNames?: string;
} & ButtonProps;
export const FormAction = forwardRef(function FormAction<T extends typeof Button>(
props: FormActionProps<T>,
forwardedRef: React.ForwardedRef<HTMLAnchorElement | HTMLButtonElement>
) {
const {
action: actionName,
routingForm,
children,
as: asFromElement,
extraClassNames,
...additionalProps
} = props;
const { appUrl, _delete, toggle, setNewFormDialogState } = useContext(actionsCtx);
const dropdownCtxValue = useContext(dropdownCtx);
const dropdown = dropdownCtxValue?.dropdown;
const embedLink = `forms/${routingForm?.id}`;
const orgBranding = useOrgBranding();
const formLink = `${orgBranding?.fullDomain ?? WEBSITE_URL}/${embedLink}`;
let redirectUrl = `${orgBranding?.fullDomain ?? WEBSITE_URL}/router?form=${routingForm?.id}`;
routingForm?.fields?.forEach((field) => {
redirectUrl += `&${getFieldIdentifier(field)}={Recalled_Response_For_This_Field}`;
});
const { t } = useLocale();
const actionData: Record<
FormActionType,
ButtonProps & { as?: React.ElementType; render?: FormActionProps<unknown>["render"] }
> = {
preview: {
href: formLink,
},
copyLink: {
onClick: () => {
showToast(t("link_copied"), "success");
navigator.clipboard.writeText(formLink);
},
},
duplicate: {
onClick: () => setNewFormDialogState?.({ action: "duplicate", target: routingForm?.id ?? null }),
},
embed: {
as: RoutingFormEmbedButton,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
embedUrl: embedLink,
// We are okay with namespace clashing here if just in case names clash
namespace: slugify((routingForm?.name || "").substring(0, 5)),
},
edit: {
href: `${appUrl}/form-edit/${routingForm?.id}`,
},
incompleteBooking: {
href: `${appUrl}/incomplete-booking/${routingForm?.id}`,
},
download: {
href: `/api/integrations/routing-forms/responses/${routingForm?.id}`,
},
_delete: {
onClick: () => _delete.onAction({ routingForm }),
loading: _delete.isPending,
},
create: {
onClick: () => setNewFormDialogState?.({ action: "new", target: "" }),
},
viewResponses: {
href: `/insights/routing${
routingForm?.id
? dataTableQueryParamsSerializer({
activeFilters: [
{ f: "formId", v: { type: ColumnFilterType.SINGLE_SELECT, data: routingForm.id } },
],
})
: ""
}`,
},
copyRedirectUrl: {
onClick: () => {
navigator.clipboard.writeText(redirectUrl);
showToast(t("typeform_redirect_url_copied"), "success");
},
},
toggle: {
render: ({ routingForm, label = "", disabled, ...restProps }) => {
if (!routingForm) {
return <></>;
}
return (
<div
{...restProps}
className={classNames(
"sm:hover:bg-subtle self-center rounded-md p-2 transition hover:bg-gray-200",
extraClassNames
)}>
<Switch
data-testid="toggle-form-switch"
disabled={!!disabled}
checked={!routingForm.disabled}
label={label}
onCheckedChange={(checked) => toggle.onAction({ routingForm, checked })}
labelOnLeading
/>
</div>
);
},
loading: toggle.isPending,
},
};
const { as: asFromAction, ...action } = actionData[actionName];
const as = asFromElement || asFromAction;
const actionProps = {
...action,
...(additionalProps as ButtonProps),
} as ButtonProps & { render?: FormActionProps<unknown>["render"] };
if (actionProps.render) {
return actionProps.render({
routingForm,
...additionalProps,
});
}
const Component = as || Button;
if (!dropdown) {
return (
<Component data-testid={`form-action-${actionName}`} ref={forwardedRef} {...actionProps}>
{children}
</Component>
);
}
return (
<DropdownMenuItem className="hover:bg-[initial]">
<Component
ref={forwardedRef}
{...actionProps}
className={classNames(
props.className,
"text-default w-full transition-none",
props.color === "destructive" && "border-0"
)}>
{children}
</Component>
</DropdownMenuItem>
);
});
@@ -0,0 +1,205 @@
"use client";
import Link from "next/link";
import { useRef } from "react";
import { Controller } from "react-hook-form";
import type { UseFormReturn } from "react-hook-form";
import { TeamMemberSelect } from "@calcom/app-store/routing-forms/components/_components/TeamMemberSelect";
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
import { IS_CALCOM } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { Switch, TextAreaField, TextField } from "@calcom/ui/components/form";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from "@calcom/ui/components/sheet";
type FormSettingsSlideoverProps = {
form: RoutingFormWithResponseCount;
hookForm: UseFormReturn<RoutingFormWithResponseCount>;
isOpen: boolean;
onOpenChange: (open: boolean) => void;
appUrl: string;
};
export const FormSettingsSlideover = ({
form,
hookForm,
isOpen,
onOpenChange,
appUrl,
}: FormSettingsSlideoverProps) => {
const { t } = useLocale();
const { data: user } = useMeQuery();
const sendUpdatesTo = hookForm.watch("settings.sendUpdatesTo") || [];
const sendToAll = hookForm.watch("settings.sendToAll") || false;
// Store initial form values
const initialValuesRef = useRef({
name: hookForm.getValues("name"),
description: hookForm.getValues("description"),
settings: {
sendUpdatesTo: hookForm.getValues("settings.sendUpdatesTo") || [],
sendToAll: hookForm.getValues("settings.sendToAll") || false,
emailOwnerOnSubmission: hookForm.getValues("settings.emailOwnerOnSubmission") || false,
},
});
const handleCancel = () => {
// Revert only the fields we edit
const initialValues = initialValuesRef.current;
hookForm.setValue("name", initialValues.name);
hookForm.setValue("description", initialValues.description);
hookForm.setValue("settings.sendUpdatesTo", initialValues.settings.sendUpdatesTo);
hookForm.setValue("settings.sendToAll", initialValues.settings.sendToAll);
hookForm.setValue("settings.emailOwnerOnSubmission", initialValues.settings.emailOwnerOnSubmission);
onOpenChange(false);
};
return (
<Sheet
open={isOpen}
onOpenChange={(open) => {
if (!open) {
handleCancel();
} else {
onOpenChange(open);
}
}}>
<SheetContent className="flex flex-col">
<SheetHeader>
<SheetTitle>{t("form_settings")}</SheetTitle>
</SheetHeader>
<div className="mt-6 flex-1 overflow-y-auto">
<TextField
type="text"
containerClassName="mb-6"
placeholder={t("title")}
{...hookForm.register("name")}
data-testid="name"
/>
<TextAreaField
rows={3}
id="description"
data-testid="description"
placeholder={t("form_description_placeholder")}
{...hookForm.register("description")}
defaultValue={form.description || ""}
/>
<div className="mt-6">
{form.teamId ? (
<div className="flex flex-col">
<TeamMemberSelect
teamMembers={form.teamMembers}
selectedMembers={sendUpdatesTo}
onChange={(memberIds) => {
hookForm.setValue("settings.sendUpdatesTo", memberIds, { shouldDirty: true });
hookForm.setValue("settings.emailOwnerOnSubmission", false, {
shouldDirty: true,
});
}}
onSelectAll={(selectAll) => {
hookForm.setValue("settings.sendToAll", selectAll, { shouldDirty: true });
}}
selectAllEnabled={true}
sendToAll={sendToAll}
placeholder={t("select_members")}
/>
</div>
) : (
<Controller
name="settings.emailOwnerOnSubmission"
control={hookForm.control}
render={({ field: { value, onChange } }) => {
return (
<div className="flex items-center gap-2">
<label
htmlFor="emailOwnerOnSubmission"
className="text-default text-sm font-medium leading-none">
{t("routing_forms_send_email_owner")}
</label>
<Switch
size="sm"
id="emailOwnerOnSubmission"
checked={value}
onCheckedChange={(val) => {
onChange(val);
hookForm.unregister("settings.sendUpdatesTo");
}}
/>
</div>
);
}}
/>
)}
</div>
{form.routers.length ? (
<div className="mt-6">
<div className="text-emphasis mb-2 block text-sm font-semibold leading-none">
{t("routers")}
</div>
<p className="text-default -mt-1 text-xs leading-normal">
{t("modifications_in_fields_warning")}
</p>
<div className="flex">
{form.routers.map((router) => {
return (
<div key={router.id} className="mr-2">
<Link href={`${appUrl}/route-builder/${router.id}`}>
<Badge variant="gray">{router.name}</Badge>
</Link>
</div>
);
})}
</div>
</div>
) : null}
{form.connectedForms?.length ? (
<div className="mt-6">
<div className="text-emphasis mb-2 block text-sm font-semibold leading-none">
{t("connected_forms")}
</div>
<p className="text-default -mt-1 text-xs leading-normal">{t("form_modifications_warning")}</p>
<div className="flex">
{form.connectedForms.map((router) => {
return (
<div key={router.id} className="mr-2">
<Link href={`${appUrl}/route-builder/${router.id}`}>
<Badge variant="default">{router.name}</Badge>
</Link>
</div>
);
})}
</div>
</div>
) : null}
<div className="mt-6 flex gap-2">
{IS_CALCOM && (
<Button
target="_blank"
color="minimal"
href={`https://i.cal.com/support/routing-support-session?email=${encodeURIComponent(
user?.email ?? ""
)}&name=${encodeURIComponent(user?.name ?? "")}&form=${encodeURIComponent(form.id)}`}>
{t("need_help")}
</Button>
)}
</div>
</div>
<SheetFooter className="flex-shrink-0 ">
<Button color="minimal" onClick={handleCancel} data-testid="settings-slider-over-cancel">
{t("cancel")}
</Button>
<Button onClick={() => onOpenChange(false)} data-testid="settings-slider-over-done">
{t("done")}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
};
@@ -0,0 +1,382 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
import { useFormContext } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RoutingFormWithResponseCount } from "@calcom/routing-forms/types/types";
import { Button } from "@calcom/ui/components/button";
import { DropdownMenuSeparator } from "@calcom/ui/components/dropdown";
import { ToggleGroup } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { FormAction, FormActionsDropdown } from "./FormActions";
import { FormSettingsSlideover } from "./FormSettingsSlideover";
// Toggle group doesnt support HREF navigation, so we need to use this hook to handle navigation
const useRoutingFormNavigation = (
form: RoutingFormWithResponseCount,
appUrl: string,
setShowInfoLostDialog: (value: boolean) => void
) => {
const pathname = usePathname();
const router = useRouter();
const formContext = useFormContext<RoutingFormWithResponseCount>();
// Get the current page based on the pathname since we use a custom routing system
const getCurrentPage = () => {
const path = pathname || "";
if (path.includes("/form-edit/")) return "form-edit";
if (path.includes("/route-builder/")) return "route-builder";
if (path.includes("/incomplete-booking/")) return "incomplete-booking";
return "form-edit"; // default to form-edit if no match
};
const handleNavigation = (value: string) => {
if (!value) return;
const baseUrl = `${appUrl}/${value}/${form.id}`;
if (value === "route-builder" && formContext.formState.isDirty) {
setShowInfoLostDialog(true);
} else {
router.push(baseUrl);
}
};
return {
getCurrentPage,
handleNavigation,
};
};
const Actions = ({
form,
isSaving,
appUrl,
setIsTestPreviewOpen,
isTestPreviewOpen,
isMobile = false,
permissions,
}: {
form: RoutingFormWithResponseCount;
setIsTestPreviewOpen: (value: boolean) => void;
isSaving: boolean;
appUrl: string;
isTestPreviewOpen: boolean;
isMobile?: boolean;
permissions: {
canCreate: boolean;
canRead: boolean;
canEdit: boolean;
canDelete: boolean;
};
}) => {
const { t } = useLocale();
const formContext = useFormContext<RoutingFormWithResponseCount>();
const [isSettingsDialogOpen, setIsSettingsDialogOpen] = useState(false);
return (
<>
<div className="flex items-center">
<div className="flex gap-2">
<Tooltip sideOffset={4} content={t("preview")} side="bottom">
<Button
color="secondary"
data-testid={isMobile ? "preview-button-mobile" : "preview-button"}
type="button"
variant="icon"
onClick={() => {
setIsTestPreviewOpen(!isTestPreviewOpen);
}}>
{t("preview")}
</Button>
</Tooltip>
<Tooltip sideOffset={4} content={t("settings")} side="bottom">
<Button
color="secondary"
type="button"
StartIcon="settings"
data-testid={isMobile ? "settings-button-mobile" : "settings-button"}
onClick={() => {
setIsSettingsDialogOpen(true);
}}
/>
</Tooltip>
<FormActionsDropdown>
<FormAction
routingForm={form}
color="minimal"
target="_blank"
type="button"
rel="noreferrer"
action="preview"
StartIcon="external-link">
{t("view_form")}
</FormAction>
<FormAction
action="incompleteBooking"
className="w-full"
routingForm={form}
color="minimal"
type="button"
StartIcon="calendar">
{t("routing_incomplete_booking_tab")}
</FormAction>
<FormAction
action="copyLink"
className="w-full"
routingForm={form}
color="minimal"
type="button"
StartIcon="link">
{t("copy_link_to_form")}
</FormAction>
<FormAction
action="download"
routingForm={form}
className="w-full"
color="minimal"
type="button"
data-testid="download-responses"
StartIcon="download">
{t("download_responses")}
</FormAction>
{form?.id && (
<FormAction
action="viewResponses"
routingForm={form}
className="w-full"
color="minimal"
type="button"
data-testid="view-responses"
StartIcon="eye">
{t("view_responses")}
</FormAction>
)}
<FormAction
action="embed"
routingForm={form}
color="minimal"
type="button"
className="w-full"
StartIcon="code">
{t("embed")}
</FormAction>
<DropdownMenuSeparator className="hidden sm:block" />
<FormAction
action="_delete"
routingForm={form}
className="w-full"
type="button"
color="destructive"
disabled={!permissions.canDelete}
StartIcon="trash">
{t("delete")}
</FormAction>
<div className="block sm:hidden">
<DropdownMenuSeparator />
<FormAction
data-testid="toggle-form"
action="toggle"
routingForm={form}
label="Disable Form"
extraClassNames="hover:bg-subtle cursor-pointer rounded-[5px] pr-4 transition"
/>
</div>
</FormActionsDropdown>
<Button
data-testid={isMobile ? "update-form-mobile" : "update-form"}
loading={isSaving}
disabled={!permissions.canEdit}
type="submit"
color="primary">
{t("save")}
</Button>
</div>
</div>
<FormSettingsSlideover
hookForm={formContext}
form={form}
isOpen={isSettingsDialogOpen}
onOpenChange={setIsSettingsDialogOpen}
appUrl={appUrl}
/>
</>
);
};
export function Header({
routingForm,
isSaving,
appUrl,
setShowInfoLostDialog,
setIsTestPreviewOpen,
isTestPreviewOpen,
permissions,
}: {
routingForm: RoutingFormWithResponseCount;
isSaving: boolean;
appUrl: string;
setShowInfoLostDialog: (value: boolean) => void;
setIsTestPreviewOpen: (value: boolean) => void;
isTestPreviewOpen: boolean;
permissions: {
canCreate: boolean;
canRead: boolean;
canEdit: boolean;
canDelete: boolean;
};
}) {
const { t } = useLocale();
const [isEditing, setIsEditing] = useState(false);
const [title, setTitle] = useState(routingForm.name);
const form = useFormContext<RoutingFormWithResponseCount>();
const { getCurrentPage, handleNavigation } = useRoutingFormNavigation(
routingForm,
appUrl,
setShowInfoLostDialog
);
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setTitle(e.target.value);
};
const handleTitleSubmit = () => {
setIsEditing(false);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
form.setValue("name", title);
handleTitleSubmit();
} else if (e.key === "Escape") {
form.setValue("name", routingForm.name);
setIsEditing(false);
}
};
const watchedName = form.watch("name");
return (
<div className="bg-default flex flex-col lg:grid lg:grid-cols-3 lg:items-center">
{/* Left - Back button and title */}
<div className="border-muted flex items-center gap-2 border-b px-4 py-3">
<Button
color="minimal"
variant="icon"
StartIcon="arrow-left"
href={`${appUrl}`}
data-testid="back-button"
/>
<div className="flex min-w-0 items-center">
<span className="text-subtle min-w-content text-sm font-semibold leading-none">
{t("routing_form")}
</span>
<span className="text-subtle mx-1 text-sm font-semibold leading-none">/</span>
{isEditing ? (
<input
{...form.register("name")}
onChange={handleTitleChange}
onKeyDown={handleKeyDown}
onBlur={handleTitleSubmit}
className="text-default h-auto w-full whitespace-nowrap border-none p-0 text-sm font-semibold leading-none focus:ring-0"
autoFocus
/>
) : (
<div className="group flex items-center gap-1">
<span
className="text-default hover:bg-muted min-w-[100px] cursor-pointer truncate whitespace-nowrap rounded px-1 text-sm font-semibold leading-none"
onClick={() => setIsEditing(true)}>
{watchedName || "Loading..."}
</span>
<Button
variant="icon"
color="minimal"
onClick={() => setIsEditing(true)}
CustomStartIcon={
<Icon name="pencil" className="text-subtle group-hover:text-default h-3 w-3" />
}>
<span className="sr-only">Edit</span>
</Button>
</div>
)}
</div>
</div>
{/* Mobile/Tablet layout - Second row with toggle group and actions on the same row */}
<div className="border-muted flex items-center justify-between border-b px-4 py-3 lg:hidden">
{/* Navigation Tabs - Left aligned */}
<div className="flex">
<ToggleGroup
defaultValue={getCurrentPage()}
value={getCurrentPage()}
onValueChange={handleNavigation}
options={[
{
value: "form-edit",
label: t("form"),
iconLeft: <Icon name="menu" className="h-3 w-3" />,
dataTestId: "toggle-group-item-form-edit",
},
{
value: "route-builder",
label: t("routing"),
iconLeft: <Icon name="waypoints" className="h-3 w-3" />,
},
]}
/>
</div>
{/* Actions - Right aligned */}
<div className="flex">
<Actions
form={routingForm}
setIsTestPreviewOpen={setIsTestPreviewOpen}
isTestPreviewOpen={isTestPreviewOpen}
isSaving={isSaving}
appUrl={appUrl}
isMobile={true}
permissions={permissions}
/>{" "}
</div>
</div>
{/* Desktop layout - Toggle group in center column */}
<div className="border-muted hidden justify-center border-b px-4 py-3 lg:flex">
<ToggleGroup
defaultValue={getCurrentPage()}
value={getCurrentPage()}
onValueChange={handleNavigation}
options={[
{
value: "form-edit",
label: t("form"),
iconLeft: <Icon name="menu" className="h-3 w-3" />,
},
{
value: "route-builder",
label: t("routing"),
iconLeft: <Icon name="waypoints" className="h-3 w-3" />,
},
]}
/>
</div>
{/* Desktop layout - Actions in right column */}
<div className="border-muted hidden justify-end border-b px-4 py-3 lg:flex">
<Actions
form={routingForm}
setIsTestPreviewOpen={setIsTestPreviewOpen}
isTestPreviewOpen={isTestPreviewOpen}
isSaving={isSaving}
appUrl={appUrl}
permissions={permissions}
/>
</div>
</div>
);
}
@@ -0,0 +1,270 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useState } from "react";
import { useFormContext } from "react-hook-form";
import type { UseFormReturn } from "react-hook-form";
import { InfoLostWarningDialog } from "@calcom/app-store/routing-forms/components/InfoLostWarningDialog";
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import classNames from "@calcom/ui/classNames";
import { Form } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import type { getServerSidePropsForSingleFormView } from "@lib/apps/routing-forms/[...pages]/getServerSidePropsSingleForm";
import type { NewFormDialogState } from "./FormActions";
import { FormActionsProvider } from "./FormActions";
import { Header } from "./Header";
import type { UptoDateForm } from "./TestForm";
import { TestFormRenderer } from "./TestForm";
export type SingleFormComponentProps = {
form: RoutingFormWithResponseCount;
appUrl: string;
Page: React.FC<{
form: RoutingFormWithResponseCount;
appUrl: string;
hookForm: UseFormReturn<RoutingFormWithResponseCount>;
}>;
enrichedWithUserProfileForm: inferSSRProps<
typeof getServerSidePropsForSingleFormView
>["enrichedWithUserProfileForm"];
permissions: inferSSRProps<typeof getServerSidePropsForSingleFormView>["permissions"];
};
const BREAKPOINTS = {
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
"2xl": 1536,
} as const;
type Breakpoint = keyof typeof BREAKPOINTS;
type BreakpointState = Record<Breakpoint, boolean>;
function useBreakPoints() {
const [breakpoints, setBreakpoints] = useState<BreakpointState>({
sm: false,
md: false,
lg: false,
xl: false,
"2xl": false,
});
useEffect(() => {
const updateBreakpoints = () => {
const width = window.innerWidth;
setBreakpoints({
sm: width >= BREAKPOINTS.sm,
md: width >= BREAKPOINTS.md,
lg: width >= BREAKPOINTS.lg,
xl: width >= BREAKPOINTS.xl,
"2xl": width >= BREAKPOINTS["2xl"],
});
};
// Initial check
updateBreakpoints();
// Add resize listener
window.addEventListener("resize", updateBreakpoints);
return () => window.removeEventListener("resize", updateBreakpoints);
}, []);
return {
...breakpoints,
// Convenience properties
isMobile: !breakpoints.md,
isTablet: breakpoints.md && !breakpoints.lg,
isDesktop: breakpoints.lg,
};
}
/**
* It has the the ongoing changes in the form along with enrichedWithUserProfileForm specific data.
* So, it can be used to test the form in the test preview dialog without saving the changes even.
*/
function SingleForm({
form,
appUrl,
Page,
enrichedWithUserProfileForm,
permissions,
}: SingleFormComponentProps) {
const utils = trpc.useUtils();
const { t } = useLocale();
const [newFormDialogState, setNewFormDialogState] = useState<NewFormDialogState>(null);
const [isTestPreviewOpen, setIsTestPreviewOpen] = useState(false);
const [skipFirstUpdate, setSkipFirstUpdate] = useState(true);
const [showInfoLostDialog, setShowInfoLostDialog] = useState(false);
const hookForm = useFormContext<RoutingFormWithResponseCount>();
const { isDesktop } = useBreakPoints();
useEffect(() => {
// The first time a tab is opened, the hookForm copies the form data (saved version, from the backend),
// and then it is considered the source of truth.
// There are two events we need to overwrite the hookForm data with the form data coming from the server.
// 1 - When we change the edited form.
// 2 - When the form is saved elsewhere (such as in another browser tab)
// In the second case. We skipped the first execution of useEffect to differentiate a tab change from a form change,
// because each time a tab changes, a new component is created and another useEffect is executed.
// An update from the form always occurs after the first useEffect execution.
if (Object.keys(hookForm.getValues()).length === 0 || hookForm.getValues().id !== form.id) {
hookForm.reset(form);
}
if (skipFirstUpdate) {
setSkipFirstUpdate(false);
} else {
hookForm.reset(form);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form]);
const mutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
onSuccess() {
showToast(t("form_updated_successfully"), "success");
},
onError(e) {
if (e.message) {
showToast(e.message, "error");
return;
}
showToast(`Something went wrong`, "error");
},
onSettled() {
utils.viewer.appRoutingForms.formQuery.invalidate({ id: form.id });
},
});
const uptoDateForm = {
...hookForm.getValues(),
routes: hookForm.watch("routes"),
user: enrichedWithUserProfileForm.user,
team: enrichedWithUserProfileForm.team,
nonOrgUsername: enrichedWithUserProfileForm.nonOrgUsername,
nonOrgTeamslug: enrichedWithUserProfileForm.nonOrgTeamslug,
userOrigin: enrichedWithUserProfileForm.userOrigin,
teamOrigin: enrichedWithUserProfileForm.teamOrigin,
} as UptoDateForm;
const handleSubmit = (data: RoutingFormWithResponseCount) => {
mutation.mutate({
...data,
});
};
return (
<>
<Form form={hookForm} handleSubmit={handleSubmit}>
<FormActionsProvider
appUrl={appUrl}
newFormDialogState={newFormDialogState}
setNewFormDialogState={setNewFormDialogState}>
<div className="flex h-full min-h-screen w-full flex-col">
<Header
routingForm={form}
isSaving={mutation.isPending}
appUrl={appUrl}
setShowInfoLostDialog={setShowInfoLostDialog}
setIsTestPreviewOpen={setIsTestPreviewOpen}
isTestPreviewOpen={isTestPreviewOpen}
permissions={permissions}
/>
<div
className={classNames(
"bg-default flex-1",
isDesktop && "grid gap-8",
isDesktop && isTestPreviewOpen && "grid-cols-[1fr,400px]",
isDesktop && !isTestPreviewOpen && "grid-cols-1",
!isDesktop && "flex flex-col"
)}>
{isDesktop ? (
<motion.div
layout
className="mx-auto w-full max-w-4xl px-2 lg:px-4 xl:px-0"
transition={{ duration: 0.3, ease: "easeInOut" }}>
<Page hookForm={hookForm} form={form} appUrl={appUrl} />
</motion.div>
) : (
<div className="mx-auto w-full max-w-4xl px-2">
<Page hookForm={hookForm} form={form} appUrl={appUrl} />
</div>
)}
<AnimatePresence>
{isTestPreviewOpen && isDesktop ? (
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
transition={{ duration: 0.3, ease: "easeInOut" }}>
<TestFormRenderer
isMobile={!isDesktop}
testForm={uptoDateForm}
isTestPreviewOpen={isTestPreviewOpen}
setIsTestPreviewOpen={setIsTestPreviewOpen}
/>
</motion.div>
) : isTestPreviewOpen ? (
<div>
<TestFormRenderer
isMobile={!isDesktop}
testForm={uptoDateForm}
isTestPreviewOpen={isTestPreviewOpen}
setIsTestPreviewOpen={setIsTestPreviewOpen}
/>
</div>
) : null}
</AnimatePresence>
</div>
</div>
</FormActionsProvider>
{showInfoLostDialog && (
<InfoLostWarningDialog
handleSubmit={() => {
mutation.mutate({
...hookForm.getValues(),
});
}}
goToRoute={`${appUrl}/route-builder/${form?.id}`}
isOpenInfoLostDialog={showInfoLostDialog}
setIsOpenInfoLostDialog={setShowInfoLostDialog}
/>
)}
</Form>
</>
);
}
export default function SingleFormWrapper({ form: _form, ...props }: SingleFormComponentProps) {
const { data: form, isPending } = trpc.viewer.appRoutingForms.formQuery.useQuery(
{ id: _form.id },
{
initialData: _form,
trpc: {},
}
);
const { t } = useLocale();
if (isPending) {
// It shouldn't be possible because we are passing the data from SSR to it as initialData. So, no need for skeleton here
return null;
}
if (!form) {
throw new Error(t("something_went_wrong"));
}
return (
<LicenseRequired>
<SingleForm form={form} {...props} />
</LicenseRequired>
);
}
@@ -0,0 +1,375 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import type { Dispatch, SetStateAction } from "react";
import { useState, useMemo } from "react";
import FormInputFields from "@calcom/app-store/routing-forms/components/FormInputFields";
import { ResultsView as Results } from "@calcom/app-store/routing-forms/components/_components/ResultSection";
import { TeamMembersMatchResult } from "@calcom/app-store/routing-forms/components/_components/TeamMembersMatchResult";
import type { MembersMatchResultType } from "@calcom/app-store/routing-forms/components/_components/TeamMembersMatchResult";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { substituteVariables } from "@calcom/app-store/routing-forms/lib/substituteVariables";
import type { RoutingForm, FormResponse, NonRouterRoute } from "@calcom/app-store/routing-forms/types/types";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import type { Brand } from "@calcom/types/utils";
import { Button } from "@calcom/ui/components/button";
import { Dialog, DialogContent, DialogHeader, DialogFooter } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
import type { getServerSidePropsForSingleFormView } from "@lib/apps/routing-forms/[...pages]/getServerSidePropsSingleForm";
import { TRPCClientError } from "@trpc/react-query";
export type UptoDateForm = Brand<
NonNullable<inferSSRProps<typeof getServerSidePropsForSingleFormView>["enrichedWithUserProfileForm"]>,
"UptoDateForm"
>;
const FormView = ({
form,
response,
setResponse,
areRequiredFieldsFilled,
onClose,
onSubmit,
renderFooter,
}: {
form: UptoDateForm | RoutingForm;
response: FormResponse;
setResponse: Dispatch<SetStateAction<FormResponse>>;
areRequiredFieldsFilled: boolean;
onClose: () => void;
onSubmit: () => void;
renderFooter?: (onClose: () => void, onSubmit: () => void, isValid: boolean) => React.ReactNode;
}) => {
const { t } = useLocale();
return (
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
transition={{ duration: 0.2 }}>
<form
noValidate
onSubmit={(e) => {
e.preventDefault();
}}>
{form && <FormInputFields form={form} response={response} setResponse={setResponse} />}
</form>
{!renderFooter ? (
<div className="mt-4">
<Button onClick={onSubmit} disabled={!areRequiredFieldsFilled} data-testid="submit-button">
{t("submit")}
</Button>
</div>
) : (
renderFooter(onClose, onSubmit, areRequiredFieldsFilled)
)}
</motion.div>
);
};
export const TestForm = ({
form,
supportsTeamMembersMatchingLogic,
renderFooter,
isDialog = false,
onClose: onCloseProp,
showRRData = false,
}: {
form: UptoDateForm | RoutingForm;
supportsTeamMembersMatchingLogic: boolean;
renderFooter?: (onClose: () => void, onSubmit: () => void, isValid: boolean) => React.ReactNode;
isDialog?: boolean;
onClose?: () => void;
showRRData?: boolean;
}) => {
const { t } = useLocale();
const [response, setResponse] = useState<FormResponse>({});
const [chosenRoute, setChosenRoute] = useState<NonRouterRoute | null>(null);
const searchParams = useCompatSearchParams();
const [membersMatchResult, setMembersMatchResult] = useState<MembersMatchResultType | null>(null);
const [showResults, setShowResults] = useState(false);
const [formKey, setFormKey] = useState<number>(0);
const orgBranding = useOrgBranding();
const embedLink = `forms/${form.id}`;
const formLink = `${orgBranding?.fullDomain ?? WEBSITE_URL}/${embedLink}`;
const areRequiredFieldsFilled = useMemo(() => {
if (!form.fields) return true;
const requiredFields = form.fields.filter((field) => field.required);
if (!requiredFields.length) return true;
return requiredFields.every((field) => {
const fieldResponse = response[field.id];
if (!fieldResponse) return false;
const value = fieldResponse.value;
if (Array.isArray(value)) {
return value.length > 0;
}
return value !== undefined && value !== null && value !== "";
});
}, [form.fields, response]);
const resetMembersMatchResult = () => {
setMembersMatchResult(null);
setShowResults(false);
};
function testRouting() {
const route = findMatchingRoute({ form, response });
// Create a copy of the route with substituted variables for display
let displayRoute = route;
if (route && form.fields && route.action.type === "eventTypeRedirectUrl") {
const substitutedUrl = substituteVariables(route.action.value, response, form.fields);
displayRoute = {
...route,
action: {
...route.action,
value: substitutedUrl,
},
};
}
setChosenRoute(displayRoute || null);
setShowResults(true);
if (!route) return;
// Custom Event Type Redirect URL has eventTypeId=0. Also, findTeamMembersMatchingAttributeLogicMutation can't work without eventTypeId
if (supportsTeamMembersMatchingLogic && route.action.eventTypeId) {
findTeamMembersMatchingAttributeLogicMutation.mutate({
formId: form.id,
response,
route,
isPreview: true,
_enablePerf: searchParams.get("enablePerf") === "true",
});
}
}
const onClose = () => {
setChosenRoute(null);
setResponse({});
setShowResults(false);
onCloseProp?.();
};
function resetForm() {
setChosenRoute(null);
setResponse({});
setShowResults(false);
// This is a hack to force the form to reset RAQB doesnt seem to be resetting the form when the form is re-rendered
setFormKey((prevKey) => prevKey + 1);
}
const findTeamMembersMatchingAttributeLogicMutation =
trpc.viewer.routingForms.findTeamMembersMatchingAttributeLogicOfRoute.useMutation({
onSuccess(data) {
setMembersMatchResult({
isUsingAttributeWeights: data.isUsingAttributeWeights,
eventTypeRedirectUrl: data.eventTypeRedirectUrl,
contactOwnerEmail: data.contactOwnerEmail,
teamMembersMatchingAttributeLogic: data.result ? data.result.users : data.result,
perUserData: data.result ? data.result.perUserData : null,
checkedFallback: data.checkedFallback,
mainWarnings: data.mainWarnings,
fallbackWarnings: data.fallbackWarnings,
});
},
onError(e) {
if (e instanceof TRPCClientError) {
showToast(e.message, "error");
} else {
showToast(t("something_went_wrong"), "error");
}
},
});
return (
<div>
<AnimatePresence mode="wait">
{!showResults ? (
<>
{isDialog ? (
<DialogHeader title={t("test_routing_form")} subtitle={t("test_preview_description")} />
) : !showRRData ? (
<div className="mb-6 flex items-center justify-between">
<h3 className="text-emphasis text-xl font-semibold">{t("preview")}</h3>
<div className="flex items-center gap-1">
<Button
color="secondary"
href={formLink}
target="_blank"
variant="icon"
StartIcon="external-link"
data-testid="open-form-in-new-tab"
size="sm">
<span className="sr-only">{t("open_in_new_tab")}</span>
</Button>
<Button
color="secondary"
onClick={resetForm}
variant="icon"
StartIcon="refresh-cw"
size="sm">
<span className="sr-only">{t("reset")}</span>
</Button>
<Button color="secondary" onClick={onClose} variant="icon" StartIcon="x" size="sm">
<span className="sr-only">{t("close")}</span>
</Button>
</div>
</div>
) : (
<></>
)}
<FormView
key={formKey}
form={form}
response={response}
setResponse={setResponse}
areRequiredFieldsFilled={areRequiredFieldsFilled}
onClose={onClose}
onSubmit={() => {
resetMembersMatchResult();
testRouting();
}}
renderFooter={renderFooter}
/>
</>
) : (
<>
{isDialog ? (
<DialogHeader title={t("test_routing_form")} subtitle={t("test_preview_description")} />
) : !showRRData ? (
<div className="mb-6 flex items-center justify-between">
<h3 className="text-emphasis text-xl font-semibold">{t("results")}</h3>
<div className="flex items-center gap-1">
<Button
color="secondary"
href={formLink}
target="_blank"
variant="icon"
StartIcon="external-link"
size="sm">
<span className="sr-only">{t("open_in_new_tab")}</span>
</Button>
<Button
color="secondary"
onClick={resetForm}
variant="icon"
StartIcon="refresh-cw"
size="sm">
<span className="sr-only">{t("reset")}</span>
</Button>
<Button
color="secondary"
onClick={onClose}
variant="icon"
StartIcon="x"
size="sm"
data-testid="close-results-button">
<span className="sr-only">{t("close")}</span>
</Button>
</div>
</div>
) : (
<></>
)}
{showRRData ? (
<>
<Button color="secondary" onClick={resetForm} variant="icon" StartIcon="refresh-cw">
{t("reset_form")}
</Button>
<TeamMembersMatchResult membersMatchResult={membersMatchResult} />
</>
) : (
<Results
chosenRoute={chosenRoute}
supportsTeamMembersMatchingLogic={supportsTeamMembersMatchingLogic}
membersMatchResult={membersMatchResult}
isPending={findTeamMembersMatchingAttributeLogicMutation.isPending}
/>
)}
{isDialog && (
<DialogFooter>
<Button onClick={onClose} color="secondary">
{t("back")}
</Button>
</DialogFooter>
)}
</>
)}
</AnimatePresence>
</div>
);
};
export const TestFormRenderer = ({
testForm,
isTestPreviewOpen,
setIsTestPreviewOpen,
isMobile,
}: {
testForm: UptoDateForm;
isTestPreviewOpen: boolean;
setIsTestPreviewOpen: (value: boolean) => void;
isMobile: boolean;
}) => {
const { t } = useLocale();
const isSubTeamForm = !!testForm.team?.parentId;
if (!isMobile) {
if (isTestPreviewOpen) {
return (
<div className="border-muted bg-muted h-full border-l p-6">
<TestForm
form={testForm}
supportsTeamMembersMatchingLogic={isSubTeamForm}
onClose={() => setIsTestPreviewOpen(false)}
/>
</div>
);
}
}
return (
<Dialog open={isTestPreviewOpen} onOpenChange={setIsTestPreviewOpen}>
<DialogContent size="md" enableOverflow>
<TestForm
isDialog
form={testForm}
supportsTeamMembersMatchingLogic={isSubTeamForm}
renderFooter={(onClose, onSubmit, isValid) => (
<DialogFooter>
<Button
onClick={() => {
onClose();
setIsTestPreviewOpen(false);
}}
color="secondary">
{t("close")}
</Button>
<Button onClick={onSubmit} disabled={!isValid}>
{t("submit")}
</Button>
</DialogFooter>
)}
/>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,487 @@
import { render, screen, fireEvent } from "@testing-library/react";
import type { Mock } from "vitest";
import { vi } from "vitest";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { TestFormRenderer } from "./TestForm";
vi.mock("framer-motion", async () => {
return {
motion: {
div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
},
AnimatePresence: ({ children }: any) => <>{children}</>,
};
});
vi.mock("@calcom/app-store/routing-forms/lib/processRoute", () => ({
findMatchingRoute: vi.fn(),
}));
vi.mock("next/navigation", async (importOriginal) => {
const actual = await importOriginal<typeof import("next/navigation")>();
return {
...actual,
useRouter: vi.fn(() => ({
push: vi.fn(() => {
return;
}),
})),
};
});
function mockMatchingRoute(route: any) {
(findMatchingRoute as Mock<typeof findMatchingRoute>).mockReturnValue({
...route,
id: "matching-route-id",
});
}
function mockCustomPageMessageMatchingRoute() {
mockMatchingRoute({
action: {
type: "customPageMessage",
value: "Thank you for submitting!",
},
});
}
function mockEventTypeRedirectUrlMatchingRoute() {
mockMatchingRoute({
action: {
type: "eventTypeRedirectUrl",
value: "john/30min",
eventTypeId: 123,
},
});
}
/**
* fixes the error due to Formbricks
*/
vi.mock("@calcom/features/shell/Shell", () => ({
ShellMain: vi.fn(),
}));
vi.mock("@calcom/lib/hooks/useApp", () => ({
default: vi.fn(),
}));
/**
* Avoids the error due to Formbricks
*/
vi.mock("./FormActions", () => ({
FormAction: vi.fn(),
FormActionsDropdown: vi.fn(),
FormActionsProvider: vi.fn(),
}));
vi.mock(
"@calcom/app-store/routing-forms/components/react-awesome-query-builder/widgets",
async (importOriginal) => {
return await importOriginal();
}
);
// Mock the necessary dependencies
vi.mock("@calcom/lib/hooks/useLocale", () => ({
useLocale: vi.fn(() => ({ t: (key: string) => key })),
}));
let findTeamMembersMatchingAttributeLogicResponse: {
result: { users: { email: string }[] } | null;
checkedFallback: boolean;
mainWarnings?: string[] | null;
fallbackWarnings?: string[] | null;
} = {
result: null,
checkedFallback: false,
mainWarnings: null,
fallbackWarnings: null,
};
function resetFindTeamMembersMatchingAttributeLogicResponse() {
findTeamMembersMatchingAttributeLogicResponse = {
result: null,
checkedFallback: false,
mainWarnings: null,
fallbackWarnings: null,
};
}
function mockFindTeamMembersMatchingAttributeLogicResponse(
response: typeof findTeamMembersMatchingAttributeLogicResponse
) {
findTeamMembersMatchingAttributeLogicResponse = response;
}
vi.mock("@calcom/trpc/react", () => ({
trpc: {
viewer: {
routingForms: {
findTeamMembersMatchingAttributeLogicOfRoute: {
useMutation: vi.fn(({ onSuccess }) => {
return {
mutate: vi.fn(() => {
onSuccess(findTeamMembersMatchingAttributeLogicResponse);
}),
};
}),
},
},
},
},
}));
const mockSubTeamForm = {
id: "routing-form-id",
teamId: "test-team-id",
name: "Test Form",
description: "Test form description",
fields: [
{
id: "name",
identifier: "name",
type: "text",
label: "Name",
required: true,
},
],
routes: [
{
id: "non-matching-route-id",
isFallback: false,
action: {
type: "customPageMessage",
value: "Not matching",
},
},
{
id: "matching-route-id",
isFallback: false,
action: {
type: "customPageMessage",
value: "Thank you for submitting!",
},
},
{
id: "fallback-route",
isFallback: true,
action: {
type: "customPageMessage",
value: "Thank you for submitting!",
},
},
],
team: {
parentId: "org-1",
},
} as any;
const mockRegularTeamForm = {
...mockSubTeamForm,
team: {
parentId: null,
},
} as any;
describe("TestFormDialog", () => {
beforeEach(() => {
resetFindTeamMembersMatchingAttributeLogicResponse();
vi.clearAllMocks();
});
it("renders the dialog when open", () => {
render(
<TestFormRenderer
isMobile={true}
testForm={mockSubTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
expect(screen.getByText("test_routing_form")).toBeInTheDocument();
expect(screen.getByText("test_preview_description")).toBeInTheDocument();
});
it("doesn't render the dialog when closed", () => {
render(
<TestFormRenderer
isMobile={true}
testForm={mockSubTeamForm}
isTestPreviewOpen={false}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
expect(screen.queryByText("test_routing_form")).not.toBeInTheDocument();
});
it("renders form fields", () => {
render(
<TestFormRenderer
isMobile={true}
testForm={mockSubTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
expect(screen.getByTestId("form-field-name")).toBeInTheDocument();
});
describe("Sub-Team Form", () => {
const form = mockSubTeamForm;
it("submits the form and shows test results for Custom Page", async () => {
mockCustomPageMessageMatchingRoute();
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("Thank you for submitting!");
});
it("submits the form and shows test results for Event Type", async () => {
mockEventTypeRedirectUrlMatchingRoute();
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("john/30min");
expect(screen.getByTestId("attribute-logic-matched")).toHaveTextContent("Yes");
expect(screen.getByTestId("attribute-logic-fallback-matched")).toHaveTextContent("Not needed");
// Skip the matching members check as it's giving issues
});
it("suggests to add fallback when matching members is empty and fallback is not checked", async () => {
mockEventTypeRedirectUrlMatchingRoute();
mockFindTeamMembersMatchingAttributeLogicResponse({
result: {
users: [],
},
checkedFallback: false,
});
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("john/30min");
expect(screen.getByTestId("attribute-logic-matched")).toHaveTextContent("Yes");
expect(screen.getByTestId("attribute-logic-fallback-matched")).toHaveTextContent("Not needed");
// Skip the matching members check as it's giving issues
});
it("shows warnings when there are warnings", async () => {
mockEventTypeRedirectUrlMatchingRoute();
mockFindTeamMembersMatchingAttributeLogicResponse({
result: null,
checkedFallback: false,
mainWarnings: ["Main-Error-1", "Main-Error-2"],
fallbackWarnings: ["Fallback-Error-1", "Fallback-Error-2"],
});
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
// Get all alerts without checking their specific count
const alerts = screen.getAllByTestId("alert");
// Verify that at least the main and fallback warnings are present
expect(alerts.some((alert) => alert.textContent?.includes("Main-Error-1"))).toBe(true);
expect(alerts.some((alert) => alert.textContent?.includes("Main-Error-2"))).toBe(true);
expect(alerts.some((alert) => alert.textContent?.includes("Fallback-Error-1"))).toBe(true);
expect(alerts.some((alert) => alert.textContent?.includes("Fallback-Error-2"))).toBe(true);
});
it("should not show warnings when there are no warnings", async () => {
mockEventTypeRedirectUrlMatchingRoute();
mockFindTeamMembersMatchingAttributeLogicResponse({
result: null,
checkedFallback: false,
mainWarnings: null,
fallbackWarnings: null,
});
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
screen.logTestingPlaygroundURL();
const alerts = screen.queryAllByTestId("alert");
expect(alerts).toHaveLength(0);
});
it("should show No in main and fallback matched", async () => {
mockEventTypeRedirectUrlMatchingRoute();
mockFindTeamMembersMatchingAttributeLogicResponse({
result: {
users: [],
},
checkedFallback: true,
mainWarnings: null,
fallbackWarnings: null,
});
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("attribute-logic-matched")).toHaveTextContent("No");
expect(screen.getByTestId("attribute-logic-fallback-matched")).toHaveTextContent("Yes");
// Skip the matching members check as it's giving issues
});
});
describe("Regular Team Form", () => {
const form = mockRegularTeamForm;
it("submits the form and shows test results for Custom Page", async () => {
mockCustomPageMessageMatchingRoute();
render(
<TestFormRenderer
isMobile={true}
testForm={mockRegularTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("Thank you for submitting!");
});
it("submits the form and shows test results for Event Type", async () => {
mockEventTypeRedirectUrlMatchingRoute();
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("john/30min");
// When we support showing matching route we can add this back
// expect(screen.getByTestId("chosen-route")).toHaveTextContent("Route 2");
});
it("should substitute variables in event redirect URL", async () => {
// Mock a route with variables using the name field that already exists
mockMatchingRoute({
action: {
type: "eventTypeRedirectUrl",
value: "/team/{name}/meeting",
},
});
render(
<TestFormRenderer
isMobile={true}
testForm={mockRegularTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
// Fill in the name field
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "Sales Team" } });
fireEvent.click(screen.getByText("submit"));
// Verify the URL shows the substituted value, not the variable
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("/team/sales-team/meeting");
expect(screen.getByTestId("test-routing-result")).not.toHaveTextContent("{name}");
});
it("should NOT substitute variables in external redirect URL", async () => {
// Mock a route with variables for external redirect
mockMatchingRoute({
action: {
type: "externalRedirectUrl",
value: "https://example.com/user/{name}",
},
});
render(
<TestFormRenderer
isMobile={true}
testForm={mockRegularTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
// Verify the URL shows the variable as-is, without substitution
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("https://example.com/user/{name}");
expect(screen.getByTestId("test-routing-result")).not.toHaveTextContent("john-doe");
});
});
});