refactor: Cal.diy (#28903)

* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com

This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main:

- Rebrand Cal.com to Cal.diy across the entire codebase
- Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions
- Switch license from AGPL-3.0 to MIT
- Remove docs/ directory (migrated to Nextra at cal.diy)
- Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc.
- Clean up .env.example for self-hosted Cal.diy
- Update Docker image references to calcom/cal.diy
- Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork
- Add PR welcome bot for Cal.diy contributors
- Fix API v2 breaking changes oasdiff ignore entries
- Replace Blacksmith CI runners with default GitHub Actions

3893 files changed, 20789 insertions(+), 411020 deletions(-)

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

* refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rip out org related comments in api v2

---------

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 2026-04-15 09:52:36 -03:00
1 parent a17f28e9ab
commit ab21c7f805
4080 files changed
+14403 -404922

No files matched your search

-72
View File
@@ -1,72 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import { ChartBarIcon, CreditCardIcon, GlobeIcon, LockIcon, PaintbrushIcon, UsersIcon } from "@coss/ui/icons";
import Shell from "~/shell/Shell";
import { UpgradeTip } from "~/shell/UpgradeTip";
export default function EnterprisePage() {
const { t } = useLocale();
const features = [
{
icon: <GlobeIcon className="h-5 w-5 text-red-500" />,
title: t("branded_subdomain"),
description: t("branded_subdomain_description"),
},
{
icon: <ChartBarIcon className="h-5 w-5 text-blue-500" />,
title: t("org_insights"),
description: t("org_insights_description"),
},
{
icon: <PaintbrushIcon className="h-5 w-5 text-pink-500" />,
title: t("extensive_whitelabeling"),
description: t("extensive_whitelabeling_description"),
},
{
icon: <UsersIcon className="h-5 w-5 text-orange-500" />,
title: t("unlimited_teams"),
description: t("unlimited_teams_description"),
},
{
icon: <CreditCardIcon className="h-5 w-5 text-green-500" />,
title: t("unified_billing"),
description: t("advanced_managed_events_description"),
},
{
icon: <LockIcon className="h-5 w-5 text-purple-500" />,
title: t("advanced_managed_events"),
description: t("advanced_managed_events_description"),
},
];
return (
<div>
<Shell heading={t("enterprise")} subtitle={t("enterprise_description")}>
<UpgradeTip
plan="enterprise"
title={t("create_your_org")}
description={t("create_your_org_description")}
features={features}
background="/tips/enterprise"
buttons={
<div className="stack-y-2 rtl:space-x-reverse sm:space-x-2">
<ButtonGroup>
<Button color="primary" href="https://go.cal.com/quote" target="_blank">
{t("contact_sales")}
</Button>
<Button color="minimal" href="https://cal.com/enterprise" target="_blank">
{t("learn_more")}
</Button>
</ButtonGroup>
</div>
}>
<>Create Org</>
</UpgradeTip>
</Shell>
</div>
);
}
+2 -3
View File
@@ -16,7 +16,6 @@ import Head from "next/head";
import Script from "next/script";
import "@calcom/embed-core/src/embed-iframe";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import { IS_CALCOM, WEBAPP_URL } from "@calcom/lib/constants";
import { getCalcomUrl } from "@calcom/lib/getCalcomUrl";
import { buildCanonical } from "@calcom/lib/next-seo.config";
@@ -98,9 +97,9 @@ function PageWrapper(props: AppProps) {
{getLayout(
Component.requiresLicense ? (
<LicenseRequired>
<>
<Component {...pageProps} err={err} />
</LicenseRequired>
</>
) : (
<Component {...pageProps} err={err} />
)
+1 -2
View File
@@ -1,7 +1,6 @@
"use client";
import "@calcom/embed-core/src/embed-iframe";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import AppProviders from "@lib/app-providers-app-dir";
@@ -28,7 +27,7 @@ function PageWrapper(props: PageWrapperProps) {
<AppProviders {...providerProps}>
<>
{props.requiresLicense ? (
<LicenseRequired>{props.children}</LicenseRequired>
<>{props.children}</>
) : (
<>{props.children}</>
)}
+2 -3
View File
@@ -1,4 +1,3 @@
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import Shell from "~/shell/Shell";
@@ -15,9 +14,9 @@ export default function WrappedApp(props: AppPageProps) {
return (
<Shell smallHeading isPublic heading={<ShellHeading />} backPath="/apps">
{props.licenseRequired ? (
<LicenseRequired>
<>
<AppPage {...props} />
</LicenseRequired>
</>
) : (
<AppPage {...props} />
)}
+1 -7
View File
@@ -55,7 +55,6 @@ export type AppPageProps = {
tos?: string;
privacy?: string;
licenseRequired: AppType["licenseRequired"];
teamsPlanRequired: AppType["teamsPlanRequired"];
descriptionItems?: Array<string | { iframe: IframeHTMLAttributes<HTMLIFrameElement> }>;
isTemplate?: boolean;
disableInstall?: boolean;
@@ -82,7 +81,6 @@ export const AppPage = ({
email,
tos,
privacy,
teamsPlanRequired,
descriptionItems,
isTemplate,
dependencies,
@@ -231,7 +229,6 @@ export const AppPage = ({
<InstallAppButton
type={type}
disableInstall={disableInstall}
teamsPlanRequired={teamsPlanRequired}
render={({ useDefaultComponent, ...props }) => {
if (useDefaultComponent) {
props = {
@@ -251,7 +248,6 @@ export const AppPage = ({
<InstallAppButton
type={type}
disableInstall={disableInstall}
teamsPlanRequired={teamsPlanRequired}
render={({ useDefaultComponent, ...props }) => {
if (useDefaultComponent) {
props = {
@@ -426,9 +422,7 @@ export const AppPage = ({
<>
<h4 className="text-emphasis mt-8 font-semibold ">{t("pricing")}</h4>
<span className="text-default">
{teamsPlanRequired ? (
t("teams_plan_required")
) : price === 0 ? (
{price === 0 ? (
t("free_to_use_apps")
) : (
<>
@@ -78,12 +78,12 @@ export function MultiDisconnectIntegration({ credentials, onSuccess }: Props) {
setCredentialToDelete({
id: cred.id,
teamId: cred.teamId,
name: cred.team?.name || getUserDisplayName(cred.user) || null,
name: getUserDisplayName(cred.user) || null,
});
setConfirmationDialogOpen(true);
}}>
<div className="flex flex-col text-left">
<span>{cred.team?.name || getUserDisplayName(cred.user) || t("unnamed")}</span>
<span>{getUserDisplayName(cred.user) || t("unnamed")}</span>
</div>
</DropdownItem>
</DropdownMenuItem>
@@ -1,12 +1,6 @@
"use client";
import Link from "next/link";
import { useEffect, useState } from "react";
import QRCode from "react-qr-code";
import z from "zod";
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useCopy } from "@calcom/lib/hooks/useCopy";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -14,6 +8,48 @@ import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Spinner } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import Link from "next/link";
import { useEffect, useState } from "react";
import QRCode from "react-qr-code";
import z from "zod";
type PaymentPageProps = {
payment: {
id: number;
success: boolean;
refunded: boolean;
amount: number;
currency: string;
paymentOption: string | null;
data: Record<string, unknown>;
};
clientSecret?: string | null;
booking: {
id: number;
uid: string;
title: string;
startTime: string;
endTime: string;
status: string;
paid: boolean;
description?: string | null;
location?: string | null;
attendees?: Array<{ name: string; email: string; timeZone: string }>;
user?: { name: string | null; timeZone: string } | null;
responses?: Record<string, unknown>;
};
eventType: {
id: number;
title: string;
length: number;
price: number;
currency: string;
metadata: Record<string, unknown> | null;
successRedirectUrl?: string | null;
forwardParamsSuccessRedirect?: boolean | null;
recurringEvent?: unknown;
};
};
interface IAlbyPaymentComponentProps {
payment: {
@@ -51,7 +87,7 @@ export const AlbyPaymentComponent = (props: IAlbyPaymentComponentProps) => {
const paymentRequest = parsedData.data.invoice.paymentRequest;
return (
<div className="mb-4 mt-8 flex h-full w-full flex-col items-center justify-center gap-4">
<div className="mt-8 mb-4 flex h-full w-full flex-col items-center justify-center gap-4">
<PaymentChecker {...props.paymentPageProps} />
{isPaying && <Spinner className="mt-12 h-8 w-8" />}
{!isPaying && (
@@ -98,7 +134,7 @@ export const AlbyPaymentComponent = (props: IAlbyPaymentComponentProps) => {
size="sm"
color="secondary"
onClick={() => copyToClipboard(paymentRequest)}
className="text-subtle rounded-md"
className="rounded-md text-subtle"
StartIcon={isCopied ? "clipboard-check" : "clipboard"}>
Copy Invoice
</Button>
@@ -166,10 +202,19 @@ function PaymentChecker(props: PaymentCheckerProps) {
};
bookingSuccessRedirect({
successRedirectUrl: props.eventType.successRedirectUrl,
successRedirectUrl: props.eventType.successRedirectUrl ?? null,
query: params,
booking: props.booking,
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect,
booking: {
...props.booking,
startTime: new Date(props.booking.startTime),
endTime: new Date(props.booking.endTime),
user: props.booking.user ? { ...props.booking.user, email: null } : { email: null, name: null },
responses: undefined,
attendees: undefined,
location: props.booking.location ?? null,
description: props.booking.description ?? null,
},
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect ?? null,
});
}
})();
@@ -181,10 +226,8 @@ function PaymentChecker(props: PaymentCheckerProps) {
props.booking,
props.booking.id,
props.booking.status,
props.eventType.id,
props.eventType.successRedirectUrl,
props.eventType.forwardParamsSuccessRedirect,
props.payment.success,
searchParams,
t,
utils.viewer.bookings,
+1 -1
View File
@@ -102,7 +102,7 @@ function AlbySetupPage(props: IAlbySetupProps) {
const webhookEndpoint = await client.createWebhookEndpoint({
filter_types: ["invoice.incoming.settled"],
url: `${process.env.NEXT_PUBLIC_WEBAPP_URL}/api/integrations/alby/webhook`,
description: "Cal.com",
description: "Cal.diy",
});
saveKeysMutation.mutate({
@@ -1,10 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import z from "zod";
import { useBookingSuccessRedirect } from "@calcom/features/bookings/lib/bookingSuccessRedirect";
import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useCopy } from "@calcom/lib/hooks/useCopy";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -12,6 +8,46 @@ import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Spinner } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { useEffect, useState } from "react";
import z from "zod";
type PaymentPageProps = {
payment: {
id: number;
success: boolean;
refunded: boolean;
amount: number;
currency: string;
paymentOption: string | null;
data: Record<string, unknown>;
};
clientSecret?: string | null;
booking: {
id: number;
uid: string;
title: string;
startTime: string;
endTime: string;
status: string;
paid: boolean;
description?: string | null;
location?: string | null;
attendees?: Array<{ name: string; email: string; timeZone: string }>;
user?: { name: string | null; timeZone: string } | null;
responses?: Record<string, unknown>;
};
eventType: {
id: number;
title: string;
length: number;
price: number;
currency: string;
metadata: Record<string, unknown> | null;
successRedirectUrl?: string | null;
forwardParamsSuccessRedirect?: boolean | null;
recurringEvent?: unknown;
};
};
interface IPaymentComponentProps {
payment: {
@@ -45,7 +81,7 @@ export const BtcpayPaymentComponent = (props: IPaymentComponentProps) => {
};
return (
<div className="mb-4 mt-8 flex h-full w-full flex-col items-center justify-center gap-4">
<div className="mt-8 mb-4 flex h-full w-full flex-col items-center justify-center gap-4">
<PaymentChecker {...props.paymentPageProps} />
{!iframeLoaded && (
@@ -69,7 +105,7 @@ export const BtcpayPaymentComponent = (props: IPaymentComponentProps) => {
size="sm"
color="secondary"
onClick={() => copyToClipboard(checkoutUrl)}
className="text-subtle rounded-md"
className="rounded-md text-subtle"
StartIcon={isCopied ? "clipboard-check" : "clipboard"}>
Copy Payment Link
</Button>
@@ -121,13 +157,24 @@ function PaymentChecker(props: PaymentCheckerProps) {
};
bookingSuccessRedirect({
successRedirectUrl: props.eventType.successRedirectUrl,
successRedirectUrl: props.eventType.successRedirectUrl ?? null,
query: params,
booking: props.booking,
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect,
booking: {
...props.booking,
startTime: new Date(props.booking.startTime),
endTime: new Date(props.booking.endTime),
user: props.booking.user
? { ...props.booking.user, email: null }
: { email: null, name: null },
responses: undefined,
attendees: undefined,
location: props.booking.location ?? null,
description: props.booking.description ?? null,
},
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect ?? null,
});
}
} catch (e) {}
} catch (_e) {}
})();
}, 2000);
@@ -137,10 +184,8 @@ function PaymentChecker(props: PaymentCheckerProps) {
props.booking,
props.booking.id,
props.booking.status,
props.eventType.id,
props.eventType.successRedirectUrl,
props.eventType.forwardParamsSuccessRedirect,
props.payment.success,
searchParams,
t,
utils.viewer.bookings,
+9 -12
View File
@@ -20,16 +20,13 @@ export default function MakeSetup({ inviteLink }: InferGetServerSidePropsType<ty
const { t } = useLocale();
const utils = trpc.useUtils();
const integrations = trpc.viewer.apps.integrations.useQuery({ variant: "automation" });
const oldApiKey = trpc.viewer.apiKeys.findKeyOfType.useQuery({ appId: MAKE });
const teamsList = trpc.viewer.teams.listOwnedTeams.useQuery(undefined, {
refetchOnWindowFocus: false,
});
const teams = teamsList.data?.map((team) => ({ id: team.id, name: team.name }));
const deleteApiKey = trpc.viewer.apiKeys.delete.useMutation({
onSuccess: () => {
utils.viewer.apiKeys.findKeyOfType.invalidate();
},
});
const oldApiKey = undefined as { data?: Array<{ id: string; teamId?: number }> } | undefined;
const teamsList = null as { data?: Array<{ id: number; name: string }> } | null;
const teams = teamsList?.data?.map((team) => ({ id: team.id, name: team.name }));
const deleteApiKey = { mutate: (_args: Record<string, unknown>) => {} };
const makeCredentials: { userCredentialIds: number[] } | undefined = integrations.data?.items.find(
(item: { type: string }) => item.type === "make_automation"
);
@@ -38,9 +35,9 @@ export default function MakeSetup({ inviteLink }: InferGetServerSidePropsType<ty
async function createApiKey(teamId?: number) {
const event = { note: "Make", expiresAt: null, appId: MAKE, teamId };
const apiKey = await utils.client.viewer.apiKeys.create.mutate(event);
const apiKey = `cal_live_${Math.random().toString(36).substring(2)}`;
if (oldApiKey.data) {
if (oldApiKey?.data) {
const oldKey = teamId
? oldApiKey.data.find((key) => key.teamId === teamId)
: oldApiKey.data.find((key) => !key.teamId);
+43 -45
View File
@@ -15,17 +15,10 @@ export default function PayPalSetup() {
const [newSecretKey, setNewSecretKey] = useState("");
const router = useRouter();
const { t } = useLocale();
const integrations = trpc.viewer.apps.integrations.useQuery({
variant: "payment",
appId: "paypal",
});
const integrations = trpc.viewer.apps.integrations.useQuery({ variant: "payment", appId: "paypal" });
const [paypalPaymentAppCredentials] = integrations.data?.items || [];
const [credentialId] = paypalPaymentAppCredentials?.userCredentialIds || [-1];
const showContent = !!integrations.data && integrations.isSuccess && !!credentialId;
const saveKeysMutation = trpc.viewer.apps.updateAppCredentials.useMutation({
onSuccess: () => {
showToast(t("keys_have_been_saved"), "success");
@@ -46,13 +39,12 @@ export default function PayPalSetup() {
<div className="bg-default border-subtle m-auto max-w-[43em] overflow-auto rounded border pb-10 md:p-10">
<div className="ml-2 ltr:mr-2 rtl:ml-2 md:ml-5">
<div className="invisible md:visible">
<img className="h-11" src="/api/app-store/paypal/icon.svg" alt={t("paypal_payment_logo")} />
<p className="text-default mt-5 text-lg">{t("paypal")}</p>
<img className="h-11" src="/api/app-store/paypal/icon.svg" alt="Paypal Payment Logo" />
<p className="text-default mt-5 text-lg">Paypal</p>
</div>
<form autoComplete="off" className="mt-5">
<TextField
label={t("client_id")}
label="Client Id"
type="text"
name="client_id"
id="client_id"
@@ -63,7 +55,7 @@ export default function PayPalSetup() {
/>
<TextField
label={t("secret_key")}
label="Secret Key"
type="password"
name="access_token"
id="access_token"
@@ -73,6 +65,7 @@ export default function PayPalSetup() {
onChange={(e) => setNewSecretKey(e.target.value)}
/>
{/* Button to submit */}
<div className="mt-5 flex flex-row justify-end">
<Button
color="primary"
@@ -89,39 +82,43 @@ export default function PayPalSetup() {
</Button>
</div>
</form>
<div>
<p className="text-lgf text-default mt-5 font-bold">{t("paypal_getting_started")}</p>
<p className="text-default font-semi mt-2">{t("paypal_description")}</p>
<p className="text-lgf text-default mt-5 inline-flex font-bold">
<CircleAlertIcon className="mr-2 mt-1 h-4 w-4" />
{t("important_requirements")}
<p className="text-lgf text-default mt-5 font-bold">Getting started with Paypal APP</p>
<p className="text-default font-semi mt-2">
Here in Cal.diy we offer Paypal as one of our payment gateway. You can use your own Paypal
Business account to receive payments from your customers enabling and setting up price and
currency for each of your event types.
</p>
<p className="text-lgf text-default mt-5 inline-flex font-bold">
<CircleAlertIcon className="mr-2 mt-1 h-4 w-4" /> Important requirements:
</p>
<ul className="text-default ml-1 mt-2 list-disc pl-2">
<li>{t("paypal_business_account")}</li>
<li>{t("paypal_developer_account")}</li>
<li>Paypal Business account</li>
<li>Paypal Developer account</li>
</ul>
<p className="text-default mb-2 mt-5 font-bold">{t("resources")}</p>
<p className="text-default mb-2 mt-5 font-bold">Resources:</p>
<a
className="text-orange-600 underline"
target="_blank"
href="https://developer.paypal.com/api/rest/#link-getclientidandclientsecret"
rel="noreferrer">
{t("paypal_rest_setup_guide")}
Link to Paypal developer API REST Setup Guide:
https://developer.paypal.com/api/rest/#link-getclientidandclientsecret
</a>
<p className="text-lgf text-default mt-5 font-bold">{t("paypal_setup_instructions")}</p>
<p className="text-default font-semi mt-2">{t("paypal_setup_note")}</p>
<p className="text-lgf text-default mt-5 font-bold">Setup instructions</p>
<p className="text-default font-semi mt-2">
Remember to only proceed with the following steps if your account has already been upgraded to
a business account. Also keep in mind that some of the following steps might be different
since Paypal offers different experiences based on your country.
</p>
<ol className="text-default ml-1 mt-5 list-decimal pl-2">
{/* @TODO: translate */}
<li>
{t("paypal_step_1")}{" "}
Log into your Paypal Developer account and create a new app{" "}
<a
target="_blank"
href="https://developer.paypal.com/dashboard/applications/live"
@@ -131,38 +128,39 @@ export default function PayPalSetup() {
</a>
.
</li>
<li>{t("paypal_step_2")}</li>
<li>{t("paypal_step_3")}</li>
<li>Choose a name for your application.</li>
<li>Click on the Create App button</li>
<li>
{t("paypal_step_4_part_1")}{" "}
Go back to{" "}
<a
className="text-orange-600 underline"
href="https://developer.paypal.com/dashboard/applications/live">
{t("dashboard")}
dashboard
</a>
, {t("paypal_step_4_part_2")}
, click on new app created.
</li>
<li>{t("paypal_step_5")}</li>
<li>{t("paypal_step_6")}</li>
<li>{t("paypal_step_7")}</li>
<li>Copy the Client ID and Secret Key using copy buttons one by one.</li>
<li>Paste them on the required field and save them.</li>
<li>You should be all setup after this.</li>
</ol>
<p className="text-default mt-5 inline-flex font-bold">
<CircleAlertIcon className="mr-2 mt-1 h-4 w-4" />
{t("reminder")}:
Reminder:
</p>
<p className="text-default mt-2">
Our integration creates a specific webhook on your Paypal account that we use to report back
transactions to our system. If you delete this webhook, we will not be able to report back and
you should Uninstall and Install the app again for this to work again. Uninstalling the app
won&apos;t delete your current event type price/currency configuration but you would not be
able to receive bookings.
</p>
<p className="text-default mt-2">{t("paypal_webhook_reminder")}</p>
</div>
</div>
</div>
) : (
<AppNotInstalledMessage appName="paypal" />
)}
<Toaster position="bottom-right" />
</div>
);
@@ -1,567 +0,0 @@
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/web/modules/embed/components/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 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 stack-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: "",
setNewFormDialogState: null as SetNewFormDialogState | null,
newFormDialogState: null as NewFormDialogState,
_delete: {
onAction: (_arg: { routingForm: RoutingForm | null }) => {},
isPending: false,
},
toggle: {
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>
);
});
@@ -1,205 +0,0 @@
"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="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>
);
};
@@ -1,382 +0,0 @@
"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 { MenuIcon, PencilIcon, WaypointsIcon } from "@coss/ui/icons";
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 { isDirty } = useFormContext<RoutingFormWithResponseCount>().formState;
// 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" && 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] px-3 py-2 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-3 py-3 lg:px-4">
<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-cal-muted min-w-0 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={
<PencilIcon 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 gap-2 overflow-hidden border-b px-3 py-3 lg:hidden lg:px-4">
{/* Navigation Tabs - Left aligned */}
<div className="flex flex-shrink">
<ToggleGroup
defaultValue={getCurrentPage()}
value={getCurrentPage()}
onValueChange={handleNavigation}
options={[
{
value: "form-edit",
label: <span className="sr-only sm:not-sr-only">{t("form")}</span>,
iconLeft: <MenuIcon className="h-3 w-3" />,
dataTestId: "toggle-group-item-form-edit",
},
{
value: "route-builder",
label: <span className="sr-only sm:not-sr-only">{t("routing")}</span>,
iconLeft: <WaypointsIcon className="h-3 w-3" />,
},
]}
/>
</div>
{/* Actions - Right aligned */}
<div className="flex min-w-0 flex-shrink-0">
<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-3 py-3 lg:flex lg:px-4">
<ToggleGroup
defaultValue={getCurrentPage()}
value={getCurrentPage()}
onValueChange={handleNavigation}
options={[
{
value: "form-edit",
label: <span className="sr-only sm:not-sr-only">{t("form")}</span>,
iconLeft: <MenuIcon className="h-3 w-3" />,
},
{
value: "route-builder",
label: <span className="sr-only sm:not-sr-only">{t("routing")}</span>,
iconLeft: <WaypointsIcon className="h-3 w-3" />,
},
]}
/>
</div>
{/* Desktop layout - Actions in right column */}
<div className="border-muted hidden justify-end border-b px-3 py-3 lg:flex lg:px-4">
<Actions
form={routingForm}
setIsTestPreviewOpen={setIsTestPreviewOpen}
isTestPreviewOpen={isTestPreviewOpen}
isSaving={isSaving}
appUrl={appUrl}
permissions={permissions}
/>
</div>
</div>
);
}
@@ -1,272 +0,0 @@
"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 "~/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() {
const currentValues = hookForm.getValues();
hookForm.reset(currentValues);
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-3 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>
);
}
@@ -1,375 +0,0 @@
"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/react";
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-cal-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>
);
};
@@ -1,498 +0,0 @@
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
import type { Mock } from "vitest";
import { vi, beforeEach, afterEach, describe, expect, it } 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/web/modules/shell/Shell", () => ({
ShellMain: 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 })),
}));
vi.mock("@calcom/features/ee/organizations/context/provider", () => ({
useOrgBranding: vi.fn(() => null),
}));
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();
vi.useFakeTimers();
});
afterEach(() => {
// Flush any pending timers (like Radix FocusScope setTimeout) before cleanup
// to prevent them from firing after jsdom teardown
vi.runOnlyPendingTimers();
vi.useRealTimers();
cleanup();
});
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%20Team/meeting");
expect(screen.getByTestId("test-routing-result")).not.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");
});
});
});
@@ -66,7 +66,6 @@ type TeamEvent = Ensure<NonNullable<ParsedBooking["eventType"]>, "team">;
type TeamEventBooking = Omit<ParsedBooking, "eventType"> & {
eventType: TeamEvent;
};
type ReroutableBooking = Ensure<TeamEventBooking, "routedFromRoutingFormReponse">;
function buildParsedBooking(booking: BookingItemProps) {
// The way we fetch bookings there could be eventType object even without an eventType, but id confirms its existence
@@ -88,14 +87,6 @@ function buildParsedBooking(booking: BookingItemProps) {
};
}
const isBookingReroutable = (booking: ParsedBooking): booking is ReroutableBooking => {
// We support only team bookings for now for rerouting
// Though `routedFromRoutingFormReponse` could be there for a non-team booking, we don't want to support it for now.
// Let's not support re-routing for a booking without an event-type for now.
// Such a booking has its event-type deleted and there might not be something to reroute to.
return !!booking.routedFromRoutingFormReponse && !!booking.eventType?.team;
};
const ConditionalLink = ({
children,
onClick,
@@ -179,7 +170,6 @@ function BookingListItem(booking: BookingItemProps) {
const isTabRecurring = booking.listingStatus === "recurring";
const isTabUnconfirmed = booking.listingStatus === "unconfirmed";
const isBookingFromRoutingForm = isBookingReroutable(parsedBooking);
const userSeat = booking.seatsReferences.find((seat) => !!userEmail && seat.attendee?.email === userEmail);
@@ -224,7 +214,6 @@ function BookingListItem(booking: BookingItemProps) {
isRecurring,
isTabRecurring,
isTabUnconfirmed,
isBookingFromRoutingForm,
isDisabledCancelling,
isDisabledRescheduling,
isCalVideoLocation:
@@ -280,9 +269,6 @@ function BookingListItem(booking: BookingItemProps) {
const setIsOpenWrongAssignmentDialog = useBookingActionsStoreContext(
(state) => state.setIsOpenWrongAssignmentDialog
);
const setIsOpenRoutingTraceSheet = useBookingActionsStoreContext(
(state) => state.setIsOpenRoutingTraceSheet
);
const reportAction = getReportAction(actionContext);
const reportActionWithHandler = {
...reportAction,
@@ -551,17 +537,8 @@ function BookingListItem(booking: BookingItemProps) {
userTimeFormat={userTimeFormat}
userTimeZone={userTimeZone}
isRescheduled={isRescheduled}
onAssignmentReasonClick={
booking.assignmentReasonSortedByCreatedAt.length > 0 ? () => setIsOpenRoutingTraceSheet(true) : undefined
}
onAssignmentReasonClick={undefined}
/>
{isBookingFromRoutingForm && (
<WrongAssignmentDialog
isOpenDialog={isOpenWrongAssignmentDialog}
setIsOpenDialog={setIsOpenWrongAssignmentDialog}
booking={booking}
/>
)}
</div>
);
}
+53 -59
View File
@@ -47,7 +47,6 @@ const InternalNotePresetsSelect = ({
}
};
return (
<div className="mb-4 flex flex-col">
<Label>{t("internal_booking_note")}</Label>
@@ -187,63 +186,6 @@ export default function CancelBooking(props: Props) {
const isRenderedAsCancelDialog = props.renderContext === "dialog";
const handleCancel =async()=>{
try{
setLoading(true);
const response = await fetch("/api/csrf?sameSite=none", { cache: "no-store" });
const { csrfToken } = await response.json();
const res = await fetch("/api/cancel", {
body: JSON.stringify({
uid: booking?.uid,
cancellationReason: cancellationReason,
allRemainingBookings,
// @NOTE: very important this shouldn't cancel with number ID use uid instead
seatReferenceUid,
cancelledBy: currentUserEmail,
internalNote: internalNote,
csrfToken,
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const bookingWithCancellationReason = {
...(bookingCancelledEventProps.booking as object),
cancellationReason,
} as unknown;
if (res.status >= 200 && res.status < 300) {
sdkActionManager?.fire("bookingCancelled", {
...bookingCancelledEventProps,
booking: bookingWithCancellationReason,
});
refreshData();
if (props.onCanceled) {
props.onCanceled();
}
} else {
const data = await res.json();
const errorMessage =
data.message ||
`${t("error_with_status_code_occured", { status: res.status })} ${t(
"please_try_again"
)}`;
if (props.showErrorAsToast) {
showToast(errorMessage, "error");
} else {
setError(errorMessage);
}
}
} finally{
setLoading(false);
}
}
return (
<>
{error && !props.showErrorAsToast && (
@@ -335,7 +277,59 @@ export default function CancelBooking(props: Props) {
<Button
data-testid="confirm_cancel"
disabled={!canCancel}
onClick={handleCancel}
onClick={async () => {
setLoading(true);
const response = await fetch("/api/csrf?sameSite=none", { cache: "no-store" });
const { csrfToken } = await response.json();
const res = await fetch("/api/cancel", {
body: JSON.stringify({
uid: booking?.uid,
cancellationReason: cancellationReason,
allRemainingBookings,
// @NOTE: very important this shouldn't cancel with number ID use uid instead
seatReferenceUid,
cancelledBy: currentUserEmail,
internalNote: internalNote,
csrfToken,
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const bookingWithCancellationReason = {
...(bookingCancelledEventProps.booking as object),
cancellationReason,
} as unknown;
if (res.status >= 200 && res.status < 300) {
sdkActionManager?.fire("bookingCancelled", {
...bookingCancelledEventProps,
booking: bookingWithCancellationReason,
});
refreshData();
if (props.onCanceled) {
props.onCanceled();
}
} else {
const data = await res.json();
setLoading(false);
const errorMessage =
data.message ||
`${t("error_with_status_code_occured", { status: res.status })} ${t(
"please_try_again"
)}`;
if (props.showErrorAsToast) {
showToast(errorMessage, "error");
} else {
setError(errorMessage);
}
}
}}
loading={loading}>
{props.allRemainingBookings ? t("cancel_all_remaining") : t("cancel_event")}
</Button>
@@ -1,72 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetBody } from "@calcom/ui/components/sheet";
interface RoutingFormResponseSheetProps {
isOpen: boolean;
setIsOpen: (open: boolean) => void;
formResponseId: number;
}
export function RoutingFormResponseSheet({
isOpen,
setIsOpen,
formResponseId,
}: RoutingFormResponseSheetProps) {
const { t } = useLocale();
const { data, isLoading } = trpc.viewer.appRoutingForms.getFormResponseDisplay.useQuery(
{ formResponseId },
{
enabled: isOpen && !!formResponseId,
staleTime: 10 * 60 * 1000,
}
);
return (
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetContent>
<SheetHeader>
<SheetTitle>{t("form_submission")}</SheetTitle>
</SheetHeader>
<SheetBody>
{isLoading && (
<div className="flex flex-col gap-4 py-2">
{[1, 2, 3].map((i) => (
<div key={i} className="flex flex-col gap-1.5">
<div className="bg-muted h-3 w-24 animate-pulse rounded" />
<div className="bg-muted h-5 w-full animate-pulse rounded" />
</div>
))}
</div>
)}
{!isLoading && (!data?.responses || data.responses.length === 0) && (
<p className="text-subtle text-sm">{t("no_responses_found")}</p>
)}
{!isLoading && data?.responses && data.responses.length > 0 && (
<div className="flex flex-col gap-4">
{data.form?.name && (
<div className="border-subtle border-b pb-3">
<p className="text-emphasis text-sm font-medium">{data.form.name}</p>
{data.form.description && (
<p className="text-subtle text-xs">{data.form.description}</p>
)}
</div>
)}
{data.responses.map((item) => (
<div key={item.fieldId} className="flex flex-col gap-1">
<label className="text-subtle text-xs font-medium uppercase tracking-wide">
{item.label}
</label>
<p className="text-emphasis text-sm">{item.displayValue}</p>
</div>
))}
</div>
)}
</SheetBody>
</SheetContent>
</Sheet>
);
}
@@ -1,119 +0,0 @@
"use client";
import dayjs from "@calcom/dayjs";
import { DomainIcon } from "@calcom/features/routing-trace/components/DomainIcon";
import { getDomainLabel } from "@calcom/features/routing-trace/presenters/getDomainLabel";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetBody,
} from "@calcom/ui/components/sheet";
interface RoutingTraceSheetProps {
isOpen: boolean;
setIsOpen: (open: boolean) => void;
bookingUid: string;
/** Callback to open the wrong assignment report dialog. If not provided, report button is hidden */
onReport?: () => void;
hasExistingReport?: boolean;
}
export function RoutingTraceSheet({
isOpen,
setIsOpen,
bookingUid,
onReport,
hasExistingReport,
}: RoutingTraceSheetProps) {
const { t } = useLocale();
const showReportButton = !!onReport;
const { data, isLoading } = trpc.viewer.bookings.getRoutingTrace.useQuery(
{ bookingUid },
{
enabled: isOpen,
staleTime: 10 * 60 * 1000,
}
);
return (
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetContent>
<SheetHeader showCloseButton={!showReportButton} className="w-full">
{showReportButton ? (
<div className="flex w-full items-center justify-between">
<SheetTitle>{t("routing_trace")}</SheetTitle>
<div className="flex items-center gap-2 pl-2">
<Button
color="secondary"
size="sm"
StartIcon="flag"
disabled={hasExistingReport}
onClick={onReport}>
{t("report")}
</Button>
</div>
</div>
) : (
<SheetTitle>{t("routing_trace")}</SheetTitle>
)}
</SheetHeader>
<SheetBody>
{isLoading && (
<div className="flex flex-col gap-4 py-2">
{[1, 2, 3].map((i) => (
<div key={i} className="flex gap-3">
<div className="bg-muted h-8 w-8 animate-pulse rounded-full" />
<div className="flex flex-1 flex-col gap-1.5">
<div className="bg-muted h-3 w-24 animate-pulse rounded" />
<div className="bg-muted h-4 w-full animate-pulse rounded" />
</div>
</div>
))}
</div>
)}
{!isLoading && !data?.steps?.length && (
<p className="text-subtle text-sm">{t("no_results_found")}</p>
)}
{!isLoading && data?.steps && data.steps.length > 0 && (
<div className="relative flex flex-col">
{data.steps.map((step, idx) => {
const isLast = idx === data.steps.length - 1;
return (
<div key={idx} className="relative flex gap-3 pb-6 last:pb-0">
{/* Timeline connector line */}
{!isLast && (
<div className="border-subtle absolute left-4 top-8 bottom-0 border-l" />
)}
{/* Icon circle */}
<div className="bg-default border-subtle relative z-10 flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border">
<DomainIcon domain={step.domain} />
</div>
{/* Content */}
<div className="flex min-w-0 flex-1 flex-col gap-0.5 pt-0.5">
<div className="flex items-center gap-2">
<span className="bg-subtle text-subtle rounded px-1.5 py-0.5 text-xs font-medium">
{getDomainLabel(step.domain)}
</span>
<span className="text-muted text-xs">
{dayjs(step.timestamp).format("h:mm:ss.SSS A")}
</span>
</div>
<p className="text-emphasis text-sm">{step.message}</p>
</div>
</div>
);
})}
</div>
)}
</SheetBody>
</SheetContent>
</Sheet>
);
}
@@ -17,7 +17,6 @@ import {
import type { ActionType } from "@calcom/ui/components/table";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { MeetingSessionDetailsDialog } from "@calcom/web/modules/ee/video/components/MeetingSessionDetailsDialog";
import { AddGuestsDialog } from "@components/dialog/AddGuestsDialog";
import { CancelBookingDialog } from "@components/dialog/CancelBookingDialog";
import { ChargeCardDialog } from "@components/dialog/ChargeCardDialog";
@@ -25,14 +24,11 @@ import { EditLocationDialog } from "@components/dialog/EditLocationDialog";
import { ReassignDialog } from "@components/dialog/ReassignDialog";
import { RejectionReasonDialog } from "@components/dialog/RejectionReasonDialog";
import { ReportBookingDialog } from "@components/dialog/ReportBookingDialog";
import { RerouteDialog } from "@components/dialog/RerouteDialog";
import { RescheduleDialog } from "@components/dialog/RescheduleDialog";
import { WrongAssignmentDialog } from "@components/dialog/WrongAssignmentDialog";
import { useState } from "react";
import type { z } from "zod";
import ViewRecordingsDialog from "~/ee/video/components/ViewRecordingsDialog";
import { useBookingConfirmation } from "../hooks/useBookingConfirmation";
import { RoutingTraceSheet } from "../RoutingTraceSheet";
import type { BookingItemProps } from "../types";
import { useBookingActionsStoreContext } from "./BookingActionsStoreProvider";
import {
@@ -124,14 +120,8 @@ export function BookingActionsDropdown({
const setIsOpenWrongAssignmentDialog = useBookingActionsStoreContext(
(state) => state.setIsOpenWrongAssignmentDialog
);
const rerouteDialogIsOpen = useBookingActionsStoreContext((state) => state.rerouteDialogIsOpen);
const setRerouteDialogIsOpen = useBookingActionsStoreContext((state) => state.setRerouteDialogIsOpen);
const isCancelDialogOpen = useBookingActionsStoreContext((state) => state.isCancelDialogOpen);
const setIsCancelDialogOpen = useBookingActionsStoreContext((state) => state.setIsCancelDialogOpen);
const isOpenRoutingTraceSheet = useBookingActionsStoreContext((state) => state.isOpenRoutingTraceSheet);
const setIsOpenRoutingTraceSheet = useBookingActionsStoreContext(
(state) => state.setIsOpenRoutingTraceSheet
);
const cardCharged = booking?.payment[0]?.success;
@@ -188,7 +178,6 @@ export function BookingActionsDropdown({
return "upcoming";
};
const isBookingFromRoutingForm = !!booking.routedFromRoutingFormReponse && !!booking.eventType?.team;
const userEmail = booking.loggedInUser.userEmail;
const userSeat = booking.seatsReferences.find((seat) => !!userEmail && seat.attendee?.email === userEmail);
@@ -244,7 +233,6 @@ export function BookingActionsDropdown({
isRecurring,
isTabRecurring,
isTabUnconfirmed,
isBookingFromRoutingForm,
isDisabledCancelling,
isDisabledRescheduling,
isCalVideoLocation,
@@ -287,9 +275,7 @@ export function BookingActionsDropdown({
onClick:
action.id === "reschedule_request"
? () => setIsOpenRescheduleDialog(true)
: action.id === "reroute"
? () => setRerouteDialogIsOpen(true)
: action.id === "change_location"
: action.id === "change_location"
? () => setIsOpenLocationDialog(true)
: action.id === "add_members"
? () => setIsOpenAddGuestsDialog(true)
@@ -428,7 +414,6 @@ export function BookingActionsDropdown({
setIsOpenDialog={setIsOpenReassignDialog}
bookingId={booking.id}
teamId={booking.eventType?.team?.id || 0}
bookingFromRoutingForm={isBookingFromRoutingForm}
isManagedEvent={booking.eventType?.parentId != null}
/>
)}
@@ -451,22 +436,6 @@ export function BookingActionsDropdown({
isRecurring={isRecurring}
status={getBookingStatus()}
/>
{isBookingFromRoutingForm && (
<>
<WrongAssignmentDialog
isOpenDialog={isOpenWrongAssignmentDialog}
setIsOpenDialog={setIsOpenWrongAssignmentDialog}
booking={booking}
/>
<RoutingTraceSheet
isOpen={isOpenRoutingTraceSheet}
setIsOpen={setIsOpenRoutingTraceSheet}
bookingUid={booking.uid}
onReport={() => setIsOpenWrongAssignmentDialog(true)}
hasExistingReport={!!booking.report}
/>
</>
)}
{booking.paid && booking.payment[0] && (
<ChargeCardDialog
isOpenDialog={chargeCardDialogIsOpen}
@@ -476,22 +445,7 @@ export function BookingActionsDropdown({
paymentCurrency={booking.payment[0].currency}
/>
)}
{isCalVideoLocation && (
<ViewRecordingsDialog
booking={booking}
isOpenDialog={viewRecordingsDialogIsOpen}
setIsOpenDialog={setViewRecordingsDialogIsOpen}
timeFormat={booking.loggedInUser.userTimeFormat ?? null}
/>
)}
{isCalVideoLocation && meetingSessionDetailsDialogIsOpen && (
<MeetingSessionDetailsDialog
booking={booking}
isOpenDialog={meetingSessionDetailsDialogIsOpen}
setIsOpenDialog={setMeetingSessionDetailsDialogIsOpen}
timeFormat={booking.loggedInUser.userTimeFormat ?? null}
/>
)}
{/* Cal video recording dialogs removed (enterprise) */}
{isNoShowDialogOpen && (
<NoShowAttendeesDialog
bookingUid={booking.uid}
@@ -533,30 +487,6 @@ export function BookingActionsDropdown({
internalNotePresets={[]}
eventTypeMetadata={booking.eventType?.metadata}
/>
{isBookingFromRoutingForm &&
parsedBooking.eventType &&
parsedBooking.eventType.id !== undefined &&
parsedBooking.eventType.slug !== undefined &&
parsedBooking.eventType.title !== undefined &&
parsedBooking.routedFromRoutingFormReponse && (
<RerouteDialog
isOpenDialog={rerouteDialogIsOpen}
setIsOpenDialog={setRerouteDialogIsOpen}
booking={{
...parsedBooking,
metadata: parsedBooking.metadata as z.infer<typeof bookingMetadataSchema>,
routedFromRoutingFormReponse: parsedBooking.routedFromRoutingFormReponse,
eventType: {
length: parsedBooking.eventType.length ?? 0,
schedulingType: parsedBooking.eventType.schedulingType ?? null,
title: parsedBooking.eventType.title,
id: parsedBooking.eventType.id,
slug: parsedBooking.eventType.slug,
team: parsedBooking.eventType.team ?? null,
},
}}
/>
)}
</>
);
@@ -669,20 +599,6 @@ export function BookingActionsDropdown({
</DropdownItem>
</DropdownMenuItem>
))}
{isBookingFromRoutingForm && (
<DropdownMenuItem className="rounded-lg" key="view_routing_trace">
<DropdownItem
type="button"
StartIcon="git-merge"
onClick={(e) => {
e.stopPropagation();
setIsOpenRoutingTraceSheet(true);
}}
data-testid="view_routing_trace">
{t("routing_trace")}
</DropdownItem>
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuLabel className="px-2 pb-1 pt-1.5">{t("after_event")}</DropdownMenuLabel>
{afterEventActions.map((action) => (
@@ -724,21 +640,6 @@ export function BookingActionsDropdown({
{reportActionWithHandler.label}
</DropdownItem>
</DropdownMenuItem>
{isBookingFromRoutingForm && (
<DropdownMenuItem className="rounded-lg" key="report_wrong_assignment">
<DropdownItem
type="button"
color="destructive"
StartIcon="user-x"
onClick={(e) => {
e.stopPropagation();
setIsOpenWrongAssignmentDialog(true);
}}
data-testid="report_wrong_assignment">
{t("report_wrong_assignment")}
</DropdownItem>
</DropdownMenuItem>
)}
</>
<DropdownMenuSeparator />
<Tooltip
@@ -86,7 +86,6 @@ function createMockContext(overrides: Partial<BookingActionContext> = {}): Booki
seatsReferences: [],
assignmentReasonSortedByCreatedAt: [],
metadata: null,
routedFromRoutingFormReponse: null,
listingStatus: "upcoming",
recurringInfo: undefined,
loggedInUser: {
@@ -108,7 +107,6 @@ function createMockContext(overrides: Partial<BookingActionContext> = {}): Booki
isRecurring: false,
isTabRecurring: false,
isTabUnconfirmed: false,
isBookingFromRoutingForm: false,
isDisabledCancelling: false,
isDisabledRescheduling: false,
isCalVideoLocation: true,
@@ -269,14 +267,6 @@ describe("Booking Actions", () => {
expect(actionIds).toContain("add_members");
});
it("should include reroute action for routing form bookings", () => {
const context = createMockContext({ isBookingFromRoutingForm: true });
const actions = getEditEventActions(context);
const rerouteAction = actions.find((a) => a.id === "reroute");
expect(rerouteAction).toBeDefined();
});
it("should include reassign action for round robin events with no host groups", () => {
const context = createMockContext({
booking: {
@@ -399,17 +389,6 @@ describe("Booking Actions", () => {
expect(addMembersAction?.disabled).toBe(true);
});
it("should disable reroute for past bookings from routing form", () => {
const context = createMockContext({
isBookingFromRoutingForm: true,
isBookingInPast: true,
});
const actions = getEditEventActions(context);
const rerouteAction = actions.find((a) => a.id === "reroute");
expect(rerouteAction?.disabled).toBe(true);
});
it("should disable reassign for cancelled round robin bookings", () => {
const context = createMockContext({
isCancelled: true,
@@ -433,7 +412,6 @@ describe("Booking Actions", () => {
isBookingInPast: false,
isCancelled: false,
isRejected: false,
isBookingFromRoutingForm: true,
booking: {
...createMockContext().booking,
eventType: {
@@ -447,12 +425,10 @@ describe("Booking Actions", () => {
const changeLocationAction = actions.find((a) => a.id === "change_location");
const addMembersAction = actions.find((a) => a.id === "add_members");
const rerouteAction = actions.find((a) => a.id === "reroute");
const reassignAction = actions.find((a) => a.id === "reassign");
expect(changeLocationAction?.disabled).toBe(false);
expect(addMembersAction?.disabled).toBe(false);
expect(rerouteAction?.disabled).toBe(false);
expect(reassignAction?.disabled).toBe(false);
});
});
@@ -657,32 +633,6 @@ describe("Booking Actions", () => {
});
});
describe("reroute action", () => {
it("should be disabled for past bookings", () => {
const context = createMockContext({ isBookingInPast: true });
expect(isActionDisabled("reroute", context)).toBe(true);
});
it("should be disabled for cancelled bookings", () => {
const context = createMockContext({ isCancelled: true });
expect(isActionDisabled("reroute", context)).toBe(true);
});
it("should be disabled for rejected bookings", () => {
const context = createMockContext({ isRejected: true });
expect(isActionDisabled("reroute", context)).toBe(true);
});
it("should be enabled for upcoming active bookings", () => {
const context = createMockContext({
isBookingInPast: false,
isCancelled: false,
isRejected: false,
});
expect(isActionDisabled("reroute", context)).toBe(false);
});
});
describe("reassign action", () => {
it("should be disabled for past bookings", () => {
const context = createMockContext({ isBookingInPast: true });
@@ -17,7 +17,6 @@ export interface BookingActionContext {
isRecurring: boolean;
isTabRecurring: boolean;
isTabUnconfirmed: boolean;
isBookingFromRoutingForm: boolean;
isDisabledCancelling: boolean;
isDisabledRescheduling: boolean;
isCalVideoLocation: boolean;
@@ -100,7 +99,6 @@ export function getEditEventActions(context: BookingActionContext): ActionType[]
booking,
isBookingInPast,
isDisabledRescheduling,
isBookingFromRoutingForm,
getSeatReferenceUid,
isAttendee,
t,
@@ -143,14 +141,6 @@ export function getEditEventActions(context: BookingActionContext): ActionType[]
isDisabledRescheduling,
}) || booking.seatsReferences.length > 0,
},
isBookingFromRoutingForm
? {
id: "reroute",
label: t("reroute"),
icon: "waypoints",
disabled: isActionDisabled("reroute", context),
}
: null,
{
id: "change_location",
label: t("edit_location"),
@@ -278,7 +268,6 @@ export function isActionDisabled(actionId: string, context: BookingActionContext
return !(isBookingInPast && booking.status === BookingStatus.ACCEPTED && context.isCalVideoLocation);
case "charge_card":
return context.cardCharged;
case "reroute":
case "reassign":
case "change_location":
case "add_members":
@@ -18,7 +18,6 @@ export type BookingActionsStore = {
rerouteDialogIsOpen: boolean;
isCancelDialogOpen: boolean;
isOpenWrongAssignmentDialog: boolean;
isOpenRoutingTraceSheet: boolean;
// Dialog setters
setRejectionDialogIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
@@ -34,7 +33,6 @@ export type BookingActionsStore = {
setRerouteDialogIsOpen: React.Dispatch<React.SetStateAction<boolean>>;
setIsCancelDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
setIsOpenWrongAssignmentDialog: React.Dispatch<React.SetStateAction<boolean>>;
setIsOpenRoutingTraceSheet: React.Dispatch<React.SetStateAction<boolean>>;
};
export const createBookingActionsStore = () => {
@@ -53,7 +51,6 @@ export const createBookingActionsStore = () => {
rerouteDialogIsOpen: false,
isCancelDialogOpen: false,
isOpenWrongAssignmentDialog: false,
isOpenRoutingTraceSheet: false,
// Dialog setters
setRejectionDialogIsOpen: (isOpen) =>
@@ -112,10 +109,5 @@ export const createBookingActionsStore = () => {
isOpenWrongAssignmentDialog:
typeof isOpen === "function" ? isOpen(state.isOpenWrongAssignmentDialog) : isOpen,
})),
setIsOpenRoutingTraceSheet: (isOpen) =>
set((state) => ({
isOpenRoutingTraceSheet:
typeof isOpen === "function" ? isOpen(state.isOpenRoutingTraceSheet) : isOpen,
})),
}));
};
@@ -23,17 +23,15 @@ export const ChargeCardDialog = (props: IRescheduleDialog) => {
const { isOpenDialog, setIsOpenDialog, bookingId } = props;
const [chargeError, setChargeError] = useState<string | null>(null);
const chargeCardMutation = trpc.viewer.payments.chargeCard.useMutation({
onSuccess: () => {
const chargeCardMutation = {
mutate: (_args: { bookingId: number }) => {
utils.viewer.bookings.invalidate();
setIsOpenDialog(false);
setChargeError(null);
showToast("Charge successful", "success");
},
onError: (error) => {
setChargeError(error.message || t("error_charging_card"));
},
});
isPending: false,
};
const currencyStringParams = {
amount: props.paymentAmount / 100.0,
+32 -100
View File
@@ -34,7 +34,6 @@ type ReassignDialog = {
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
teamId: number;
bookingId: number;
bookingFromRoutingForm: boolean;
isManagedEvent: boolean;
};
@@ -66,7 +65,6 @@ export const ReassignDialog = ({
setIsOpenDialog,
teamId,
bookingId,
bookingFromRoutingForm,
isManagedEvent,
}: ReassignDialog) => {
const { t } = useLocale();
@@ -78,41 +76,26 @@ export const ReassignDialog = ({
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearch = useDebounce(searchTerm, 500);
const managedEventQuery = trpc.viewer.teams.getManagedEventUsersToReassign.useInfiniteQuery(
{
bookingId,
limit: 10,
searchTerm: debouncedSearch,
},
{
enabled: isManagedEvent,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
);
const managedEventQuery: {
data: { pages: { items: { id: number; name: string | null; email: string; status: string }[] }[] } | undefined;
fetchNextPage: () => void;
hasNextPage: boolean;
isFetching: boolean;
isFetchingNextPage: boolean;
} = { data: undefined, fetchNextPage: () => {}, hasNextPage: false, isFetching: false, isFetchingNextPage: false };
const roundRobinQuery = trpc.viewer.teams.getRoundRobinHostsToReassign.useInfiniteQuery(
{
bookingId,
exclude: "fixedHosts",
limit: 10,
searchTerm: debouncedSearch,
},
{
enabled: !isManagedEvent,
getNextPageParam: (lastPage) => lastPage.nextCursor,
}
);
const roundRobinQuery: typeof managedEventQuery = { data: undefined, fetchNextPage: () => {}, hasNextPage: false, isFetching: false, isFetchingNextPage: false };
const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = isManagedEvent
? managedEventQuery
: roundRobinQuery;
const allRows = useMemo(() => {
return data?.pages.flatMap((page) => page.items) ?? [];
return data?.pages.flatMap((page: { items: { id: number; name: string | null; email: string; status: string }[] }) => page.items) ?? [];
}, [data]);
const teamMemberOptions = useMemo(() => {
return allRows.map((member) => ({
return allRows.map((member: { id: number; name: string | null; email: string; status: string }) => ({
label: member.name || member.email,
value: member.id,
status: member.status,
@@ -128,69 +111,21 @@ export const ReassignDialog = ({
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
reassignType: bookingFromRoutingForm ? ReassignType.TEAM_MEMBER : ReassignType.AUTO,
reassignType: ReassignType.AUTO,
},
});
const roundRobinReassignMutation = trpc.viewer.teams.roundRobinReassign.useMutation({
onSuccess: async (data) => {
await utils.viewer.bookings.get.invalidate();
setIsOpenDialog(false);
showToast(t("booking_reassigned_to_host", { host: data?.reassignedTo.name }), "success");
},
onError: async (error) => {
if (error.message.includes(ErrorCode.NoAvailableUsersFound)) {
showToast(t("no_available_hosts"), "error");
} else {
showToast(t(error.message), "error");
}
},
});
const roundRobinReassignMutation = { mutate: (..._args: unknown[]) => {}, mutateAsync: async () => ({}), isPending: false };
const managedEventReassignMutation = trpc.viewer.teams.managedEventReassign.useMutation({
onSuccess: async () => {
await utils.viewer.bookings.get.invalidate();
setIsOpenDialog(false);
showToast(t("booking_reassigned"), "success");
},
onError: async (error) => {
if (error.message.includes(ErrorCode.NoAvailableUsersFound)) {
showToast(t("no_available_hosts"), "error");
} else {
showToast(t(error.message), "error");
}
},
});
const roundRobinManualReassignMutation = trpc.viewer.teams.roundRobinManualReassign.useMutation({
onSuccess: async () => {
await utils.viewer.bookings.get.invalidate();
setIsOpenDialog(false);
showToast(t("booking_reassigned"), "success");
},
onError: async (error) => {
if (error.message.includes(ErrorCode.NoAvailableUsersFound)) {
showToast(t("no_available_hosts"), "error");
} else {
showToast(t(error.message), "error");
}
},
});
const managedEventReassignMutation = { mutate: (..._args: unknown[]) => {}, mutateAsync: async () => ({}), isPending: false };
const roundRobinManualReassignMutation = { mutate: (..._args: unknown[]) => {}, mutateAsync: async () => ({}), isPending: false };
const managedEventManualReassignMutation = { mutate: (..._args: unknown[]) => {}, mutateAsync: async () => ({}), isPending: false };
const managedEventManualReassignMutation = trpc.viewer.teams.managedEventManualReassign.useMutation({
onSuccess: async () => {
await utils.viewer.bookings.get.invalidate();
setIsOpenDialog(false);
showToast(t("booking_reassigned"), "success");
},
onError: async (error) => {
if (error.message.includes(ErrorCode.NoAvailableUsersFound)) {
showToast(t("no_available_hosts"), "error");
} else {
showToast(t(error.message), "error");
}
},
});
const [confirmationModal, setConfirmationModal] = useState<{
show: boolean;
@@ -240,23 +175,20 @@ export const ReassignDialog = ({
const reassignType: ReassignType = z.nativeEnum(ReassignType).parse(val);
form.setValue("reassignType", reassignType);
}}
defaultValue={bookingFromRoutingForm ? ReassignType.TEAM_MEMBER : ReassignType.AUTO}
defaultValue={ReassignType.AUTO}
className="mt-1 flex flex-col gap-4">
{!bookingFromRoutingForm ? (
<RadioArea.Item
value={ReassignType.AUTO}
className="w-full text-sm"
classNames={{ container: "w-full" }}
disabled={bookingFromRoutingForm}
data-testid="reassign-option-auto">
<strong className="mb-1 block">
{isManagedEvent ? t("auto_reassign") : t("round_robin")}
</strong>
<p>
{isManagedEvent ? t("auto_reassign_description") : t("round_robin_reassign_description")}
</p>
</RadioArea.Item>
) : null}
<RadioArea.Item
value={ReassignType.AUTO}
className="w-full text-sm"
classNames={{ container: "w-full" }}
data-testid="reassign-option-auto">
<strong className="mb-1 block">
{isManagedEvent ? t("auto_reassign") : t("round_robin")}
</strong>
<p>
{isManagedEvent ? t("auto_reassign_description") : t("round_robin_reassign_description")}
</p>
</RadioArea.Item>
<RadioArea.Item
value={ReassignType.TEAM_MEMBER}
className="text-sm"
@@ -1,916 +0,0 @@
import { useMutation } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useEffect, useCallback } from "react";
import type { z } from "zod";
import FormInputFields, {
FormInputFieldsSkeleton,
} from "@calcom/app-store/routing-forms/components/FormInputFields";
import { getAbsoluteEventTypeRedirectUrl } from "@calcom/app-store/routing-forms/getEventTypeRedirectUrl";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { substituteVariables } from "@calcom/app-store/routing-forms/lib/substituteVariables";
import type { FormResponse, LocalRoute } from "@calcom/app-store/routing-forms/types/types";
import { RouteActionType } from "@calcom/app-store/routing-forms/zod";
import dayjs from "@calcom/dayjs";
import { useBookerUrl } from "@calcom/features/bookings/hooks/useBookerUrl";
import { createBooking } from "@calcom/features/bookings/lib/create-booking";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { getUrlSearchParamsToForwardForReroute } from "@calcom/features/routing-forms/lib/getUrlSearchParamsToForward";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { EventType, User, Team, Attendee, Booking as PrismaBooking } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
import type { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import type { Ensure } from "@calcom/types/utils";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
const enum ReroutingStatusEnum {
REROUTING_NOT_INITIATED = "not_initiated",
REROUTING_IN_PROGRESS = "in_progress",
REROUTING_COMPLETE = "complete",
REROUTING_FAILED = "failed",
}
type ResponseWithForm = RouterOutputs["viewer"]["appRoutingForms"]["getResponseWithFormFields"];
type BookingToReroute = Pick<PrismaBooking, "metadata" | "responses" | "id" | "uid" | "title" | "status"> & {
routedFromRoutingFormReponse: {
id: number;
};
startTime: string;
metadata: z.infer<typeof bookingMetadataSchema>;
attendees: Pick<Attendee, "locale" | "timeZone" | "email" | "name">[];
eventType: Pick<EventType, "length" | "schedulingType" | "title" | "id" | "slug"> & {
team: Pick<Team, "slug"> | null;
};
user: Pick<User, "id" | "name" | "email"> | null;
};
type TeamEventTypeBookingToReroute = Omit<BookingToReroute, "eventType"> & {
user: NonNullable<BookingToReroute["user"]>;
eventType: Omit<BookingToReroute["eventType"], "team"> & {
team: Ensure<Pick<Team, "slug">, "slug">;
};
};
type RerouteDialogProps = {
isOpenDialog: boolean;
setIsOpenDialog: (isOpen: boolean) => void;
booking: BookingToReroute;
};
type ReroutingState =
| {
type: "reschedule_to_same_event_new_tab" | "reschedule_to_different_event_new_tab";
/**
* UID of the rescheduled booking
*/
newBooking: string | null;
/**
* window for the new tab that is opened for rerouting
*/
reschedulerWindow: Window;
error?: Error;
}
| {
type: "same_timeslot";
newBooking: string | null;
reschedulerWindow: null;
error?: Error;
};
type TeamMemberMatchingAttributeLogic = {
id: number;
name: string | null;
email: string;
};
// We can't let user change email identifier field as that would require contact owner information from salesforce which we don't support yet.
// Also, this isn't a requirement as well to allow correcting the email
const fieldsThatCannotBeCorrected = ["email"];
function getEventTypeUrlsForTheChosenRoute({
chosenRoute,
form,
reroutingFormResponses,
currentResponse,
teamMemberIdsMatchingAttributeLogic,
booking,
searchParams,
}: {
form: ResponseWithForm["form"];
currentResponse: FormResponse;
reroutingFormResponses: Record<string, Pick<FormResponse[keyof FormResponse], "value">>;
teamMemberIdsMatchingAttributeLogic: number[] | null;
chosenRoute: LocalRoute | null;
booking: TeamEventTypeBookingToReroute;
searchParams: URLSearchParams;
}) {
if (!chosenRoute) {
return null;
}
const formFields = form.fields || [];
const routedFromRoutingFormReponseId = booking.routedFromRoutingFormReponse.id;
const allURLSearchParams = getUrlSearchParamsToForwardForReroute({
formResponse: currentResponse,
formResponseId: routedFromRoutingFormReponseId,
fields: formFields,
searchParams,
teamMembersMatchingAttributeLogic: teamMemberIdsMatchingAttributeLogic,
attributeRoutingConfig: chosenRoute.attributeRoutingConfig ?? null,
rescheduleUid: booking.uid,
reroutingFormResponses,
});
const eventFullSlug = substituteVariables(chosenRoute.action.value, currentResponse, formFields);
const eventBookingAbsoluteUrl = getAbsoluteEventTypeRedirectUrl({
form,
eventTypeRedirectUrl: eventFullSlug,
allURLSearchParams,
isEmbed: false,
});
return { eventFullSlug, eventBookingAbsoluteUrl };
}
function rescheduleInNewTab({ url }: { url: string }) {
const reschedulerWindow = window.open(url, "_blank");
if (!reschedulerWindow) {
throw new Error("Failed to open new tab");
}
return reschedulerWindow;
}
const getFullSlugForEvent = (
eventType: Pick<TeamEventTypeBookingToReroute["eventType"], "team" | "slug">
) => {
return `team/${eventType.team.slug}/${eventType.slug}`;
};
function isBookingTimeslotInPast(booking: BookingToReroute) {
return dayjs(booking.startTime).isBefore(dayjs());
}
const useReroutingState = ({ isOpenDialog }: Pick<RerouteDialogProps, "isOpenDialog">) => {
const [value, setValue] = useState<ReroutingState | null>(null);
const state = value;
// If dialog is closed but the rerouting window is still open, close it
if (!isOpenDialog && state?.reschedulerWindow) {
state.reschedulerWindow.close();
setValue(null);
}
useEffect(() => {
const checkInterval = setInterval(() => {
if (state?.reschedulerWindow?.closed) {
// Ensure that render happens again
setValue(null);
clearInterval(checkInterval);
}
}, 1);
return () => clearInterval(checkInterval);
}, [value, setValue]);
const status = (() => {
if (!value) return ReroutingStatusEnum.REROUTING_NOT_INITIATED;
if (value.error) return ReroutingStatusEnum.REROUTING_FAILED;
if (value.newBooking) return ReroutingStatusEnum.REROUTING_COMPLETE;
return ReroutingStatusEnum.REROUTING_IN_PROGRESS;
})();
return { value: state, setValue, status };
};
// const useUpdateIsReroutingQueryParam = ({ isOpenDialog }: { isOpenDialog: boolean }) => {
// const { setQuery: setIsReroutingQuery } = useRouterQuery("isRerouting");
// useEffect(() => {
// if (isOpenDialog) {
// setIsReroutingQuery("true");
// } else {
// setIsReroutingQuery(undefined);
// }
// }, [isOpenDialog]);
// };
const gotoBookingPage = ({
booking,
router,
}: {
booking: Pick<PrismaBooking, "uid">;
router: ReturnType<typeof useRouter>;
}) => {
// TODO: Do we need to send other params as well?
router.push(`/booking/${booking.uid}?cal.rerouting=true`);
};
const useEventListeners = ({ reroutingState }: { reroutingState: ReturnType<typeof useReroutingState> }) => {
const router = useRouter();
const { t } = useLocale();
const messageListener = useCallback(
(event: MessageEvent) => {
if (event.data.type !== "CAL:rescheduleBookingSuccessfulV2") {
return;
}
const calEventData = event.data.data;
showToast(t("rerouted_booking_successfully_redirecting_to_booking_page"), "success");
if (!calEventData.uid) {
console.error("Booking UID is not there");
throw new Error(t("something_went_wrong"));
}
const newBookingId = calEventData.uid;
reroutingState.setValue((prev) => {
if (!prev) return null;
return { ...prev, newBooking: newBookingId };
});
gotoBookingPage({ router, booking: { uid: newBookingId } });
reroutingState.value?.reschedulerWindow?.close();
},
[reroutingState, reroutingState.value?.reschedulerWindow]
);
// Make sure to close the rescheduler window when this tab closes/reloads
const beforeUnloadListener = useCallback(() => {
reroutingState.value?.reschedulerWindow?.close();
reroutingState.setValue(null);
}, [reroutingState.value?.reschedulerWindow]);
// Ensure listeners are added once the component is mounted and removed once the component is unmounted
useEffect(() => {
window.addEventListener("message", messageListener);
window.addEventListener("beforeunload", beforeUnloadListener);
return () => {
window.removeEventListener("message", messageListener);
window.removeEventListener("beforeunload", beforeUnloadListener);
};
// messageListener and beforeUnloadListener are memoized using useCallback, so the reference remains stable
}, [messageListener, beforeUnloadListener]);
};
const NewRoutingManager = ({
chosenRoute,
booking,
form,
currentResponse,
teamMembersMatchingAttributeLogic,
reroutingState,
}: {
chosenRoute: LocalRoute;
booking: TeamEventTypeBookingToReroute;
form: ResponseWithForm["form"];
currentResponse: FormResponse;
teamMembersMatchingAttributeLogic: {
isPending: boolean;
data: TeamMemberMatchingAttributeLogic[] | null;
};
reroutingState: ReturnType<typeof useReroutingState>;
}) => {
const { t } = useLocale();
const router = useRouter();
const bookerUrl = useBookerUrl();
const session = useSession();
const teamMemberIdsMatchingAttributeLogic =
teamMembersMatchingAttributeLogic?.data
?.map((member) => member.id)
.filter((id) => {
// We don't want to reroute to the same user who booked the booking
return id !== booking.user?.id;
}) || null;
const routedFromRoutingFormReponseId = booking.routedFromRoutingFormReponse.id;
const bookingEventType = booking.eventType;
// Provide a reason for rescheduling that can be customized by user in the future
// const rescheduleReason = "Rerouted";
const isRoundRobinScheduling = bookingEventType.schedulingType === SchedulingType.ROUND_ROBIN;
const reroutingFormResponses = Object.fromEntries(
Object.entries(currentResponse).map(([key, response]) => [key, { value: response.value }])
);
const chosenEventUrls = getEventTypeUrlsForTheChosenRoute({
chosenRoute,
form,
reroutingFormResponses,
teamMemberIdsMatchingAttributeLogic,
booking,
currentResponse,
searchParams: new URLSearchParams({
rescheduledBy: session?.data?.user?.email ?? "",
}),
});
const chosenEventTypeId = chosenRoute.action.eventTypeId;
const enableChosenEventTypeQuery = !!chosenEventTypeId;
// TODO: Get bare minimum eventType details
const { data: chosenEventTypeData, isPending: isChosenEventTypePending } =
trpc.viewer.eventTypes.get.useQuery(
// enabled prop ensures that the query is not run if the chosenEventTypeId is not there
{ id: chosenEventTypeId! },
{
enabled: enableChosenEventTypeQuery,
}
);
// isPending of the query is true even if enabled=false and no request was sent. So, identify if the request is actually in progress
const isChosenEventTypeRequestInProgress = enableChosenEventTypeQuery ? isChosenEventTypePending : false;
const chosenEventType = chosenEventTypeData?.eventType;
const currentBookingEventFullSlug = getFullSlugForEvent(booking.eventType);
const isReroutingToDifferentEvent = currentBookingEventFullSlug !== chosenEventUrls?.eventFullSlug;
const createBookingMutation = useMutation({
mutationFn: createBooking,
onSuccess: (booking) => {
showToast(t("rerouted_booking_successfully_redirecting_to_booking_page"), "success");
if (!booking.uid) {
console.error("Booking UID is not there");
throw new Error(t("something_went_wrong"));
}
const newBookingId = booking.uid;
reroutingState.setValue((prev) => {
if (!prev) return null;
return {
...prev,
newBooking: newBookingId,
};
});
gotoBookingPage({ router, booking: { uid: newBookingId } });
},
onError: (err, _, ctx) => {
reroutingState.setValue({
error: err,
newBooking: null,
type: "same_timeslot",
reschedulerWindow: null,
});
showToast(
"Looks like the timeslot is not available for the new team members. Try rescheduling with different timeslot",
"error"
);
},
});
useEventListeners({ reroutingState });
if (!chosenRoute) return null;
const isReroutingInNewTab =
reroutingState.value?.type === "reschedule_to_same_event_new_tab" ||
reroutingState.value?.type === "reschedule_to_different_event_new_tab";
return (
<div className="bg-cal-muted flex flex-col stack-y-3 rounded-md p-4 text-sm">
<h2 className="text-emphasis font-medium">{t("new_routing_status")}</h2>
<div className="flex flex-col stack-y-2">
{reroutingState.status === ReroutingStatusEnum.REROUTING_NOT_INITIATED && reroutingPreview()}
{(reroutingState.status === ReroutingStatusEnum.REROUTING_NOT_INITIATED || !isReroutingInNewTab) &&
reroutingCTAs()}
{isReroutingInNewTab && newTabReroutingStatus()}
</div>
</div>
);
function rescheduleToSameTimeslotOfEvent({
eventType: { id: eventTypeId, slug: eventTypeSlug, team: eventTypeTeam, length: eventTypeLength },
}: {
eventType: Pick<TeamEventTypeBookingToReroute["eventType"], "id" | "slug" | "length"> & {
team: {
slug: string | null;
} | null;
};
}) {
if (!chosenRoute) {
console.error("Chosen route must be there for rerouting");
throw new Error(t("something_went_wrong"));
}
if (!eventTypeTeam?.slug) {
console.error("Event type team slug must be there for rerouting");
throw new Error(t("something_went_wrong"));
}
const teamSlug = eventTypeTeam.slug;
if (isBookingTimeslotInPast(booking)) {
showToast("You cannot reschedule to a past timeslot", "error");
return;
}
const booker = booking.attendees[0];
const getFieldsThatRemainSame = () => {
return {
responses: booking.responses,
timeZone: booker.timeZone,
language: booker.locale || "en",
metadata: booking.metadata || {},
...getBookingSeatFields(),
...getHashedLinkFields(),
};
function getBookingSeatFields() {
// During rerouting, do all the seats need to be re-routed?
// Let's not support re-routing for booking with seats for now.
return {
// bookingUid: booking.uid,
// seatReferenceUid: booking.eventType,
};
}
function getHashedLinkFields() {
// After booking hashedLink is deleted, so I don't believe we need to return anything here.
// Also, Rerouting is for a booking that was routed and routing doesn't involve hashed link even if it is enabled for the event.
return {};
}
};
const getFieldFromEventTypeThatRemainSame = () => {
return {
user: teamSlug,
eventTypeId: eventTypeId,
eventTypeSlug: eventTypeSlug,
};
};
const getTimeslotFields = () => {
return {
// It is possible that EvenType changed its duration, so we would consider that as well.
start: dayjs(booking.startTime).format(),
end: dayjs(booking.startTime)
// Defaults to the default event length in case no custom duration is set.
.add(eventTypeLength, "minute")
.format(),
};
};
const getRoutingFormRelatedFields = () => {
return {
routedTeamMemberIds: teamMemberIdsMatchingAttributeLogic,
routingFormResponseId: routedFromRoutingFormReponseId,
skipContactOwner: chosenRoute.attributeRoutingConfig?.skipContactOwner,
};
};
const getSalesforceContactOwnerFields = () => {
// Email field won't need to be corrected, so we don't need to support it.
return {};
};
// TODO: Long term, we should refactor handleNewBooking and use a different route specific for this purpose,
createBookingMutation.mutate({
rescheduleUid: booking.uid,
rescheduledBy: session?.data?.user?.email ?? undefined,
// rescheduleReason,
reroutingFormResponses: reroutingFormResponses,
...getTimeslotFields(),
...getFieldsThatRemainSame(),
...getFieldFromEventTypeThatRemainSame(),
...getRoutingFormRelatedFields(),
...getSalesforceContactOwnerFields(),
});
reroutingState.setValue({
newBooking: null,
type: "same_timeslot",
reschedulerWindow: null,
});
}
function rescheduleToSameTimeslotOfSameEvent() {
return rescheduleToSameTimeslotOfEvent({
eventType: booking.eventType,
});
}
function rescheduleToSameTimeslotOfChosenEvent() {
if (!chosenEventTypeId && isReroutingToDifferentEvent) {
showToast(
"We don't have ID for the new event. Please go to the Routing Form and save it again.",
"error"
);
return;
}
if (!chosenEventType) {
// There are disabled/loading state on button to ensure that this function is not called if chosenEventType is not there
console.error("Chosen event type must be there for rerouting");
throw new Error(t("something_went_wrong"));
}
return rescheduleToSameTimeslotOfEvent({
eventType: chosenEventType,
});
}
function rescheduleSameEventInNewTab() {
if (!chosenEventUrls?.eventBookingAbsoluteUrl) {
console.error("URL must be there for opening new tab");
throw new Error(t("something_went_wrong"));
}
const reschedulerWindow = rescheduleInNewTab({
url: chosenEventUrls.eventBookingAbsoluteUrl,
});
reroutingState.setValue({
type: "reschedule_to_same_event_new_tab",
reschedulerWindow,
newBooking: null,
});
}
function rescheduleDifferentEventInNewTab() {
if (!chosenEventUrls?.eventBookingAbsoluteUrl) {
console.error("URL must be there for opening new tab");
throw new Error(t("something_went_wrong"));
}
const reschedulerWindow = rescheduleInNewTab({
url: chosenEventUrls.eventBookingAbsoluteUrl,
});
reroutingState.setValue({
type: "reschedule_to_different_event_new_tab",
reschedulerWindow,
newBooking: null,
});
}
function reroutingPreview() {
if (chosenRoute.action.type === RouteActionType.CustomPageMessage) {
return <span className="text-attention">{t("reroute_preview_custom_message")}</span>;
}
if (chosenRoute.action.type === RouteActionType.ExternalRedirectUrl) {
return (
<span className="text-attention">
{t("reroute_preview_external_redirect", { externalUrl: chosenRoute.action.value })}
</span>
);
}
if (chosenRoute.action.type === RouteActionType.EventTypeRedirectUrl) {
// Computed value for eventTypeSlugToRedirect
const eventTypeSlugToRedirect =
chosenRoute.action.type === RouteActionType.EventTypeRedirectUrl ? chosenRoute.action.value : null;
if (!eventTypeSlugToRedirect) {
console.error("Event type slug to redirect must be there if action is EventTypeRedirectUrl");
throw new Error(t("something_went_wrong"));
}
return (
<div className="flex flex-col stack-y-2">
<span className="text-default" data-testid="reroute-preview-event-type">
<span className="font-semibold">{t("event_type")}:</span>{" "}
<a
className="underline"
target="_blank"
href={`${bookerUrl}/${eventTypeSlugToRedirect}`}
rel="noreferrer"
data-testid="test-routing-result">
{eventTypeSlugToRedirect}
</a>
</span>
<span className="text-default" data-testid="reroute-preview-hosts">
<Tooltip content="Includes fixed hosts always and assumes that all the team members mentioned here are assigned to the event">
<span className="font-semibold">
{isRoundRobinScheduling ? t("reroute_preview_possible_host") : t("hosts")}:
</span>
</Tooltip>{" "}
{bookingHosts()}
</span>
</div>
);
}
function bookingHosts() {
if (teamMembersMatchingAttributeLogic.isPending) return t("loading");
const hostEmails = teamMembersMatchingAttributeLogic.data?.map((member) => member.email).join(", ");
return hostEmails || t("no_matching_members");
}
return null;
}
function reroutingCTAs() {
if (chosenRoute.action.type !== RouteActionType.EventTypeRedirectUrl) {
// There are no actions to perform if the new chosen route isn't an event type redirect
return null;
}
const shouldDisableCTAs = teamMembersMatchingAttributeLogic.isPending || createBookingMutation.isPending;
return (
<div className="flex flex-col gap-2">
{!isReroutingToDifferentEvent ? (
<Button onClick={rescheduleSameEventInNewTab} disabled={shouldDisableCTAs}>
{t("reschedule_with_different_timeslot")}
</Button>
) : (
<Button onClick={rescheduleDifferentEventInNewTab} disabled={shouldDisableCTAs}>
{t("reschedule_to_the_new_event_with_different_timeslot")}
</Button>
)}
{!isReroutingToDifferentEvent ? (
<Button
disabled={shouldDisableCTAs}
loading={createBookingMutation.isPending}
onClick={rescheduleToSameTimeslotOfSameEvent}>
{t("reschedule_with_same_timeslot")}
</Button>
) : (
<Button
disabled={shouldDisableCTAs}
loading={createBookingMutation.isPending || isChosenEventTypeRequestInProgress}
onClick={rescheduleToSameTimeslotOfChosenEvent}>
{t("reschedule_with_same_timeslot_of_new_event")}
</Button>
)}
</div>
);
}
function newTabReroutingStatus() {
if (reroutingState.status !== ReroutingStatusEnum.REROUTING_IN_PROGRESS) {
return null;
}
return (
<div>
<span className="text-attention">
<span>Continue with rerouting in the new</span>{" "}
<a
href="javascript:void(0)"
className="text-attention underline"
onClick={() => reroutingState.value?.reschedulerWindow?.focus()}>
tab
</a>
</span>
</div>
);
}
};
const CurrentRoutingStatus = ({
booking,
}: {
booking: Pick<TeamEventTypeBookingToReroute, "eventType" | "user" | "attendees">;
}) => {
const fullSlug = getFullSlugForEvent(booking.eventType);
const { t } = useLocale();
const bookerUrl = useBookerUrl();
if (!fullSlug) return null;
return (
<div className="bg-cal-muted flex flex-col stack-y-3 rounded-md p-4 text-sm">
<h2 className="text-emphasis font-medium">{t("current_routing_status")}</h2>
<div className="flex flex-col stack-y-2">
<span className="text-default" data-testid="current-routing-status-event-type">
<span className="font-semibold">{t("event_type")}:</span>{" "}
<a
className="underline"
target="_blank"
href={`${bookerUrl}/${fullSlug}`}
rel="noreferrer"
data-testid="test-routing-result">
{fullSlug}
</a>
</span>
<span className="text-default" data-testid="current-routing-status-organizer">
<span className="font-semibold">{t("organizer")}:</span> <span>{booking.user.email}</span>
</span>
<span className="text-default" data-testid="current-routing-status-attendees">
<span className="font-semibold">{t("attendees")}:</span>{" "}
<span>{booking.attendees.map((attendee) => attendee.email).join(", ")}</span>
</span>
</div>
</div>
);
};
const RerouteDialogContentAndFooter = ({
booking,
isOpenDialog,
setIsOpenDialog,
}: Pick<RerouteDialogProps, "isOpenDialog" | "setIsOpenDialog"> & {
booking: TeamEventTypeBookingToReroute;
}) => {
const {
data: responseWithForm,
isPending: isRoutingFormLoading,
error: formResponseFetchError,
} = trpc.viewer.appRoutingForms.getResponseWithFormFields.useQuery({
formResponseId: booking.routedFromRoutingFormReponse.id,
});
const { t } = useLocale();
if (isRoutingFormLoading)
return (
<>
<FormInputFieldsSkeleton />
<DialogFooter>
<Button color="secondary" onClick={() => setIsOpenDialog(false)}>
{t("cancel")}
</Button>
<Button disabled data-testid="verify-new-route-button">
{t("verify_new_route")}
</Button>
</DialogFooter>
</>
);
if (formResponseFetchError) {
return <div className="mb-8">{formResponseFetchError.message}</div>;
}
if (!responseWithForm) return <div className="mb-8">{t("something_went_wrong")}</div>;
return (
<RerouteDialogContentAndFooterWithFormResponse
isOpenDialog={isOpenDialog}
setIsOpenDialog={setIsOpenDialog}
responseWithForm={responseWithForm}
booking={booking}
/>
);
};
const RerouteDialogContentAndFooterWithFormResponse = ({
responseWithForm,
booking,
isOpenDialog,
setIsOpenDialog,
}: Pick<RerouteDialogProps, "isOpenDialog" | "setIsOpenDialog"> & {
responseWithForm: ResponseWithForm;
booking: TeamEventTypeBookingToReroute;
}) => {
const form = responseWithForm.form;
const { t } = useLocale();
const router = useRouter();
const [responseFromOrganizer, setResponseFromOrganizer] = useState<FormResponse>({});
const isResponseFromOrganizerUnpopulated = Object.keys(responseFromOrganizer).length === 0;
const currentResponse = isResponseFromOrganizerUnpopulated
? responseWithForm.response
: responseFromOrganizer;
const [chosenRoute, setChosenRoute] = useState<LocalRoute | null>(null);
const reroutingState = useReroutingState({
isOpenDialog,
});
const [teamMembersMatchingAttributeLogic, setTeamMembersMatchingAttributeLogic] = useState<
| {
id: number;
name: string | null;
email: string;
}[]
| null
>([]);
const findTeamMembersMatchingAttributeLogicMutation =
trpc.viewer.routingForms.findTeamMembersMatchingAttributeLogicOfRoute.useMutation({
onSuccess(data) {
setTeamMembersMatchingAttributeLogic(data.result ? data.result.users : data.result);
},
});
function verifyRoute() {
// Reset all states
reroutingState.setValue(null);
setTeamMembersMatchingAttributeLogic(null);
const route = findMatchingRoute({
form,
response: currentResponse,
});
setChosenRoute(route || null);
if (!route) return;
findTeamMembersMatchingAttributeLogicMutation.mutate({
formId: form.id,
response: currentResponse,
route,
});
}
return (
<div>
<div>
<Link
className="text-emphasis text-semibold font-cal mb-4 flex underline"
href={`/apps/routing-forms/form-edit/${form.id}`}
target="_blank">
{form.name}
</Link>
<FormInputFields
response={currentResponse}
disabledFields={fieldsThatCannotBeCorrected}
form={form}
setResponse={setResponseFromOrganizer}
/>
<div className="flex flex-col gap-2">
<CurrentRoutingStatus booking={booking} />
{chosenRoute && (
<NewRoutingManager
chosenRoute={chosenRoute}
booking={booking}
teamMembersMatchingAttributeLogic={{
isPending: findTeamMembersMatchingAttributeLogicMutation.isPending,
data: teamMembersMatchingAttributeLogic,
}}
reroutingState={reroutingState}
form={form}
currentResponse={currentResponse}
/>
)}
</div>
</div>
{renderFooter()}
</div>
);
function renderFooter() {
if (reroutingState.status !== ReroutingStatusEnum.REROUTING_COMPLETE) {
return (
<DialogFooter>
<Button color="secondary" onClick={() => setIsOpenDialog(false)}>
{t("cancel")}
</Button>
<Button
onClick={verifyRoute}
data-testid="verify-new-route-button"
disabled={reroutingState.status === ReroutingStatusEnum.REROUTING_IN_PROGRESS}>
{t("verify_new_route")}
</Button>
</DialogFooter>
);
}
if (reroutingState.status === ReroutingStatusEnum.REROUTING_COMPLETE) {
return (
<DialogFooter>
<Button
onClick={() => {
setIsOpenDialog(false);
}}>
{t("close")}
</Button>
</DialogFooter>
);
}
return null;
}
};
export const RerouteDialog = ({ isOpenDialog, setIsOpenDialog, booking }: RerouteDialogProps) => {
const { t } = useLocale();
const bookingEventType = booking.eventType;
if (!bookingEventType.team) {
console.error("Only team event can be re-routed");
throw new Error(t("something_went_wrong"));
}
if (!bookingEventType.team.slug) {
console.error("Team slug must be there for rerouting");
throw new Error(t("something_went_wrong"));
}
if (!booking.user) {
// Not a hard requirement, but better to be strict with data.
console.error("Booking must have a user");
throw new Error(t("something_went_wrong"));
}
const teamEventTypeBooking = {
...booking,
user: booking.user,
eventType: {
...bookingEventType,
team: {
...bookingEventType.team,
slug: bookingEventType.team.slug,
},
},
};
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
<DialogContent preventCloseOnOutsideClick enableOverflow>
<DialogHeader title={t("reroute_booking")} subtitle={t("reroute_booking_description")} />
<RerouteDialogContentAndFooter
booking={teamEventTypeBooking}
isOpenDialog={isOpenDialog}
setIsOpenDialog={setIsOpenDialog}
/>
</DialogContent>
</Dialog>
);
};
@@ -10,12 +10,11 @@ import { DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components
import { Label, Select, TextArea } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import assignmentReasonBadgeTitleMap from "@lib/booking/assignmentReasonBadgeTitleMap";
import type { Dispatch, SetStateAction } from "react";
import type { Control, ControllerRenderProps } from "react-hook-form";
import { Controller, useForm } from "react-hook-form";
import assignmentReasonBadgeTitleMap from "@lib/booking/assignmentReasonBadgeTitleMap";
interface BookingData {
uid: string;
eventType?: {
@@ -265,13 +264,10 @@ export function WrongAssignmentDialog(props: IWrongAssignmentDialog): JSX.Elemen
const alreadyReported = existingReport?.hasReport ?? false;
const teamIdForQuery = teamId ?? 0;
const { data: teamMembersData } = trpc.viewer.teams.listMembers.useQuery(
{ teamId: teamIdForQuery, limit: 100 },
{ enabled: !!teamId && isOpenDialog }
);
const teamMembersData = undefined as { members: Array<{ name: string | null; email: string }> } | undefined;
const teamMemberOptions: TeamMemberOption[] =
teamMembersData?.members.map((member) => ({
teamMembersData?.members.map((member: { name: string | null; email: string }) => ({
label: member.name || member.email,
value: member.email,
email: member.email,
@@ -1,556 +0,0 @@
import { TooltipProvider } from "@radix-ui/react-tooltip";
import { act, fireEvent, render, screen } from "@testing-library/react";
import type { Session } from "next-auth";
import { SessionProvider } from "next-auth/react";
import { vi } from "vitest";
import { RouteActionType } from "@calcom/app-store/routing-forms/zod";
import { BookingStatus, SchedulingType } from "@calcom/prisma/enums";
import { RerouteDialog } from "../RerouteDialog";
const mockRouter = {
push: vi.fn((path: string) => {
return;
}),
};
vi.mock("next/navigation", async (importOriginal) => {
const actual = await importOriginal<typeof import("next/navigation")>();
return {
...actual,
useRouter: vi.fn(() => mockRouter),
};
});
vi.mock("@calcom/app-store/routing-forms/lib/processRoute", () => ({
findMatchingRoute: vi.fn(({ form, response }) => {
return form.routes.find((route: any) => route.__testMatching);
}),
}));
const fakeNewTabWindow = {
close: vi.fn(),
};
const mockOpen = vi.fn((_url: string) => {
return fakeNewTabWindow;
});
vi.stubGlobal("open", mockOpen);
const mockSession = {
expires: new Date(Date.now() + 2 * 86400).toISOString(),
user: {
id: 1,
name: "Test User",
email: "[email protected]",
},
} as Session;
vi.mock("@calcom/app-store/routing-forms/components/FormInputFields", () => ({
default: vi.fn(({ response, form, setResponse, disabledFields }) => {
return (
<div data-testid="mock-form-input-fields">
{form.fields?.map((field: any) => (
<div key={field.id}>
<label data-testid={`mock-form-field-${field.id}-label`}>{field.label}</label>
<div data-testid={`mock-form-field-${field.id}-value`}>{response[field.id]?.value}</div>
</div>
))}
<div data-testid="mock-form-field-disabled-fields-identifiers">{disabledFields.join(", ")}</div>
<button
data-testid="mock-form-update-response-button"
onClick={() =>
setResponse({
"company-size": {
label: "Company Size",
value: "small",
},
country: {
label: "Country",
value: "usa",
},
})
}>
Test Update Response
</button>
</div>
);
}),
FormInputFieldsSkeleton: vi.fn(() => <div data-testid="mock-form-input-fields-skeleton" />),
}));
vi.mock("@calcom/lib/hooks/useLocale", () => ({
useLocale: vi.fn(() => ({ t: (key: string) => key })),
}));
vi.mock("@calcom/features/ee/organizations/context/provider", () => ({
useOrgBranding: vi.fn(() => null),
}));
vi.mock("@calcom/web/lib/hooks/useRouterQuery", () => ({
default: vi.fn(() => {
return {
setQuery: vi.fn(),
};
}),
}));
vi.mock("@calcom/ui/components/tooltip", () => ({
Tooltip: vi.fn(({ children }) => <div data-testid="mock-tooltip">{children}</div>),
}));
vi.mock("@calcom/trpc/react", () => ({
trpc: {
viewer: {
appRoutingForms: {
getResponseWithFormFields: {
useQuery: vi.fn(() => ({
data: {
form: {
id: "form-id",
name: "Test Form",
fields: [
{
id: "company-size",
label: "Company Size",
type: "select",
options: [
{ label: "Small", value: "small" },
{ label: "Medium", value: "medium" },
{ label: "Large", value: "large" },
],
},
{
id: "country",
label: "Country",
type: "select",
options: [
{ label: "USA", value: "usa" },
{ label: "Canada", value: "canada" },
{ label: "UK", value: "uk" },
],
},
{
id: "email",
label: "Email",
type: "email",
required: true,
},
],
routes: [
{
id: "mock-route-id",
action: {
eventTypeId: 123,
type: RouteActionType.EventTypeRedirectUrl,
value: "team/test-team/new-test-event",
},
__testMatching: true,
},
{
id: "fallback-route",
isFallback: true,
action: {
type: RouteActionType.CustomPageMessage,
value: "456",
},
__testMatching: false,
},
],
},
response: {
"company-size": {
label: "Company Size",
value: "small",
},
country: {
label: "Country",
value: "usa",
},
},
},
isPending: false,
})),
},
},
eventTypes: {
get: {
useQuery: vi.fn(() => ({
data: {
eventType: {
id: "123",
title: "Mocked Event Type",
slug: "mocked-event-type",
length: 30,
schedulingType: "ROUND_ROBIN",
team: { slug: "mocked-team" },
},
},
isPending: false,
})),
},
},
routingForms: {
findTeamMembersMatchingAttributeLogicOfRoute: {
useMutation: vi.fn(({ onSuccess }) => {
return {
mutate: vi.fn(() => {
onSuccess({
result: {
users: [
{
id: 1,
name: "Matching User 1",
email: "[email protected]",
},
{
id: 2,
name: "Matching User 2",
email: "[email protected]",
},
],
},
});
}),
};
}),
},
},
},
},
}));
const mockReactQueryMutateFn = vi.fn(({ __testOnSuccess }) => {
__testOnSuccess({
uid: "RESCHEDULED_BOOKING_UID_SAME_TIMESLOT",
});
});
vi.mock("@tanstack/react-query", () => ({
useMutation: vi.fn(({ onSuccess }) => {
return {
mutate: vi.fn((payload) => {
mockReactQueryMutateFn({
...payload,
__testOnSuccess: onSuccess,
});
}),
isLoading: false,
isError: false,
error: null,
onSuccess: onSuccess,
};
}),
}));
async function mockMessageFromOpenedTab({ type, data }: { type: string; data: any }) {
const messageReceivedPromise = new Promise<boolean>((resolve) => {
window.addEventListener("message", () => {
resolve(true);
});
});
window.postMessage(
{
type,
data,
},
"*"
);
return messageReceivedPromise;
}
async function expectEventTypeInfoInCurrentRouting({
eventTypeText,
eventTypeHref,
}: {
eventTypeText: string;
eventTypeHref: string;
}) {
const eventTypeEl = screen.getByTestId("current-routing-status-event-type");
expect(eventTypeEl).toHaveTextContent(eventTypeText);
await expect(eventTypeEl.querySelector("a")).toHaveAttribute("href", eventTypeHref);
}
async function expectEventTypeInfoInReroutePreview({
eventTypeText,
eventTypeHref,
}: {
eventTypeText: string;
eventTypeHref: string;
}) {
const eventTypeEl = screen.getByTestId("reroute-preview-event-type");
expect(eventTypeEl).toHaveTextContent(eventTypeText);
await expect(eventTypeEl.querySelector("a")).toHaveAttribute("href", eventTypeHref);
}
function expectOrganizerInfoInCurrentRouting({ organizerText }: { organizerText: string }) {
const organizerEl = screen.getByTestId("current-routing-status-organizer");
expect(organizerEl).toHaveTextContent(organizerText);
}
function expectAttendeesInfoInCurrentRouting({ attendeesText }: { attendeesText: string }) {
const attendeesEl = screen.getByTestId("current-routing-status-attendees");
expect(attendeesEl).toHaveTextContent(attendeesText);
}
const userWhoBooked = { id: 1, name: "Test User", email: "[email protected]" };
const mockBooking = {
id: 1,
uid: "original-booking-uid",
title: "Test Booking",
startTime: new Date(new Date().setDate(new Date().getDate() + 1)).toISOString(),
metadata: {},
responses: {},
attendees: [{ email: "[email protected]", name: "Attendee", timeZone: "UTC", locale: "en" }],
eventType: {
id: 1,
slug: "test-event",
team: { slug: "test-team" },
length: 60,
schedulingType: SchedulingType.ROUND_ROBIN,
title: "Test Event",
},
user: userWhoBooked,
routedFromRoutingFormReponse: { id: 1 },
status: BookingStatus.ACCEPTED, // Add this line
};
const buildBooking = () => {
return {
...mockBooking,
};
};
describe("RerouteDialog", () => {
const mockSetIsOpenDialog = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
});
test("renders the dialog when open", () => {
render(
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
</TooltipProvider>
);
expect(screen.getByText("reroute_booking")).toBeInTheDocument();
expect(screen.getByText("reroute_booking_description")).toBeInTheDocument();
});
test("doesn't render the dialog when closed", () => {
render(
<TooltipProvider>
<RerouteDialog isOpenDialog={false} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
</TooltipProvider>
);
expect(screen.queryByText("reroute_booking")).not.toBeInTheDocument();
});
test("displays current routing status", async () => {
render(
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
</TooltipProvider>
);
expect(screen.getByText("current_routing_status")).toBeInTheDocument();
expectEventTypeInfoInCurrentRouting({
eventTypeText: "team/test-team/test-event",
eventTypeHref: "https://cal.com/team/test-team/test-event",
});
expectOrganizerInfoInCurrentRouting({
organizerText: "[email protected]",
});
expectAttendeesInfoInCurrentRouting({
attendeesText: "[email protected]",
});
// screen.logTestingPlaygroundURL()
});
test("verify_new_route button is enabled even when form fields are not filled", async () => {
render(
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
</TooltipProvider>
);
await expect(screen.getByText("verify_new_route")).toBeEnabled();
});
test("disabledFields are passed to FormInputFields with value ['email'] - email field is disabled", async () => {
render(
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
</TooltipProvider>
);
expect(screen.getByTestId("mock-form-field-disabled-fields-identifiers")).toHaveTextContent(/^email$/);
});
test("Expect form fields and name to be rendered", async () => {
render(
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
</TooltipProvider>
);
expect(screen.getByText("Test Form")).toBeInTheDocument();
expect(screen.getByTestId("mock-form-field-company-size-label")).toHaveTextContent("Company Size");
expect(screen.getByTestId("mock-form-field-company-size-value")).toHaveTextContent("small");
expect(screen.getByTestId("mock-form-field-country-label")).toHaveTextContent("Country");
expect(screen.getByTestId("mock-form-field-country-value")).toHaveTextContent("usa");
});
test("cancel button closes the dialog", async () => {
render(
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
</TooltipProvider>
);
expect(screen.getByText("cancel")).toBeInTheDocument();
fireEvent.click(screen.getByText("cancel"));
expect(mockSetIsOpenDialog).toHaveBeenCalledWith(false);
});
describe("New Routing tests", () => {
test("when verify_new_route is clicked, the form is submitted", async () => {
render(
<SessionProvider session={mockSession}>
<TooltipProvider>
<RerouteDialog isOpenDialog={true} setIsOpenDialog={mockSetIsOpenDialog} booking={mockBooking} />
</TooltipProvider>
</SessionProvider>
);
fireEvent.click(screen.getByText("verify_new_route"));
expectEventTypeInfoInReroutePreview({
eventTypeText: "team/test-team/new-test-event",
eventTypeHref: "https://cal.com/team/test-team/new-test-event",
});
await expect(screen.getByText("verify_new_route")).toBeEnabled();
expect(screen.getByTestId("reroute-preview-hosts")).toHaveTextContent("reroute_preview_possible_host");
expect(screen.getByTestId("reroute-preview-hosts")).toHaveTextContent("[email protected]");
expect(screen.getByText("reschedule_to_the_new_event_with_different_timeslot")).toBeInTheDocument();
expect(screen.getByText("reschedule_with_same_timeslot_of_new_event")).toBeInTheDocument();
});
describe("New tab rescheduling", () => {
test("new tab is closed when new booking is rerouted", async () => {
render(
<SessionProvider session={mockSession}>
<TooltipProvider>
<RerouteDialog
isOpenDialog={true}
setIsOpenDialog={mockSetIsOpenDialog}
booking={mockBooking}
/>
</TooltipProvider>
</SessionProvider>
);
clickVerifyNewRouteButton();
clickRescheduleToTheNewEventWithDifferentTimeslotButton();
await mockMessageFromOpenedTab({
type: "CAL:rescheduleBookingSuccessfulV2",
data: {
uid: "RESCHEDULED_BOOKING_UID_NEW_TAB",
},
});
const rescheduleTabUrl = mockOpen.mock.calls[0][0] as unknown as string;
const rescheduleTabUrlObject = new URL(rescheduleTabUrl, "http://mockcal.com");
expect(Object.fromEntries(rescheduleTabUrlObject.searchParams.entries())).toEqual(
expect.objectContaining({
rescheduleUid: mockBooking.uid,
"cal.rerouting": "true",
// Shouldn't include the user who booked the booking
"cal.routedTeamMemberIds": "2",
"cal.reroutingFormResponses": JSON.stringify({
"company-size": {
value: "small",
},
country: {
value: "usa",
},
}),
})
);
expect(fakeNewTabWindow.close).toHaveBeenCalled();
expectToBeNavigatedToBookingPage({
booking: {
uid: "RESCHEDULED_BOOKING_UID_NEW_TAB",
},
});
});
test("Rescheduling with same timeslot works", async () => {
render(
<SessionProvider session={mockSession}>
<TooltipProvider>
<RerouteDialog
isOpenDialog={true}
setIsOpenDialog={mockSetIsOpenDialog}
booking={mockBooking}
/>
</TooltipProvider>
</SessionProvider>
);
clickVerifyNewRouteButton();
clickRescheduleWithSameTimeslotOfChosenEventButton();
expect(mockReactQueryMutateFn).toHaveBeenCalledWith(
expect.objectContaining({
rescheduleUid: mockBooking.uid,
// Shouldn't include the user who booked the booking
routedTeamMemberIds: [2],
reroutingFormResponses: {
"company-size": {
value: "small",
},
country: {
value: "usa",
},
},
})
);
expectToBeNavigatedToBookingPage({
booking: {
uid: "RESCHEDULED_BOOKING_UID_SAME_TIMESLOT",
},
});
});
});
});
});
function clickVerifyNewRouteButton() {
act(() => {
fireEvent.click(screen.getByText("verify_new_route"));
});
}
function clickRescheduleToTheNewEventWithDifferentTimeslotButton() {
act(() => {
fireEvent.click(screen.getByText("reschedule_to_the_new_event_with_different_timeslot"));
});
}
function clickRescheduleWithSameTimeslotOfChosenEventButton() {
act(() => {
fireEvent.click(screen.getByText("reschedule_with_same_timeslot_of_new_event"));
});
}
function expectToBeNavigatedToBookingPage({
booking,
}: {
booking: {
uid: string;
};
}) {
expect(mockRouter.push).toHaveBeenCalledWith(`/booking/${booking.uid}?cal.rerouting=true`);
}
@@ -1,50 +0,0 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { showToast } from "@calcom/ui/components/toast";
const DisableUserImpersonation = ({ disableImpersonation }: { disableImpersonation: boolean }) => {
const utils = trpc.useUtils();
const { t } = useLocale();
const mutation = trpc.viewer.me.updateProfile.useMutation({
onSuccess: async () => {
showToast(t("your_user_profile_updated_successfully"), "success");
await utils.viewer.me.invalidate();
},
});
return (
<>
<div className="flex flex-col justify-between pl-2 pt-9 sm:flex-row">
<div>
<div className="flex flex-row items-center">
<h2 className="font-cal text-emphasis text-lg font-medium leading-6">
{t("user_impersonation_heading")}
</h2>
<Badge className="ml-2 text-xs" variant={!disableImpersonation ? "success" : "gray"}>
{!disableImpersonation ? t("enabled") : t("disabled")}
</Badge>
</div>
<p className="text-subtle mt-1 text-sm">{t("user_impersonation_description")}</p>
</div>
<div className="mt-5 sm:mt-0 sm:self-center">
<Button
type="submit"
color="secondary"
onClick={() =>
!disableImpersonation
? mutation.mutate({ disableImpersonation: true })
: mutation.mutate({ disableImpersonation: false })
}>
{!disableImpersonation ? t("disable") : t("enable")}
</Button>
</div>
</div>
</>
);
};
export default DisableUserImpersonation;
@@ -1,79 +0,0 @@
"use client";
import { signIn } from "next-auth/react";
import { useState } from "react";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { getRecentImpersonations, type RecentImpersonation } from "@calcom/lib/recentImpersonations";
import { Button } from "@calcom/ui/components/button";
import { PanelCard } from "@calcom/ui/components/card";
import {
TableNew,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@calcom/ui/components/table";
interface RecentImpersonationsListProps {
onImpersonate?: (username: string) => void;
}
export default function RecentImpersonationsList({ onImpersonate }: RecentImpersonationsListProps) {
const { t } = useLocale();
const [recentImpersonations] = useState<RecentImpersonation[]>(() => getRecentImpersonations());
const handleQuickImpersonate = (username: string) => {
if (onImpersonate) {
onImpersonate(username);
} else {
signIn("impersonation-auth", {
username: username.toLowerCase(),
callbackUrl: `${WEBAPP_URL}/event-types`,
});
}
};
if (recentImpersonations.length === 0) {
return null;
}
return (
<PanelCard title={t("recent_impersonations")}>
<div className="overflow-x-auto">
<TableNew className="border-0">
<TableHeader>
<TableRow>
<TableHead className="w-[40%]">User</TableHead>
<TableHead>Impersonated At</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{recentImpersonations.map((impersonation) => (
<TableRow key={impersonation.username}>
<TableCell className="font-medium">{impersonation.username}</TableCell>
<TableCell className="text-muted-foreground">
{new Date(impersonation.timestamp).toLocaleDateString()}{" "}
{new Date(impersonation.timestamp).toLocaleTimeString()}
</TableCell>
<TableCell className="text-right">
<Button
type="button"
color="secondary"
size="sm"
onClick={() => handleQuickImpersonate(impersonation.username)}
data-testid={`quick-impersonate-${impersonation.username}`}>
{t("quick_impersonate")}
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</TableNew>
</div>
</PanelCard>
);
}
@@ -1,43 +0,0 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Card } from "@calcom/ui/components/card";
import { Icon } from "@calcom/ui/components/icon";
import { helpCards } from "@lib/settings/platform/utils";
import { useGetUserAttributes } from "@components/settings/platform/hooks/useGetUserAttributes";
export const HelpCards = () => {
const { t } = useLocale();
const { userBillingData } = useGetUserAttributes();
const isPaidUser = userBillingData?.valid && userBillingData?.plan?.toLowerCase() !== "free";
return (
<>
<div className="grid-col-1 mb-4 grid gap-2 md:grid-cols-3">
{helpCards.map((card) => {
if (card.title === "Contact us" && !isPaidUser) return null;
const title = card.title === "Report issue" ? t("report_issue") : card.title;
const description =
card.title === "Report issue" ? t("report_issue_description") : card.description;
const actionButtonChild = card.title === "Report issue" ? t("open_issue") : card.actionButton.child;
return (
<div key={card.title}>
<Card
icon={<Icon name={card.icon} className="h-5 w-5 text-green-700" />}
variant={card.variant}
title={title}
description={description}
actionButton={{
href: `${card.actionButton.href}`,
child: actionButtonChild,
}}
/>
</div>
);
})}
</div>
</>
);
};
@@ -1,38 +0,0 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
export default function NoPlatformPlan() {
const { t } = useLocale();
return (
<EmptyScreen
Icon="credit-card"
headline={t("subscription_needed")}
description={t("subscription_needed_description")}
buttonRaw={
<div className="flex gap-2">
<Button
className="hover:bg-slate-300 hover:text-black"
color="secondary"
href="/settings/platform/new">
Subscribe
</Button>
<Button
color="secondary"
className="hover:bg-slate-300 hover:text-black"
href="https://cal.com/platform/pricing"
target="_blank">
Go to Pricing
</Button>
<Button
color="secondary"
className="hover:bg-slate-300 hover:text-black"
href="https://cal.com/sales"
target="_blank">
Contact Sales
</Button>
</div>
}
/>
);
}
@@ -1,85 +0,0 @@
import { useRouter } from "next/navigation";
import type { PlatformOAuthClientDto } from "@calcom/platform-types";
import { Button } from "@calcom/ui/components/button";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { OAuthClientCard } from "@components/settings/platform/oauth-clients/OAuthClientCard";
type OAuthClientsListProps = {
oauthClients: PlatformOAuthClientDto[];
isDeleting: boolean;
handleDelete: (id: string) => Promise<void>;
};
export const OAuthClientsList = ({ oauthClients, isDeleting, handleDelete }: OAuthClientsListProps) => {
return (
<div className="mb-10">
<div className="border-subtle mx-auto block justify-between rounded-t-lg border px-4 py-6 sm:flex sm:px-6">
<div className="flex w-full flex-col">
<h1 className="font-cal text-emphasis mb-1 text-xl font-semibold leading-5 tracking-wide">
OAuth Clients
</h1>
<p className="text-default text-sm ltr:mr-4 rtl:ml-4">
Connect your platform to cal.com with OAuth
</p>
</div>
<div>
<NewOAuthClientButton redirectLink="/settings/platform/oauth-clients/create" />
</div>
</div>
{Array.isArray(oauthClients) && oauthClients.length ? (
<>
<div className="border-subtle rounded-b-lg border border-t-0">
{oauthClients.map((client, index) => {
return (
<OAuthClientCard
name={client.name}
redirectUris={client.redirectUris}
bookingRedirectUri={client.bookingRedirectUri}
bookingRescheduleRedirectUri={client.bookingRescheduleRedirectUri}
bookingCancelRedirectUri={client.bookingCancelRedirectUri}
permissions={client.permissions}
key={index}
lastItem={oauthClients.length === index + 1}
id={client.id}
secret={client.secret}
isLoading={isDeleting}
onDelete={handleDelete}
areEmailsEnabled={client.areEmailsEnabled}
areDefaultEventTypesEnabled={client.areDefaultEventTypesEnabled}
areCalendarEventsEnabled={client.areCalendarEventsEnabled}
organizationId={client.organizationId}
/>
);
})}
</div>
</>
) : (
<EmptyScreen
headline="Create your first OAuth client"
description="OAuth clients facilitate access to Cal.com on behalf of users"
Icon="plus"
className=""
buttonRaw={<NewOAuthClientButton redirectLink="/settings/platform/oauth-clients/create" />}
/>
)}
</div>
);
};
const NewOAuthClientButton = ({ redirectLink, label }: { redirectLink: string; label?: string }) => {
const router = useRouter();
return (
<Button
onClick={(e) => {
e.preventDefault();
router.push(redirectLink);
}}
color="secondary"
StartIcon="plus">
{!!label ? label : "Add"}
</Button>
);
};
@@ -1,30 +0,0 @@
import { useCheckTeamBilling } from "@calcom/web/lib/hooks/settings/platform/billing/useCheckTeamBilling";
import { usePlatformMe } from "./usePlatformMe";
export const useGetUserAttributes = () => {
const {
data: platformUser,
isLoading: isPlatformUserLoading,
refetch: refetchPlatformUser,
} = usePlatformMe();
const {
data: userBillingData,
isFetching: isUserBillingDataLoading,
refetch: refetchTeamBilling,
} = useCheckTeamBilling(platformUser?.organizationId, platformUser?.organization?.isPlatform ?? false);
const isPlatformUser = platformUser?.organization?.isPlatform ?? false;
const isPaidUser = userBillingData?.valid;
const userOrgId = platformUser?.organizationId;
return {
isUserLoading: isPlatformUserLoading,
isUserBillingDataLoading,
isPlatformUser,
isPaidUser,
userBillingData,
userOrgId,
refetchTeamBilling,
refetchPlatformUser,
};
};
@@ -1,15 +0,0 @@
import { trpc } from "@calcom/trpc/react";
export function usePlatformMe() {
const meQuery = trpc.viewer.me.platformMe.useQuery(undefined, {
retry(failureCount) {
return failureCount > 3;
},
// 5 minutes
staleTime: 300000,
});
return meQuery;
}
export default usePlatformMe;
@@ -1,204 +0,0 @@
import { useRouter } from "next/navigation";
import React from "react";
import type { PERMISSION_MAP } from "@calcom/platform-constants";
import { PERMISSIONS_GROUPED_MAP } from "@calcom/platform-constants";
import type { Avatar } from "@calcom/prisma/client";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
type OAuthClientCardProps = {
name: string;
logo?: Avatar;
redirectUris: string[];
bookingRedirectUri: string | null | undefined;
bookingCancelRedirectUri: string | null | undefined;
bookingRescheduleRedirectUri: string | null | undefined;
areEmailsEnabled: boolean | undefined;
areDefaultEventTypesEnabled: boolean;
areCalendarEventsEnabled: boolean;
permissions: Array<keyof typeof PERMISSION_MAP>;
lastItem: boolean;
id: string;
secret: string;
onDelete: (id: string) => Promise<void>;
isLoading: boolean;
organizationId: number;
};
export const OAuthClientCard = ({
name,
logo,
redirectUris,
bookingRedirectUri,
bookingCancelRedirectUri,
bookingRescheduleRedirectUri,
permissions,
id,
secret,
lastItem,
onDelete,
isLoading,
areEmailsEnabled,
areDefaultEventTypesEnabled,
areCalendarEventsEnabled,
organizationId,
}: OAuthClientCardProps) => {
const router = useRouter();
const groupedPermissions = permissions.reduce<Record<string, { read: boolean; write: boolean }>>(
(acc, permission) => {
const [resource] = permission.split("_READ") as [string] | [string, string];
const isRead = permission.endsWith("_READ");
const isWrite = permission.endsWith("_WRITE");
const key = resource.replace("_WRITE", "");
if (!acc[key]) acc[key] = { read: false, write: false };
if (isRead) acc[key].read = true;
if (isWrite) acc[key].write = true;
return acc;
},
{}
);
const clientPermissions = Object.entries(groupedPermissions).map(([resource, { read, write }], index) => {
const permissionTypes = [];
if (read) permissionTypes.push("read");
if (write) permissionTypes.push("write");
const permissionsMessage = permissionTypes.join("/");
const groupedPermission = PERMISSIONS_GROUPED_MAP[resource as keyof typeof PERMISSIONS_GROUPED_MAP];
const isLastItem = index === Object.keys(groupedPermissions).length - 1;
return (
<div key={resource} className="relative text-sm">
&nbsp;{permissionsMessage} {groupedPermission?.label.toLowerCase()}
{!isLastItem && ", "}
</div>
);
});
return (
<div
className={classNames(
"flex w-full justify-between px-4 py-4 sm:px-6",
lastItem ? "" : "border-subtle border-b"
)}>
<div className="flex flex-col gap-2">
<div className="flex gap-1">
<p className="font-semibold">
Client name: <span className="font-normal">{name}</span>
</p>
</div>
{!!logo && (
<div>
<>{logo}</>
</div>
)}
<div className="flex flex-col gap-2">
<div className="flex flex-row items-center gap-2">
<div className="font-semibold">Client Id:</div>
<div>{id}</div>
<Icon
name="clipboard"
type="button"
className="h-4 w-4 cursor-pointer"
onClick={() => {
navigator.clipboard.writeText(id);
showToast("Client id copied to clipboard.", "success");
}}
/>
</div>
</div>
<div className="flex items-center gap-2">
<div className="font-semibold">Client Secret:</div>
<div className="flex items-center justify-center rounded-md">
{[...new Array(20)].map((_, index) => (
<Icon name="asterisk" key={`${index}asterisk`} className="h-2 w-2" />
))}
<Icon
name="clipboard"
type="button"
className="ml-2 h-4 w-4 cursor-pointer"
onClick={() => {
navigator.clipboard.writeText(secret);
showToast("Client secret copied to clipboard.", "success");
}}
/>
</div>
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-row items-center gap-2">
<div className="font-semibold">Organization Id:</div>
<div>{organizationId}</div>
<Icon
name="clipboard"
type="button"
className="h-4 w-4 cursor-pointer"
onClick={() => {
navigator.clipboard.writeText(organizationId.toString());
showToast("Organization id copied to clipboard.", "success");
}}
/>
</div>
</div>
<div className="border-subtle flex text-sm">
<span className="font-semibold">Permissions: </span>
{permissions ? <div className="flex">{clientPermissions}</div> : <>&nbsp;Disabled</>}
</div>
<div className="flex gap-1 text-sm">
<span className="font-semibold">Redirect uris: </span>
{redirectUris.map((item, index) => (redirectUris.length === index + 1 ? `${item}` : `${item}, `))}
</div>
{bookingRedirectUri && (
<div className="flex gap-1 text-sm">
<span className="font-semibold">Booking redirect uri: </span> {bookingRedirectUri}
</div>
)}
{bookingRescheduleRedirectUri && (
<div className="flex gap-1 text-sm">
<span className="font-semibold">Booking reschedule uri: </span> {bookingRescheduleRedirectUri}
</div>
)}
{bookingCancelRedirectUri && (
<div className="flex gap-1 text-sm">
<span className="font-semibold">Booking cancel uri: </span> {bookingCancelRedirectUri}
</div>
)}
<div className="flex gap-1 text-sm">
<span className="text-sm font-semibold">Emails enabled:</span> {areEmailsEnabled ? "Yes" : "No"}
</div>
<div className="flex gap-1 text-sm">
<span className="text-sm font-semibold">Default event types enabled:</span>{" "}
{areDefaultEventTypesEnabled ? "Yes" : "No"}
</div>
<div className="flex gap-1 text-sm">
<span className="text-sm font-semibold">Calendar events enabled:</span>{" "}
{areCalendarEventsEnabled ? "Yes" : "No"}
</div>
</div>
<div className="flex items-start gap-4">
<Button
color="primary"
loading={isLoading}
disabled={isLoading}
onClick={() => router.push(`/settings/platform/oauth-clients/${id}/edit/webhooks`)}>
Webhooks
</Button>
<Button
color="secondary"
loading={isLoading}
disabled={isLoading}
onClick={() => router.push(`/settings/platform/oauth-clients/${id}/edit`)}>
Edit
</Button>
<Button color="destructive" loading={isLoading} disabled={isLoading} onClick={() => onDelete(id)}>
Delete
</Button>
</div>
</div>
);
};
@@ -1,275 +0,0 @@
import { useState, useCallback } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PERMISSIONS_GROUPED_MAP } from "@calcom/platform-constants/permissions";
import { Button } from "@calcom/ui/components/button";
import { Label, TextField } from "@calcom/ui/components/form";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { InfoIcon } from "@coss/ui/icons";
type OAuthClientFormProps = {
defaultValues?: Partial<FormValues>;
isPending?: boolean;
isFormDisabled?: boolean;
onSubmit: (data: FormValues) => void;
};
export type FormValues = {
name: string;
logo?: string;
permissions: number;
eventTypeRead: boolean;
eventTypeWrite: boolean;
bookingRead: boolean;
bookingWrite: boolean;
scheduleRead: boolean;
scheduleWrite: boolean;
appsRead: boolean;
appsWrite: boolean;
profileRead: boolean;
profileWrite: boolean;
redirectUris: {
uri: string;
}[];
bookingRedirectUri?: string;
bookingCancelRedirectUri?: string;
bookingRescheduleRedirectUri?: string;
areEmailsEnabled?: boolean;
areDefaultEventTypesEnabled?: boolean;
areCalendarEventsEnabled?: boolean;
};
export const OAuthClientForm = ({
defaultValues,
isPending,
isFormDisabled,
onSubmit,
}: OAuthClientFormProps) => {
const { t } = useLocale();
const { register, control, handleSubmit, setValue } = useForm<FormValues>({
defaultValues: { redirectUris: [{ uri: "" }], ...defaultValues },
});
const { fields, append, remove } = useFieldArray({
control,
name: "redirectUris",
});
const [isSelectAllPermissionsChecked, setIsSelectAllPermissionsChecked] = useState(false);
const selectAllPermissions = useCallback(() => {
Object.keys(PERMISSIONS_GROUPED_MAP).forEach((key) => {
const entity = key as keyof typeof PERMISSIONS_GROUPED_MAP;
const permissionKey = PERMISSIONS_GROUPED_MAP[entity].key;
setValue(`${permissionKey}Read`, !isSelectAllPermissionsChecked);
setValue(`${permissionKey}Write`, !isSelectAllPermissionsChecked);
});
setIsSelectAllPermissionsChecked((preValue) => !preValue);
}, [isSelectAllPermissionsChecked, setValue]);
const permissionsCheckboxes = Object.keys(PERMISSIONS_GROUPED_MAP).map((key) => {
const entity = key as keyof typeof PERMISSIONS_GROUPED_MAP;
const permissionKey = PERMISSIONS_GROUPED_MAP[entity].key;
const permissionLabel = PERMISSIONS_GROUPED_MAP[entity].label;
return (
<div className="my-3" key={key}>
<p className="text-sm font-semibold">{permissionLabel}</p>
<div className="mt-1 flex gap-x-5">
<div className="flex items-center gap-x-2">
<input
{...register(`${permissionKey}Read`)}
id={`${permissionKey}Read`}
className="border-default bg-default h-4 w-4 shrink-0 cursor-pointer rounded-[4px] border ring-offset-2 transition checked:border-transparent checked:bg-gray-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed"
style={{ accentColor: "#ffffff" }}
type="checkbox"
disabled={!!defaultValues}
/>
<label htmlFor={`${permissionKey}Read`} className="cursor-pointer text-sm">
Read
</label>
</div>
<div className="flex items-center gap-x-2">
<input
{...register(`${permissionKey}Write`)}
id={`${permissionKey}Write`}
className="border-default bg-default h-4 w-4 shrink-0 cursor-pointer rounded-[4px] border ring-offset-2 transition checked:border-transparent checked:bg-gray-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed"
style={{ accentColor: "#ffffff" }}
type="checkbox"
disabled={!!defaultValues}
/>
<label htmlFor={`${permissionKey}Write`} className="cursor-pointer text-sm">
Write
</label>
</div>
</div>
</div>
);
});
return (
<div>
<form
className="border-subtle rounded-b-lg border border-t-0 px-4 pb-8 pt-2"
onSubmit={handleSubmit(onSubmit)}>
<div className="mt-6">
<TextField disabled={isFormDisabled} required={true} label="Client name" {...register("name")} />
</div>
<div className="mt-6">
<Label>Redirect uris</Label>
{fields.map((field, index) => {
return (
<div className="flex items-end" key={field.id}>
<div className="w-[80vw]">
<TextField
type="url"
required={index === 0}
className="w-full"
label=""
disabled={isFormDisabled}
{...register(`redirectUris.${index}.uri` as const)}
/>
</div>
<div className="flex">
<Button
tooltip="Add url"
type="button"
color="minimal"
variant="icon"
StartIcon="plus"
className="text-default mx-2"
disabled={isFormDisabled}
onClick={() => {
append({ uri: "" });
}}
/>
{index > 0 && (
<Button
tooltip="Remove url"
type="button"
color="destructive"
variant="icon"
StartIcon="trash"
className="text-default mx-2"
disabled={isFormDisabled}
onClick={() => {
remove(index);
}}
/>
)}
</div>
</div>
);
})}
</div>
<div className="mt-6">
<Tooltip content={t("booking_redirect_uri")}>
<TextField
type="url"
label="Booking redirect uri"
className="w-full"
{...register("bookingRedirectUri")}
disabled={isFormDisabled}
/>
</Tooltip>
</div>
<div className="mt-6">
<Tooltip content={t("booking_cancel_redirect_uri")}>
<TextField
type="url"
label="Booking cancel redirect uri"
className="w-full"
{...register("bookingCancelRedirectUri")}
disabled={isFormDisabled}
/>
</Tooltip>
</div>
<div className="mt-6">
<Tooltip content={t("booking_reschedule_redirect_uri")}>
<TextField
type="url"
label="Booking reschedule redirect uri"
className="w-full"
{...register("bookingRescheduleRedirectUri")}
disabled={isFormDisabled}
/>
</Tooltip>
</div>
<div className="mt-6">
<input
{...register("areEmailsEnabled")}
id="areEmailsEnabled"
className="border-default bg-default h-4 w-4 shrink-0 cursor-pointer rounded-[4px] border ring-offset-2 transition checked:border-transparent checked:bg-gray-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed"
style={{ accentColor: "#ffffff" }}
type="checkbox"
disabled={isFormDisabled}
/>
<label htmlFor="areEmailsEnabled" className="cursor-pointer px-2 text-base font-semibold">
Enable emails
</label>
</div>
<div className="mt-6">
<div className="flex items-center">
<input
{...register("areCalendarEventsEnabled")}
id="areCalendarEventsEnabled"
className="border-default bg-default h-4 w-4 shrink-0 cursor-pointer rounded-[4px] border ring-offset-2 transition checked:border-transparent checked:bg-gray-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed"
style={{ accentColor: "#ffffff" }}
type="checkbox"
disabled={isFormDisabled}
/>
<label htmlFor="areCalendarEventsEnabled" className="cursor-pointer px-2 text-base font-semibold">
Enable calendar events
</label>
<Tooltip
className="max-w-[400px] whitespace-normal"
content="If enabled and the managed user has calendar connected, an event in the calendar will be created. By default true. Disable it if you want to create events in the calendar manually.">
<div className="ml-1">
<InfoIcon className="h-4 w-4 text-gray-500" />
</div>
</Tooltip>
</div>
<p className="text-subtle mt-2 text-sm">{t("calendar_events_disabled_video_limitation")}</p>
</div>
<div className="mt-6">
<div className="flex items-center">
<input
{...register("areDefaultEventTypesEnabled")}
id="areDefaultEventTypesEnabled"
className="border-default bg-default h-4 w-4 shrink-0 cursor-pointer rounded-[4px] border ring-offset-2 transition checked:border-transparent checked:bg-gray-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed"
style={{ accentColor: "#ffffff" }}
type="checkbox"
disabled={isFormDisabled}
/>
<label
htmlFor="areDefaultEventTypesEnabled"
className="cursor-pointer px-2 text-base font-semibold">
Enable managed user default event types
</label>
<Tooltip
className="max-w-[400px] whitespace-normal"
content="If enabled, when creating a managed user the managed user will have 4 default event types: 30 and 60 minutes without Cal video, 30 and 60 minutes with Cal video. Leave this disabled if you want to create a managed user and then manually create event types for the user.">
<div className="ml-1">
<InfoIcon className="h-4 w-4 text-gray-500" />
</div>
</Tooltip>
</div>
</div>
<div className="mt-6">
<div className="flex justify-between">
<h1 className="text-base font-semibold underline">Permissions</h1>
<Button type="button" onClick={selectAllPermissions} disabled={!!defaultValues || isFormDisabled}>
{!isSelectAllPermissionsChecked ? "Select all" : "Discard all"}
</Button>
</div>
<div>{permissionsCheckboxes}</div>
</div>
<Button className="mt-6" type="submit" loading={isPending}>
{defaultValues ? t("update") : t("submit")}
</Button>
</form>
</div>
);
};
@@ -1,69 +0,0 @@
type IndividualPlatformPlan = {
plan: string;
description: string;
pricing?: number;
includes: string[];
};
// if pricing or plans change in future modify this
export const platformPlans: IndividualPlatformPlan[] = [
{
plan: "Free",
description:
"The best plan to dip your toes into scheduling infrastructure. Start immediately with 25 free meetings per month",
pricing: 0,
includes: [
"Up to 25 bookings a month",
"$0.99 overage beyond",
"Community Support",
"Cal Atoms (React Library)",
"Platform APIs",
],
},
{
plan: "Essentials",
description:
"Your essential package with sophisticated support, hosted platform APIs, Cal.com Atoms (React components) and more.",
pricing: 299,
includes: [
"Everything in Starter",
"Up to 500 bookings a month",
"$0.60 overage beyond",
"User Management and Analytics",
"Technical Account Manager and Onboarding Support",
],
},
{
plan: "Scale",
description:
"The best all-in-one plan to scale your company. Everything you need to provide scheduling for the masses, without breaking things.",
pricing: 2499,
includes: [
"Everything in Essentials",
"Up to 5000 bookings a month",
"$0.50 overage beyond",
"Credential import from other platforms",
"Compliance Check SOC2, HIPAA",
"One-on-one developer calls",
"Help with Credentials Verification (Zoom, Google App Store)",
"Expedited features and integrations",
"SLA (99.999% uptime)",
],
},
{
plan: "Enterprise",
description:
"Enterprise is perfect for institutions that focus on control, security and everything beyond.",
includes: [
"Everything in Scale",
"No overages",
"Credential import from other platforms",
"Compliance Check SOC2, HIPAA",
"One-on-one developer calls",
"Help with Credentials Verification (Zoom, Google App Store)",
"Expedited features and integrations",
"SLA (99.999% uptime)",
"Volume Discount",
],
},
];
@@ -1,72 +0,0 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
type PlatformBillingCardProps = {
plan: string;
description: string;
pricing?: number;
includes: string[];
isLoading?: boolean;
currentPlan?: boolean;
handleSubscribe?: () => void;
};
export const PlatformBillingCard = ({
plan,
description,
pricing,
includes,
isLoading,
handleSubscribe,
currentPlan,
}: PlatformBillingCardProps) => {
const { t } = useLocale();
return (
<div className="border-subtle max-w-[450px] rounded-2xl border p-5 md:mx-4">
<div className="pb-5">
<h1 className="border-b pb-2 pt-1 text-center text-2xl font-bold">
{plan}
{currentPlan && (
<>
<Button
type="button"
StartIcon="circle-check"
className="bg-default hover:bg-default cursor-none text-green-500 hover:cursor-pointer"
tooltip={t("this_is_your_current_plan")}
/>
</>
)}
</h1>
<p className="pb-5 pt-3 text-base">{description}</p>
<h1 className="text-3xl font-semibold">
{pricing !== undefined && (
<>
US${pricing} <span className="text-sm">{t("per_month")}</span>
</>
)}
</h1>
</div>
{!currentPlan && (
<div>
<Button
loading={isLoading}
onClick={handleSubscribe}
className="flex w-full items-center justify-center">
{pricing !== undefined ? t("subscribe") : t("schedule_a_time")}
</Button>
</div>
)}
<div className="mt-5">
<p>{t("this_includes")}</p>
{includes.map((feature) => {
return (
<div key={feature} className="my-2 flex">
<div className="pr-2">&bull;</div>
<div>{feature}</div>
</div>
);
})}
</div>
</div>
);
};
@@ -1,92 +0,0 @@
import { useRouter } from "next/navigation";
import { usePathname } from "next/navigation";
import type { ReactNode } from "react";
import { useState } from "react";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { showToast } from "@calcom/ui/components/toast";
import { useSubscribeTeamToStripe } from "@lib/hooks/settings/platform/billing/useSubscribeTeamToStripe";
import { useUpgradeTeamSubscriptionInStripe } from "@lib/hooks/settings/platform/billing/useUpgradeTeamSubscriptionInStripe";
import { platformPlans } from "@components/settings/platform/platformUtils";
import { PlatformBillingCard } from "@components/settings/platform/pricing/billing-card";
type PlatformPricingProps = { teamId?: number | null; teamPlan?: string; heading?: ReactNode };
export const PlatformPricing = ({ teamId, teamPlan, heading }: PlatformPricingProps) => {
const pathname = usePathname();
const currentPage = pathname?.split("/").pop();
const router = useRouter();
const [loadingPlan, setLoadingPlan] = useState<string | null>(null);
const { mutateAsync: createTeamSubscription, isPending: isCreateTeamSubscriptionLoading } =
useSubscribeTeamToStripe({
onSuccess: (redirectUrl: string) => {
router.push(redirectUrl);
},
onError: () => {
showToast(ErrorCode.UnableToSubscribeToThePlatform, "error");
setLoadingPlan(null);
},
teamId,
});
const { mutateAsync: upgradeTeamSubscription, isPending: isUpgradeTeamSubscriptionLoading } =
useUpgradeTeamSubscriptionInStripe({
onSuccess: (redirectUrl: string) => {
router.push(redirectUrl);
},
onError: () => {
showToast(ErrorCode.UnableToSubscribeToThePlatform, "error");
setLoadingPlan(null);
},
teamId,
});
const handleStripeSubscription = async (plan: string) => {
if (plan === "Enterprise") {
return router.push("https://go.cal.com/quote");
}
setLoadingPlan(plan);
if (currentPage === "platform") {
createTeamSubscription({ plan: plan.toLocaleUpperCase() });
} else {
upgradeTeamSubscription({ plan: plan.toLocaleUpperCase() });
}
};
if (!teamId) {
return <div className="m-5">Platform team not present, you need to create a team first.</div>;
}
return (
<div className="flex h-auto flex-col items-center justify-center px-5 py-10 md:px-10 lg:h-full">
{heading}
<div>
<div className="grid grid-cols-1 gap-5 md:grid-cols-2 lg:grid-cols-4">
{platformPlans.map((plan) => {
return (
<div key={plan.plan} className="mx-10 my-4 md:mx-0 md:my-0">
<PlatformBillingCard
plan={plan.plan}
description={plan.description}
pricing={plan.pricing}
includes={plan.includes}
isLoading={
loadingPlan === plan.plan &&
(isCreateTeamSubscriptionLoading || isUpgradeTeamSubscriptionLoading)
}
currentPlan={plan.plan.toLocaleLowerCase() === teamPlan}
handleSubscribe={() => handleStripeSubscription(plan.plan)}
/>
</div>
);
})}
</div>
</div>
</div>
);
};
@@ -1,71 +0,0 @@
import * as RadioGroup from "@radix-ui/react-radio-group";
import classNames from "classnames";
import Link from "next/link";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
const ChooseLicense = (
props: {
value: string;
onChange: (value: string) => void;
onSubmit: (value: string) => void;
} & Omit<JSX.IntrinsicElements["form"], "onSubmit" | "onChange">
) => {
const { value: initialValue = "FREE", onChange, onSubmit, ...rest } = props;
const [value, setValue] = useState(initialValue);
const { t } = useLocale();
return (
<form
{...rest}
className="stack-y-4"
onSubmit={(e) => {
e.preventDefault();
onSubmit(value);
}}>
<RadioGroup.Root
defaultValue={initialValue}
value={value}
aria-label={t("choose_a_license")}
className="grid grid-rows-2 gap-4 md:grid-cols-2 md:grid-rows-1"
onValueChange={(value) => {
onChange(value);
setValue(value);
}}>
<RadioGroup.Item value="FREE">
<div
className={classNames(
"bg-default cursor-pointer stack-y-2 rounded-md border p-4 hover:border-black",
value === "FREE" && "ring-2 ring-black"
)}>
<h2 className="font-cal text-emphasis text-xl">{t("agplv3_license")}</h2>
<p className="font-medium text-green-800">{t("free_license_fee")}</p>
<p className="text-subtle">{t("forever_open_and_free")}</p>
<ul className="text-subtle ml-4 list-disc text-left text-xs">
<li>{t("required_to_keep_your_code_open_source")}</li>
<li>{t("cannot_repackage_and_resell")}</li>
<li>{t("no_enterprise_features")}</li>
</ul>
</div>
</RadioGroup.Item>
<RadioGroup.Item value="EE" disabled>
<Link href="https://cal.com/sales" target="_blank">
<div className={classNames("bg-default h-full cursor-pointer stack-y-2 rounded-md border p-4")}>
<h2 className="font-cal text-emphasis text-xl">{t("custom_plan")}</h2>
<p className="font-medium text-green-800">{t("contact_sales")}</p>
<p className="text-subtle">Build on top of Cal.com</p>
<ul className="text-subtle ml-4 list-disc text-left text-xs">
<li>{t("no_need_to_keep_your_code_open_source")}</li>
<li>{t("repackage_rebrand_resell")}</li>
<li>{t("a_vast_suite_of_enterprise_features")}</li>
</ul>
</div>
</Link>
</RadioGroup.Item>
</RadioGroup.Root>
</form>
);
};
export default ChooseLicense;
@@ -1,146 +0,0 @@
import { zodResolver } from "@hookform/resolvers/zod";
// eslint-disable-next-line no-restricted-imports
import { noop } from "lodash";
import { useCallback, useState } from "react";
import { Controller, FormProvider, useForm, useFormState } from "react-hook-form";
import { z } from "zod";
import { CONSOLE_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterInputs, RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { TextField } from "@calcom/ui/components/form";
import { CheckIcon, LoaderIcon } from "@coss/ui/icons";
type EnterpriseLicenseFormValues = {
licenseKey: string;
};
const makeSchemaLicenseKey = (args: { callback: (valid: boolean) => void; onSuccessValidate: () => void }) =>
z.object({
licenseKey: z
.string()
.uuid({
message: "License key must follow UUID format: 8-4-4-4-12",
})
.superRefine(async (data, ctx) => {
const parse = z.string().uuid().safeParse(data);
if (parse.success) {
args.callback(true);
const response = await fetch(`${CONSOLE_URL}/api/license?key=${data}`);
args.callback(false);
const json = await response.json();
if (!json.valid) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `License key ${json.message.toLowerCase()}`,
});
} else {
args.onSuccessValidate();
}
}
}),
});
const EnterpriseLicense = (
props: {
licenseKey?: string;
initialValue?: Partial<EnterpriseLicenseFormValues>;
onSuccessValidate: () => void;
onSubmit: (value: EnterpriseLicenseFormValues) => void;
onSuccess?: (
data: RouterOutputs["viewer"]["deploymentSetup"]["update"],
variables: RouterInputs["viewer"]["deploymentSetup"]["update"]
) => void;
} & Omit<JSX.IntrinsicElements["form"], "onSubmit">
) => {
const { onSubmit, onSuccess = noop, onSuccessValidate = noop, ...rest } = props;
const { t } = useLocale();
const [checkLicenseLoading, setCheckLicenseLoading] = useState(false);
const mutation = trpc.viewer.deploymentSetup.update.useMutation({
onSuccess,
});
const schemaLicenseKey = useCallback(
() =>
makeSchemaLicenseKey({
callback: setCheckLicenseLoading,
onSuccessValidate,
}),
[setCheckLicenseLoading, onSuccessValidate]
);
const formMethods = useForm<EnterpriseLicenseFormValues>({
defaultValues: {
licenseKey: props.licenseKey || "",
},
resolver: zodResolver(schemaLicenseKey()),
});
const handleSubmit = formMethods.handleSubmit((values) => {
onSubmit(values);
setCheckLicenseLoading(false);
mutation.mutate(values);
});
const { isDirty, errors } = useFormState(formMethods);
return (
<FormProvider {...formMethods}>
<form {...rest} className="bg-default stack-y-4 rounded-md px-8 py-10" onSubmit={handleSubmit}>
<div>
<Button
className="w-full justify-center text-lg"
EndIcon="external-link"
href="https://go.cal.com/get-license"
target="_blank">
{t("purchase_license")}
</Button>
<div className="relative flex justify-center">
<hr className="border-subtle my-8 w-full border-[1.5px]" />
<span className="bg-default absolute mt-[22px] px-3.5 text-sm">OR</span>
</div>
{t("already_have_key")}
<Controller
name="licenseKey"
control={formMethods.control}
render={({ field: { onBlur, onChange, value } }) => (
<TextField
{...formMethods.register("licenseKey")}
className={classNames(
"group-hover:border-emphasis mb-0",
(checkLicenseLoading || (errors.licenseKey === undefined && isDirty)) && "border-r-0"
)}
placeholder="xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx"
labelSrOnly={true}
value={value}
addOnClassname={classNames(
"hover:border-default",
errors.licenseKey === undefined && isDirty && "group-hover:border-emphasis"
)}
addOnSuffix={
checkLicenseLoading ? (
<LoaderIcon className="h-5 w-5 animate-spin" />
) : errors.licenseKey === undefined && isDirty ? (
<CheckIcon className="h-5 w-5 text-green-700" />
) : undefined
}
color={errors.licenseKey ? "warn" : ""}
onBlur={onBlur}
onChange={async (e: React.ChangeEvent<HTMLInputElement>) => {
onChange(e.target.value);
formMethods.setValue("licenseKey", e.target.value);
await formMethods.trigger("licenseKey");
}}
/>
)}
/>
</div>
</form>
</FormProvider>
);
};
export default EnterpriseLicense;
@@ -1,255 +0,0 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import * as RadioGroup from "@radix-ui/react-radio-group";
import classNames from "classnames";
import Link from "next/link";
import { useCallback, useState } from "react";
import { Controller, FormProvider, useForm, useFormState } from "react-hook-form";
import { z } from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterInputs, RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { TextField } from "@calcom/ui/components/form";
import { CheckIcon, LoaderIcon } from "@coss/ui/icons";
type LicenseSelectionFormValues = {
licenseKey: string;
signatureToken?: string;
};
type LicenseOption = "FREE" | "EXISTING";
const LicenseSelection = (
props: {
value: LicenseOption;
onChange: (value: LicenseOption) => void;
onSubmit: (value: LicenseSelectionFormValues) => void;
onSuccess?: (
data: RouterOutputs["viewer"]["deploymentSetup"]["update"],
variables: RouterInputs["viewer"]["deploymentSetup"]["update"]
) => void;
onPrevStep: () => void;
onNextStep: () => void;
} & Omit<JSX.IntrinsicElements["form"], "onSubmit" | "onChange">
) => {
const {
value: initialValue = "FREE",
onChange,
onSubmit,
onSuccess,
onPrevStep,
onNextStep,
...rest
} = props;
const [value, setValue] = useState<LicenseOption>(initialValue);
const { t } = useLocale();
const mutation = trpc.viewer.deploymentSetup.update.useMutation({
onSuccess,
});
const [licenseKeyInput, setLicenseKeyInput] = useState("");
const [licenseTouched, setLicenseTouched] = useState(false);
// Use TRPC query for validation
const { data: licenseValidation, isLoading: checkLicenseLoading } =
trpc.viewer.deploymentSetup.validateLicense.useQuery(
{ licenseKey: licenseKeyInput },
{
enabled: licenseTouched && licenseKeyInput.trim().length > 0,
}
);
const schemaLicenseKey = useCallback(
() =>
z.object({
licenseKey: z
.string()
.min(1, t("license_key_required"))
.refine(() => !licenseTouched || (licenseValidation ? licenseValidation.valid : true), {
message: licenseValidation?.message || t("invalid_license_key"),
}),
signatureToken: z.string().optional(),
}),
[licenseValidation, licenseTouched, t]
);
const formMethods = useForm<LicenseSelectionFormValues>({
defaultValues: {
licenseKey: "",
signatureToken: "",
},
resolver: zodResolver(schemaLicenseKey()),
});
const handleSubmit = formMethods.handleSubmit((values) => {
onSubmit(values);
if (value === "EXISTING" && values.licenseKey) {
mutation.mutate(values);
}
});
const { isDirty, errors } = useFormState(formMethods);
const handleRadioChange = (newValue: LicenseOption) => {
setValue(newValue);
onChange(newValue);
};
return (
<form
{...rest}
className="stack-y-6"
onSubmit={(e) => {
e.preventDefault();
if (value === "FREE") {
onSubmit({ licenseKey: "", signatureToken: "" });
} else {
handleSubmit();
}
}}>
<RadioGroup.Root
defaultValue={initialValue}
value={value}
aria-label={t("choose_a_license")}
className="grid grid-rows-2 gap-4 md:grid-cols-2 md:grid-rows-1"
onValueChange={(value) => handleRadioChange(value as LicenseOption)}>
<RadioGroup.Item value="FREE" className="h-full">
<div
className={classNames(
"bg-default h-full cursor-pointer stack-y-2 rounded-md border p-4 hover:border-black",
value === "FREE" && "ring-2 ring-black"
)}>
<h2 className="font-cal text-emphasis text-xl">{t("agplv3_license")}</h2>
<p className="font-medium text-green-800">{t("free_license_fee")}</p>
<p className="text-subtle">{t("forever_open_and_free")}</p>
<ul className="text-subtle ml-4 list-disc text-left text-xs">
<li>{t("required_to_keep_your_code_open_source")}</li>
<li>{t("cannot_repackage_and_resell")}</li>
<li>{t("no_enterprise_features")}</li>
</ul>
</div>
</RadioGroup.Item>
<RadioGroup.Item value="EXISTING" className="h-full">
<div
className={classNames(
"bg-default h-full cursor-pointer stack-y-2 rounded-md border p-4 hover:border-black",
value === "EXISTING" && "ring-2 ring-black"
)}>
<h2 className="font-cal text-emphasis text-xl">{t("enter_license_key")}</h2>
<p className="font-medium text-green-800">{t("enter_existing_license")}</p>
<p className="text-subtle">{t("enter_your_license_key")}</p>
<p className="text-subtle text-xs">
{t("need_a_license")}{" "}
<Link
href="https://go.cal.com/self-hosted"
target="_blank"
rel="noreferrer noopener"
className="text-blue-600 hover:underline">
{t("purchase_license")}
</Link>
</p>
</div>
</RadioGroup.Item>
</RadioGroup.Root>
{value === "EXISTING" && (
<FormProvider {...formMethods}>
<div className="bg-cal-muted stack-y-4 rounded-md px-4 py-3">
<div className="stack-y-4">
<div>
<Controller
name="licenseKey"
control={formMethods.control}
render={({ field: { onBlur, onChange, value } }) => (
<TextField
name="licenseKey"
label={t("license_key")}
className={classNames(
"group-hover:border-emphasis mb-0",
(checkLicenseLoading || (errors.licenseKey === undefined && isDirty)) && "border-r-0"
)}
placeholder="cal_live_XXXXXXXXXXX"
value={licenseKeyInput}
addOnClassname={classNames(
"hover:border-default",
errors.licenseKey === undefined && isDirty && "group-hover:border-emphasis"
)}
addOnSuffix={
checkLicenseLoading ? (
<LoaderIcon className="h-5 w-5 animate-spin" />
) : licenseValidation?.valid && licenseTouched ? (
<CheckIcon className="h-5 w-5 text-green-700" />
) : undefined
}
color={errors.licenseKey ? "warn" : ""}
onBlur={(e) => {
setLicenseTouched(true);
onBlur();
}}
onChange={(e) => {
setLicenseKeyInput(e.target.value);
onChange(e.target.value);
}}
/>
)}
/>
{errors.licenseKey && (
<p className="mt-1 text-sm text-red-600">{errors.licenseKey.message}</p>
)}
</div>
<div>
<Controller
name="signatureToken"
control={formMethods.control}
render={({ field: { onBlur, onChange, value } }) => (
<TextField
name="signatureToken"
label={t("signature_token_optional")}
placeholder="cal_sk_XXXXXXXXXXX"
value={value || ""}
onBlur={onBlur}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
onChange(e.target.value);
formMethods.setValue("signatureToken", e.target.value);
}}
/>
)}
/>
<p className="text-subtle mt-1 text-sm">{t("signature_token_description")}</p>
</div>
</div>
</div>
</FormProvider>
)}
<div className="flex justify-end gap-2">
<Button type="button" color="secondary" onClick={onPrevStep}>
{t("prev_step")}
</Button>
{value === "EXISTING" ? (
<Button
type="submit"
color="primary"
loading={checkLicenseLoading || mutation.isPending}
disabled={
value === "EXISTING" &&
(!formMethods.formState.isValid || checkLicenseLoading || mutation.isPending)
}>
{t("save_license_key")}
</Button>
) : (
<Button color="primary" onClick={onNextStep} type="button">
{t("next_step")}
</Button>
)}
</div>
</form>
);
};
export default LicenseSelection;
+31 -19
View File
@@ -1,18 +1,32 @@
import Link from "next/link";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import type { TeamWithMembers } from "@calcom/features/ee/teams/lib/queries";
import type { UserProfile } from "@calcom/types/UserProfile";
import { UserAvatar } from "@calcom/ui/components/avatar";
import Link from "next/link";
type TeamWithMembers = {
id: number;
name: string;
slug: string | null;
logoUrl?: string | null;
bio?: string | null;
members: {
id: number;
name: string | null;
bio?: string | null;
username?: string | null;
avatar?: string | null;
}[];
};
type TeamType = Omit<NonNullable<TeamWithMembers>, "inviteToken">;
type MembersType = TeamType["members"];
type MemberType = Pick<
MembersType[number],
"id" | "name" | "bio" | "username" | "organizationId" | "avatarUrl"
> & {
type MemberType = Pick<MembersType[number], "id" | "name" | "bio"> & {
username: string | null;
organizationId?: number | null;
avatarUrl: string | null;
} & {
profile: Omit<UserProfile, "upId">;
safeBio: string | null;
bookerUrl: string;
@@ -30,20 +44,18 @@ const Member = ({ member, teamName }: { member: MemberType; teamName: string | n
<Link
key={member.id}
href={{ pathname: `${member.bookerUrl}/${member.username}`, query: queryParamsToForward }}>
<div className="bg-default hover:bg-cal-muted border-subtle group flex min-h-full flex-col stack-y-2 rounded-md border p-4 transition hover:cursor-pointer sm:w-80">
<div className="group stack-y-2 flex min-h-full flex-col rounded-md border border-subtle bg-default p-4 transition hover:cursor-pointer hover:bg-cal-muted sm:w-80">
<UserAvatar noOrganizationIndicator size="md" user={member} />
<section className="mt-2 line-clamp-4 w-full stack-y-1">
<p className="text-default font-medium">{member.name}</p>
<div className="text-subtle line-clamp-3 text-ellipsis text-sm font-normal">
<section className="stack-y-1 mt-2 line-clamp-4 w-full">
<p className="font-medium text-default">{member.name}</p>
<div className="line-clamp-3 text-ellipsis font-normal text-sm text-subtle">
{!isBioEmpty ? (
<>
<div
className=" text-subtle wrap-break-word text-sm [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
// eslint-disable-next-line react/no-danger
// biome-ignore lint/security/noDangerouslySetInnerHtml: Content is sanitized via markdownToSafeHTML
dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(member.bio) }}
/>
</>
<div
className="wrap-break-word text-sm text-subtle [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
// eslint-disable-next-line react/no-danger
// biome-ignore lint/security/noDangerouslySetInnerHtml: Content is sanitized via markdownToSafeHTML
dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(member.bio ?? null) }}
/>
) : (
t("user_from_team", { user: member.name, team: teamName })
)}
@@ -1,17 +1,13 @@
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import { useState } from "react";
import type { RefCallback, ReactNode } from "react";
import { Controller, useForm } from "react-hook-form";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { WEBSITE_URL, IS_SELF_HOSTED } from "@calcom/lib/constants";
import { IS_SELF_HOSTED, WEBSITE_URL } from "@calcom/lib/constants";
import { trpc } from "@calcom/trpc/react";
import type { AppRouter } from "@calcom/trpc/types/server/routers/_app";
import useRouterQuery from "@lib/hooks/useRouterQuery";
import type { TRPCClientErrorLike } from "@trpc/client";
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import type { ReactNode, RefCallback } from "react";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
interface UsernameAvailabilityFieldProps {
onSuccessMutation?: () => void;
@@ -64,10 +60,10 @@ export const UsernameAvailabilityField = ({
},
});
const orgBranding = useOrgBranding();
const orgBranding = null;
const usernamePrefix = orgBranding
? orgBranding?.fullDomain.replace(/^(https?:|)\/\//, "")
? "".replace(/^(https?:|)\/\//, "")
: `${WEBSITE_URL?.replace(/^(https?:|)\/\//, "")}`;
const isPremium = !IS_SELF_HOSTED && !user.organization?.id;