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

* mv PaymentPage to web

* mv 2 more components to web

* refactor

* update imports

* mv

* revert

* fix

* fix

* update

* migrate relevant test too

* move setup components to web from appstore

* move wipemycalother

* mv

* fix typechecks

* mv more routing forms components

* fix

* fix

* fix

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

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

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

* delete

* refactors

* fix

* fix

* fix

* remove usage of trpc client from OmniInstallAppButton.tsx

* fix test

* import only type

* fix test

* remove trpc package from appstore package.json

* remove remaining trpc usage

* update test

* fix type checks

* fix errors

* fix

* make it error

* nit

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2025-09-14 12:51:05 +00:00
1 parent 06fcea4116
commit 76bba1ca05
99 files changed
+728 -634

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
import dynamic from "next/dynamic";
import { DynamicComponent } from "@calcom/app-store/_components/DynamicComponent";
export const AppSetupMap = {
alby: dynamic(() => import("@calcom/web/components/apps/alby/Setup")),
"apple-calendar": dynamic(() => import("@calcom/web/components/apps/applecalendar/Setup")),
exchange: dynamic(() => import("@calcom/web/components/apps/exchangecalendar/Setup")),
"exchange2013-calendar": dynamic(() => import("@calcom/web/components/apps/exchange2013calendar/Setup")),
"exchange2016-calendar": dynamic(() => import("@calcom/web/components/apps/exchange2016calendar/Setup")),
"caldav-calendar": dynamic(() => import("@calcom/web/components/apps/caldavcalendar/Setup")),
"ics-feed": dynamic(() => import("@calcom/web/components/apps/ics-feedcalendar/Setup")),
zapier: dynamic(() => import("@calcom/web/components/apps/zapier/Setup")),
make: dynamic(() => import("@calcom/web/components/apps/make/Setup")),
sendgrid: dynamic(() => import("@calcom/web/components/apps/sendgrid/Setup")),
stripe: dynamic(() => import("@calcom/web/components/apps/stripepayment/Setup")),
paypal: dynamic(() => import("@calcom/web/components/apps/paypal/Setup")),
hitpay: dynamic(() => import("@calcom/web/components/apps/hitpay/Setup")),
btcpayserver: dynamic(() => import("@calcom/web/components/apps/btcpayserver/Setup")),
};
export const AppSetupPage = (props: { slug: string }) => {
return <DynamicComponent<typeof AppSetupMap> componentMap={AppSetupMap} {...props} />;
};
export default AppSetupPage;
@@ -0,0 +1,194 @@
"use client";
import Link from "next/link";
import { useEffect, useState } from "react";
import QRCode from "react-qr-code";
import z from "zod";
import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useCopy } from "@calcom/lib/hooks/useCopy";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { Button } from "@calcom/ui/components/button";
import { Spinner } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
interface IAlbyPaymentComponentProps {
payment: {
// Will be parsed on render
data: unknown;
};
paymentPageProps: PaymentPageProps;
}
// Create zod schema for data
const PaymentAlbyDataSchema = z.object({
invoice: z
.object({
paymentRequest: z.string(),
})
.required(),
});
export const AlbyPaymentComponent = (props: IAlbyPaymentComponentProps) => {
const { payment } = props;
const { data } = payment;
const [showQRCode, setShowQRCode] = useState(window.webln === undefined);
const [isPaying, setPaying] = useState(false);
const { copyToClipboard, isCopied } = useCopy();
const wrongUrl = (
<>
<p className="mt-3 text-center">Couldn&apos;t obtain payment URL</p>
</>
);
const parsedData = PaymentAlbyDataSchema.safeParse(data);
if (!parsedData.success || !parsedData.data?.invoice?.paymentRequest) {
return wrongUrl;
}
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">
<PaymentChecker {...props.paymentPageProps} />
{isPaying && <Spinner className="mt-12 h-8 w-8" />}
{!isPaying && (
<>
{!showQRCode && (
<div className="flex gap-4">
<Button color="secondary" onClick={() => setShowQRCode(true)}>
Show QR
</Button>
{window.webln && (
<Button
onClick={async () => {
try {
if (!window.webln) {
throw new Error("webln not found");
}
setPaying(true);
await window.webln.enable();
window.webln.sendPayment(paymentRequest);
} catch (error) {
setPaying(false);
alert((error as Error).message);
}
}}>
Pay Now
</Button>
)}
</div>
)}
{showQRCode && (
<>
<div className="flex items-center justify-center gap-2">
<Spinner className="h-4 w-4" />
<p className="text-xs">Waiting for payment</p>
</div>
<p className="text-sm">Click or scan the invoice below to pay</p>
<Link
href={`lightning:${paymentRequest}`}
className="inline-flex items-center justify-center rounded-2xl rounded-md border border-transparent bg-white p-2 font-medium text-black shadow-sm hover:brightness-95 focus:outline-none focus:ring-offset-2">
<QRCode size={192} value={paymentRequest} />
</Link>
<Button
size="sm"
color="secondary"
onClick={() => copyToClipboard(paymentRequest)}
className="text-subtle rounded-md"
StartIcon={isCopied ? "clipboard-check" : "clipboard"}>
Copy Invoice
</Button>
<Link target="_blank" href="https://getalby.com" className="link mt-4 text-sm underline">
Don&apos;t have a lightning wallet?
</Link>
</>
)}
</>
)}
<Link target="_blank" href="https://getalby.com">
<div className="mt-4 flex items-center text-sm">
Powered by&nbsp;
<img title="Alby" src="/app-store/alby/logo.svg" alt="Alby" className="h-8 dark:hidden" />
<img
title="Alby"
src="/app-store/alby/logo-dark.svg"
alt="Alby"
className="hidden h-8 dark:block"
/>
</div>
</Link>
</div>
);
};
type PaymentCheckerProps = PaymentPageProps;
function PaymentChecker(props: PaymentCheckerProps) {
// TODO: move booking success code to a common lib function
// TODO: subscribe rather than polling
const searchParams = useCompatSearchParams();
const bookingSuccessRedirect = useBookingSuccessRedirect();
const utils = trpc.useUtils();
const { t } = useLocale();
useEffect(() => {
if (searchParams === null) {
return;
}
// use closure to ensure non-nullability
const sp = searchParams;
const interval = setInterval(() => {
(async () => {
if (props.booking.status === "ACCEPTED") {
return;
}
const { booking: bookingResult } = await utils.viewer.bookings.find.fetch({
bookingUid: props.booking.uid,
});
if (bookingResult?.paid) {
showToast("Payment successful", "success");
const params: {
uid: string;
email: string | null;
location: string;
} = {
uid: props.booking.uid,
email: sp.get("email"),
location: t("web_conferencing_details_to_follow"),
};
bookingSuccessRedirect({
successRedirectUrl: props.eventType.successRedirectUrl,
query: params,
booking: props.booking,
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect,
});
}
})();
}, 1000);
return () => clearInterval(interval);
}, [
bookingSuccessRedirect,
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,
]);
return null;
}
+183
View File
@@ -0,0 +1,183 @@
import { auth, Client, webln } from "@getalby/sdk";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useCallback, useEffect } from "react";
import { Toaster } from "sonner";
import AppNotInstalledMessage from "@calcom/app-store/_components/AppNotInstalledMessage";
import { albyCredentialKeysSchema } from "@calcom/app-store/alby/lib/albyCredentialKeysSchema";
import type { IAlbySetupProps } from "@calcom/app-store/alby/pages/setup/_getServerSideProps";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
export default function AlbySetup(props: IAlbySetupProps) {
const params = useCompatSearchParams();
if (params?.get("callback") === "true") {
return <AlbySetupCallback />;
}
return <AlbySetupPage {...props} />;
}
function AlbySetupCallback() {
const [error, setError] = useState<string | null>(null);
const searchParams = useCompatSearchParams();
useEffect(() => {
if (!searchParams) {
return;
}
if (!window.opener) {
setError("Something went wrong. Opener not available. Please contact [email protected]");
return;
}
const code = searchParams?.get("code");
const error = searchParams?.get("error");
if (!code) {
setError("declined");
}
if (error) {
setError(error);
alert(error);
return;
}
window.opener.postMessage({
type: "alby:oauth:success",
payload: { code },
});
window.close();
}, [searchParams]);
return (
<div>
{error && <p>Authorization failed: {error}</p>}
{!error && <p>Connecting...</p>}
</div>
);
}
function AlbySetupPage(props: IAlbySetupProps) {
const router = useRouter();
const { t } = useLocale();
const integrations = trpc.viewer.apps.integrations.useQuery({ variant: "payment", appId: "alby" });
const [albyPaymentAppCredentials] = integrations.data?.items || [];
const [credentialId] = albyPaymentAppCredentials?.userCredentialIds || [-1];
const showContent = !!integrations.data && integrations.isSuccess && !!credentialId;
const saveKeysMutation = trpc.viewer.apps.updateAppCredentials.useMutation({
onSuccess: () => {
showToast(t("keys_have_been_saved"), "success");
router.push("/event-types");
},
onError: (error) => {
showToast(error.message, "error");
},
});
const connectWithAlby = useCallback(async () => {
const authClient = new auth.OAuth2User({
client_id: props.clientId,
client_secret: props.clientSecret,
callback: `${process.env.NEXT_PUBLIC_WEBAPP_URL}/apps/alby/setup?callback=true`,
scopes: ["invoices:read", "account:read"],
user_agent: "cal.com",
});
const weblnOAuthProvider = new webln.OauthWeblnProvider({
auth: authClient,
});
await weblnOAuthProvider.enable();
const client = new Client(authClient);
const accountInfo = await client.accountInformation({});
// TODO: add a way to delete the endpoint when the app is uninstalled
const webhookEndpoint = await client.createWebhookEndpoint({
filter_types: ["invoice.incoming.settled"],
url: `${process.env.NEXT_PUBLIC_WEBAPP_URL}/api/integrations/alby/webhook`,
description: "Cal.com",
});
saveKeysMutation.mutate({
credentialId,
key: albyCredentialKeysSchema.parse({
account_id: accountInfo.identifier,
account_email: accountInfo.email,
account_lightning_address: accountInfo.lightning_address,
webhook_endpoint_id: webhookEndpoint.id,
webhook_endpoint_secret: webhookEndpoint.endpoint_secret,
}),
});
}, [credentialId, props.clientId, props.clientSecret, saveKeysMutation]);
if (integrations.isPending) {
return <div className="absolute z-50 flex h-screen w-full items-center bg-gray-200" />;
}
const albyIcon = (
<>
<img className="h-12 w-12 dark:hidden" src="/api/app-store/alby/icon-borderless.svg" alt="Alby Icon" />
<img
className="hidden h-12 w-12 dark:block"
src="/api/app-store/alby/icon-borderless-dark.svg"
alt="Alby Icon"
/>
</>
);
return (
<div className="bg-default flex h-screen">
{showContent ? (
<div className="flex w-full items-center justify-center p-4">
<div className="bg-default border-subtle m-auto flex max-w-[43em] flex-col items-center justify-center gap-4 overflow-auto rounded border p-4 md:p-10">
{!props.lightningAddress ? (
<>
<p className="text-default">
Create or connect to an existing Alby account to receive lightning payments for your paid
bookings.
</p>
<button
className="font-body flex h-10 w-56 items-center justify-center gap-2 rounded-md font-bold text-black shadow transition-all hover:brightness-90 active:scale-95"
style={{
background: "linear-gradient(180deg, #FFDE6E 63.72%, #F8C455 95.24%)",
}}
type="button"
onClick={connectWithAlby}>
{albyIcon}
<span className="mr-2">Connect with Alby</span>
</button>
</>
) : (
<>
{albyIcon}
<p>Alby Connected!</p>
<Badge>Email: {props.email}</Badge>
<Badge>Lightning Address: {props.lightningAddress}</Badge>
</>
)}
{/* TODO: remove when invoices are generated using user identifier */}
<div className="mt-4 rounded bg-blue-50 p-3 text-sm text-blue-700 dark:bg-blue-950 dark:text-blue-300">
<Icon name="info" className="mb-0.5 inline-flex h-4 w-4" /> Your Alby lightning address will be
used to generate invoices. If you update your lightning address, please disconnect and setup the
Alby app again.
</div>
<Link href="/apps/alby">
<Button color="secondary">Go to App Store Listing</Button>
</Link>
</div>
</div>
) : (
<AppNotInstalledMessage appName="alby" />
)}
<Toaster position="bottom-right" />
</div>
);
}
@@ -0,0 +1,119 @@
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Toaster } from "sonner";
import { APP_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { PasswordField } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { Form } from "@calcom/ui/components/form";
export default function AppleCalendarSetup() {
const { t } = useLocale();
const router = useRouter();
const form = useForm({
defaultValues: {
username: "",
password: "",
},
});
const [errorMessage, setErrorMessage] = useState("");
return (
<div className="bg-emphasis flex h-screen dark:bg-inherit">
<div className="bg-default dark:bg-muted border-subtle m-auto rounded p-5 dark:border md:w-[560px] md:p-10">
<div className="flex flex-col space-y-5 md:flex-row md:space-x-5 md:space-y-0">
<div>
{/* eslint-disable @next/next/no-img-element */}
<img
src="/api/app-store/applecalendar/icon.svg"
alt="Apple Calendar"
className="h-12 w-12 max-w-2xl"
/>
</div>
<div>
<h1 className="text-default dark:text-emphasis mb-3 font-semibold">
{t("connect_apple_server")}
</h1>
<div className="mt-1 text-sm">
{t("apple_server_generate_password", { appName: APP_NAME })}{" "}
<a
className="font-bold hover:underline"
href="https://appleid.apple.com/account/manage"
target="_blank"
rel="noopener noreferrer">
https://appleid.apple.com/account/manage
</a>
. {t("credentials_stored_encrypted")}
</div>
<div className="my-2 mt-4">
<Form
form={form}
handleSubmit={async (values) => {
try {
setErrorMessage("");
const res = await fetch("/api/integrations/applecalendar/add", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (!res.ok) {
setErrorMessage(t(json?.message) || t("something_went_wrong"));
} else {
router.push(json.url);
}
} catch (err) {
setErrorMessage(t("unable_to_add_apple_calendar"));
}
}}>
<fieldset
className="space-y-4"
disabled={form.formState.isSubmitting}
data-testid="apple-calendar-form">
<TextField
required
type="text"
{...form.register("username")}
label="Apple ID"
placeholder="[email protected]"
data-testid="apple-calendar-email"
/>
<PasswordField
required
{...form.register("password")}
label={t("password")}
placeholder="•••••••••••••"
autoComplete="password"
data-testid="apple-calendar-password"
/>
</fieldset>
{errorMessage && <Alert severity="error" title={errorMessage} className="my-4" />}
<div className="mt-5 justify-end space-x-2 rtl:space-x-reverse sm:mt-4 sm:flex">
<Button type="button" color="secondary" onClick={() => router.back()}>
{t("cancel")}
</Button>
<Button
type="submit"
loading={form.formState.isSubmitting}
data-testid="apple-calendar-login-button">
{t("save")}
</Button>
</div>
</Form>
</div>
</div>
</div>
</div>
<Toaster position="bottom-right" />
</div>
);
}
@@ -0,0 +1,150 @@
"use client";
import { useEffect, useState } from "react";
import z from "zod";
import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useCopy } from "@calcom/lib/hooks/useCopy";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { Button } from "@calcom/ui/components/button";
import { Spinner } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
interface IPaymentComponentProps {
payment: {
// Will be parsed on render
data: unknown;
};
paymentPageProps: PaymentPageProps;
}
// Create zod schema for data
const PaymentBTCPayDataSchema = z.object({
invoice: z.object({ checkoutLink: z.string() }).required(),
});
export const BtcpayPaymentComponent = (props: IPaymentComponentProps) => {
const { payment } = props;
const { data } = payment;
const [iframeLoaded, setIframeLoaded] = useState(false);
const { copyToClipboard, isCopied } = useCopy();
const wrongUrl = (
<>
<p className="mt-3 text-center">Couldn&apos;t obtain payment URL</p>
</>
);
const parsedData = PaymentBTCPayDataSchema.safeParse(data);
if (!parsedData.success || !parsedData.data?.invoice?.checkoutLink) return wrongUrl;
const checkoutUrl = parsedData.data.invoice.checkoutLink;
const handleOpenInNewTab = () => {
window.open(checkoutUrl, "_blank", "noopener,noreferrer");
};
return (
<div className="mb-4 mt-8 flex h-full w-full flex-col items-center justify-center gap-4">
<PaymentChecker {...props.paymentPageProps} />
{!iframeLoaded && (
<div className="flex items-center justify-center">
<Spinner className="mr-2 h-5 w-5" />
<p>Loading payment page...</p>
</div>
)}
<div className={`w-full ${iframeLoaded ? "block" : "hidden"}`}>
<iframe
src={checkoutUrl}
title="BTCPay Payment"
className="h-[1000px] w-full rounded-md border-0"
onLoad={() => setIframeLoaded(true)}
/>
</div>
<div className="flex flex-row flex-wrap items-center justify-center gap-4">
<Button
size="sm"
color="secondary"
onClick={() => copyToClipboard(checkoutUrl)}
className="text-subtle rounded-md"
StartIcon={isCopied ? "clipboard-check" : "clipboard"}>
Copy Payment Link
</Button>
<Button onClick={handleOpenInNewTab}>Open in New Tab</Button>
</div>
</div>
);
};
type PaymentCheckerProps = PaymentPageProps;
function PaymentChecker(props: PaymentCheckerProps) {
// TODO: move booking success code to a common lib function
// TODO: subscribe rather than polling
const searchParams = useCompatSearchParams();
const bookingSuccessRedirect = useBookingSuccessRedirect();
const utils = trpc.useUtils();
const { t } = useLocale();
useEffect(() => {
if (searchParams === null) {
return;
}
// use closure to ensure non-nullability
const sp = searchParams;
const interval = setInterval(() => {
(async () => {
try {
if (props.booking.status === "ACCEPTED") {
return;
}
const { booking: bookingResult } = await utils.viewer.bookings.find.fetch({
bookingUid: props.booking.uid,
});
if (bookingResult?.paid) {
showToast("Payment successful", "success");
const params: {
uid: string;
email: string | null;
location: string;
} = {
uid: props.booking.uid,
email: sp.get("email"),
location: t("web_conferencing_details_to_follow"),
};
bookingSuccessRedirect({
successRedirectUrl: props.eventType.successRedirectUrl,
query: params,
booking: props.booking,
forwardParamsSuccessRedirect: props.eventType.forwardParamsSuccessRedirect,
});
}
} catch (e) {}
})();
}, 2000);
return () => clearInterval(interval);
}, [
bookingSuccessRedirect,
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,
]);
return null;
}
@@ -0,0 +1,352 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { Toaster } from "sonner";
import { z } from "zod";
import AppNotInstalledMessage from "@calcom/app-store/_components/AppNotInstalledMessage";
import KeyField from "@calcom/app-store/btcpayserver/components/KeyInput";
import { btcpayCredentialKeysSchema } from "@calcom/app-store/btcpayserver/lib/btcpayCredentialKeysSchema";
import type { IBTCPaySetupProps } from "@calcom/app-store/btcpayserver/pages/setup/_getServerSideProps";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { Button } from "@calcom/ui/components/button";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
export default function BTCPaySetup(props: IBTCPaySetupProps) {
const params = useCompatSearchParams();
if (params?.get("callback") === "true") {
return <BTCPaySetupCallback />;
}
return <BTCPaySetupPage {...props} />;
}
enum BTCPayOAuthError {
Declined = "declined",
Unknown = "unknown",
}
function BTCPaySetupCallback() {
const [error, setError] = useState<string | null>(null);
const searchParams = useCompatSearchParams();
useEffect(() => {
if (!searchParams) {
return;
}
if (!window.opener) {
setError("Something went wrong. Opener not available. Please contact support");
return;
}
const code = searchParams?.get("code");
const error = searchParams?.get("error");
if (!code) {
setError(BTCPayOAuthError.Declined);
}
if (error) {
setError(error);
return;
}
window.opener.postMessage({
type: "btcpayserver:oauth:success",
payload: { code },
});
window.close();
}, [searchParams]);
return (
<div>
{error && <p>Authorization failed: {error}</p>}
{!error && <p>Connecting...</p>}
</div>
);
}
function BTCPaySetupPage(props: IBTCPaySetupProps) {
const router = useRouter();
const { t } = useLocale();
const session = useSession();
const [loading, setLoading] = useState<boolean>(false);
const [validating, setValidating] = useState<boolean>(false);
const [updatable, setUpdatable] = useState<boolean>(false);
const [keyData, setKeyData] = useState<
| {
storeId: string;
serverUrl: string;
apiKey: string;
webhookSecret: string;
}
| undefined
>();
const settingsSchema = z.object({
storeId: z.string().trim(),
serverUrl: z.string().trim(),
apiKey: z.string().trim(),
webhookSecret: z.string().optional(),
});
const integrations = trpc.viewer.apps.integrations.useQuery({ variant: "payment", appId: "btcpayserver" });
const [btcPayPaymentAppCredentials] = integrations.data?.items || [];
const [credentialId] = btcPayPaymentAppCredentials?.userCredentialIds || [-1];
const showContent = !!integrations.data && integrations.isSuccess && !!credentialId;
const saveKeysMutation = trpc.viewer.apps.updateAppCredentials.useMutation({
onSuccess: () => {
showToast(t("keys_have_been_saved"), "success");
router.push("/event-types");
},
onError: (error) => {
showToast(error.message, "error");
},
});
const deleteMutation = trpc.viewer.credentials.delete.useMutation({
onSuccess: () => {
router.push("/apps/btcpayserver");
},
onError: () => {
showToast(t("error_removing_app"), "error");
},
});
const {
register,
handleSubmit,
formState: { errors },
watch,
reset,
} = useForm<z.infer<typeof settingsSchema>>({
reValidateMode: "onChange",
resolver: zodResolver(settingsSchema),
});
useEffect(() => {
const _keyData = {
storeId: props?.storeId || "",
serverUrl: props?.serverUrl || "",
apiKey: props?.apiKey || "",
webhookSecret: props?.webhookSecret || "",
};
setKeyData(_keyData);
}, [props]);
useEffect(() => {
const subscription = watch((value) => {
const { serverUrl, storeId, apiKey, webhookSecret } = value;
if (
serverUrl &&
storeId &&
apiKey &&
(keyData?.serverUrl !== serverUrl || keyData?.storeId !== storeId || keyData?.apiKey !== apiKey)
) {
setUpdatable(true);
} else {
setUpdatable(false);
}
});
return () => subscription.unsubscribe();
}, [watch, keyData]);
const configureBTCPayWebhook = async (data: z.infer<typeof settingsSchema>) => {
setValidating(true);
const specificEvents = ["InvoiceSettled", "InvoiceProcessing"];
const serverUrl = data.serverUrl.endsWith("/") ? data.serverUrl.slice(0, -1) : data.serverUrl;
const endpoint = `${serverUrl}/api/v1/stores/${data.storeId}/webhooks`;
const webhookUrl = `${WEBAPP_URL}/api/integrations/btcpayserver/webhook`;
const requestBody = {
enabled: true,
automaticRedelivery: false,
url: webhookUrl,
authorizedEvents: {
everything: false,
specificEvents: specificEvents,
},
secret: null,
};
try {
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `token ${data.apiKey}`,
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorBody = await response.text();
showToast(`Failed to configure webhook: ${errorBody}`, "error");
return false;
}
const webhookResponse = await response.json();
saveKeysMutation.mutate({
credentialId,
key: btcpayCredentialKeysSchema.parse({
...data,
webhookSecret: webhookResponse.secret,
}),
});
return true;
} catch (error) {
if (error instanceof Error) {
showToast(error.message || "Failed to configure BTCPay webhook", "error");
} else {
showToast("An unknown error occurred while configuring BTCPay webhook", "error");
}
return false;
} finally {
setValidating(false);
}
};
const onSubmit = handleSubmit(async (data) => {
if (loading) return;
setLoading(true);
try {
const isValid = await configureBTCPayWebhook(data);
if (!isValid) {
setLoading(false);
return;
}
} catch (error: unknown) {
let message = "";
if (error instanceof Error) {
message = error.message;
}
showToast(message, "error");
} finally {
setLoading(false);
}
});
const onCancel = () => {
deleteMutation.mutate({ id: credentialId });
};
const btcpayIcon = (
<>
<img className="h-5 w-5" src="/app-store/btcpayserver/btcpay.svg" alt="BTCPay Server Icon" />
</>
);
if (session.status === "loading") return <></>;
if (integrations.isPending) {
return <div className="absolute z-50 flex h-screen w-full items-center bg-gray-200" />;
}
const isNewCredential = !props.serverUrl && !props.storeId && !props.webhookSecret && !props.apiKey;
const webhookUri = `${WEBAPP_URL}/api/integrations/btcpayserver/webhook`;
return (
<>
<div className="bg-default flex h-screen items-center justify-center">
{showContent ? (
<div className="flex w-full w-full max-w-[43em] flex-col items-center justify-center space-y-4 p-4 lg:space-y-5">
<form className="w-full space-y-4" onSubmit={onSubmit}>
<div className="bg-default border-subtle overflow-auto rounded border">
<div className="border-subtle flex items-center justify-between border-b-[1px] p-4 md:p-5">
<h2 className="text-2xl font-semibold">BTCPay Server Information</h2>
</div>
<div className="w-full space-y-4 p-4 md:p-5">
<div className="w-full">
<KeyField
{...register("serverUrl", { required: true })}
id="serverUrl"
name="serverUrl"
containerClassName="w-full"
label="BTCPay Server Url"
autoComplete="off"
autoCorrect="off"
defaultValue={keyData?.serverUrl || ""}
/>
{errors.serverUrl && (
<p data-testid="required" className="py-2 text-xs text-red-500">
{errors.serverUrl?.message}
</p>
)}
</div>
<div className="w-full">
<KeyField
{...register("storeId", { required: true })}
id="storeId"
name="storeId"
containerClassName="w-full"
label="BTCPay Store Id"
autoComplete="off"
autoCorrect="off"
defaultValue={keyData?.storeId || ""}
/>
{errors.storeId && (
<p data-testid="required" className="py-2 text-xs text-red-500">
{errors.storeId?.message}
</p>
)}
</div>
<div className="w-full">
<KeyField
{...register("apiKey", { required: true })}
id="apiKey"
name="apiKey"
containerClassName="w-full"
label="API Key"
autoComplete="off"
autoCorrect="off"
defaultValue={keyData?.apiKey || ""}
/>
{errors.apiKey && (
<p data-testid="required" className="py-2 text-xs text-red-500">
{errors.apiKey?.message}
</p>
)}
</div>
</div>
</div>
<div className="flex justify-end gap-4">
{isNewCredential ? (
<>
<Button color="secondary" className="h-10" onClick={onCancel}>
Cancel
</Button>
<Button
className="h-10"
color="primary"
type="submit"
disabled={loading || validating || !updatable}>
{loading ? (
<>
<Icon name="loader" className="mr-2 animate-spin" />
{t("connecting")}
</>
) : (
t("connect")
)}
</Button>
</>
) : (
<>
<Link href="/apps/btcpayserver" className="inline-block">
<Button color="secondary">Go to App Store</Button>
</Link>
</>
)}
</div>
</form>
</div>
) : (
<AppNotInstalledMessage appName="btcpayserver" />
)}
<Toaster position="bottom-right" />
</div>
</>
);
}
@@ -0,0 +1,122 @@
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Toaster } from "sonner";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { Form } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
export default function CalDavCalendarSetup() {
const { t } = useLocale();
const router = useRouter();
const form = useForm({
defaultValues: {
url: "",
username: "",
password: "",
},
});
const [errorMessage, setErrorMessage] = useState("");
const [errorActionUrl, setErrorActionUrl] = useState("");
return (
<div className="bg-emphasis flex h-screen">
<div className="bg-default m-auto rounded p-5 md:w-[560px] md:p-10">
<div className="flex flex-col space-y-5 md:flex-row md:space-x-5 md:space-y-0">
<div>
{/* eslint-disable @next/next/no-img-element */}
<img
src="/api/app-store/caldavcalendar/icon.svg"
alt="CalDav Calendar"
className="h-12 w-12 max-w-2xl"
/>
</div>
<div className="flex w-10/12 flex-col">
<h1 className="text-default">{t("connect_caldav")}</h1>
<div className="mt-1 text-sm">{t("credentials_stored_encrypted")}</div>
<div className="my-2 mt-3">
<Form
form={form}
handleSubmit={async (values) => {
setErrorMessage("");
const res = await fetch("/api/integrations/caldavcalendar/add", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (!res.ok) {
setErrorMessage(json?.message || t("something_went_wrong"));
if (json.actionUrl) {
setErrorActionUrl(json.actionUrl);
}
} else {
router.push(json.url);
}
}}>
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
<TextField
required
type="text"
{...form.register("url")}
label={t("calendar_url")}
placeholder="https://example.com/calendar"
/>
<TextField
required
type="text"
{...form.register("username")}
label={t("username")}
placeholder="rickroll"
/>
<TextField
required
type="password"
{...form.register("password")}
label={t("password")}
placeholder="•••••••••••••"
autoComplete="password"
/>
</fieldset>
{errorMessage && (
<Alert
severity="error"
title={errorMessage}
actions={
errorActionUrl !== "" ? (
<Button
href={errorActionUrl}
color="secondary"
target="_blank"
className="ml-5 w-32 !p-5">
Go to Admin
</Button>
) : undefined
}
className="my-4"
/>
)}
<div className="mt-5 justify-end space-x-2 rtl:space-x-reverse sm:mt-4 sm:flex">
<Button type="button" color="secondary" onClick={() => router.back()}>
{t("cancel")}
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
{t("save")}
</Button>
</div>
</Form>
</div>
</div>
</div>
</div>
<Toaster position="bottom-right" />
</div>
);
}
@@ -0,0 +1,98 @@
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Toaster } from "sonner";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { Form } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
export default function Exchange2013CalendarSetup() {
const { t } = useLocale();
const router = useRouter();
const form = useForm({
defaultValues: {
username: "",
password: "",
url: process.env.EXCHANGE_DEFAULT_EWS_URL || "",
},
});
const [errorMessage, setErrorMessage] = useState("");
return (
<div className="bg-emphasis flex h-screen">
<div className="bg-default m-auto rounded p-5 md:w-[560px] md:p-10">
<div>
<img
src="/api/app-store/exchange2013calendar/icon.svg"
alt="Exchange 2013 Calendar"
className="h-12 w-12 max-w-2xl"
/>
</div>
<div className="flex w-10/12 flex-col">
<h1 className="text-default">{t("add_exchange2013")}</h1>
<div className="mt-1 text-sm">{t("credentials_stored_encrypted")}</div>
<div className="my-2 mt-3">
<Form
form={form}
handleSubmit={async (values) => {
setErrorMessage("");
const res = await fetch("/api/integrations/exchange2013calendar/add", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (!res.ok) {
setErrorMessage(json?.message || t("something_went_wrong"));
} else {
router.push(json.url);
}
}}>
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
<TextField
required
type="text"
{...form.register("url")}
label={t("calendar_url")}
placeholder="https://example.com/Ews/Exchange.asmx"
/>
<TextField
required
type="text"
{...form.register("username")}
label="E-Mail"
placeholder="[email protected]"
/>
<TextField
required
type="password"
{...form.register("password")}
label="Password"
placeholder="•••••••••••••"
autoComplete="password"
/>
</fieldset>
{errorMessage && <Alert severity="error" title={errorMessage} className="my-4" />}
<div className="mt-5 justify-end space-x-2 rtl:space-x-reverse sm:mt-4 sm:flex">
<Button type="button" color="secondary" onClick={() => router.back()}>
{t("cancel")}
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
{t("save")}
</Button>
</div>
</Form>
</div>
</div>
</div>
<Toaster position="bottom-right" />
</div>
);
}
@@ -0,0 +1,98 @@
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Toaster } from "sonner";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { Form } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
export default function Exchange2016CalendarSetup() {
const { t } = useLocale();
const router = useRouter();
const form = useForm({
defaultValues: {
username: "",
password: "",
url: process.env.EXCHANGE_DEFAULT_EWS_URL || "",
},
});
const [errorMessage, setErrorMessage] = useState("");
return (
<div className="bg-emphasis flex h-screen">
<div className="bg-default m-auto rounded p-5 md:w-[560px] md:p-10">
<div>
<img
src="/api/app-store/exchange2016calendar/icon.svg"
alt="Exchange 2016 Calendar"
className="h-12 w-12 max-w-2xl"
/>
</div>
<div className="flex w-10/12 flex-col">
<h1 className="text-default">{t("add_exchange2016")}</h1>
<div className="mt-1 text-sm">{t("credentials_stored_encrypted")}</div>
<div className="my-2 mt-3">
<Form
form={form}
handleSubmit={async (values) => {
setErrorMessage("");
const res = await fetch("/api/integrations/exchange2016calendar/add", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (!res.ok) {
setErrorMessage(json?.message || t("something_went_wrong"));
} else {
router.push(json.url);
}
}}>
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
<TextField
required
type="text"
{...form.register("url")}
label={t("calendar_url")}
placeholder="https://example.com/Ews/Exchange.asmx"
/>
<TextField
required
type="text"
{...form.register("username")}
label="E-Mail"
placeholder="[email protected]"
/>
<TextField
required
type="password"
{...form.register("password")}
label="Password"
placeholder="•••••••••••••"
autoComplete="password"
/>
</fieldset>
{errorMessage && <Alert severity="error" title={errorMessage} className="my-4" />}
<div className="mt-5 justify-end space-x-2 rtl:space-x-reverse sm:mt-4 sm:flex">
<Button type="button" color="secondary" onClick={() => router.back()}>
{t("cancel")}
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
{t("save")}
</Button>
</div>
</Form>
</div>
</div>
</div>
<Toaster position="bottom-right" />
</div>
);
}
@@ -0,0 +1,187 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { Toaster } from "sonner";
import z from "zod";
import { ExchangeAuthentication, ExchangeVersion } from "@calcom/app-store/exchangecalendar/enums";
import { emailSchema } from "@calcom/lib/emailSchema";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { EmailField } from "@calcom/ui/components/form";
import { Form } from "@calcom/ui/components/form";
import { PasswordField } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { SelectField } from "@calcom/ui/components/form";
interface IFormData {
url: string;
username: string;
password: string;
authenticationMethod: ExchangeAuthentication;
exchangeVersion: ExchangeVersion;
useCompression: boolean;
}
const schema = z
.object({
url: z.string().url(),
username: emailSchema,
password: z.string(),
authenticationMethod: z.number().default(ExchangeAuthentication.STANDARD),
exchangeVersion: z.number().default(ExchangeVersion.Exchange2016),
useCompression: z.boolean().default(false),
})
.strict();
export default function ExchangeSetup() {
const { t } = useLocale();
const router = useRouter();
const [errorMessage, setErrorMessage] = useState("");
const form = useForm<IFormData>({
defaultValues: {
authenticationMethod: ExchangeAuthentication.NTLM,
exchangeVersion: ExchangeVersion.Exchange2016,
},
resolver: zodResolver(schema),
});
const authenticationMethod = form.watch("authenticationMethod");
const authenticationMethods = [
{ value: ExchangeAuthentication.STANDARD, label: t("exchange_authentication_standard") },
{ value: ExchangeAuthentication.NTLM, label: t("exchange_authentication_ntlm") },
];
const exchangeVersions = [
{ value: ExchangeVersion.Exchange2007_SP1, label: t("exchange_version_2007_SP1") },
{ value: ExchangeVersion.Exchange2010, label: t("exchange_version_2010") },
{ value: ExchangeVersion.Exchange2010_SP1, label: t("exchange_version_2010_SP1") },
{ value: ExchangeVersion.Exchange2010_SP2, label: t("exchange_version_2010_SP2") },
{ value: ExchangeVersion.Exchange2013, label: t("exchange_version_2013") },
{ value: ExchangeVersion.Exchange2013_SP1, label: t("exchange_version_2013_SP1") },
{ value: ExchangeVersion.Exchange2015, label: t("exchange_version_2015") },
{ value: ExchangeVersion.Exchange2016, label: t("exchange_version_2016") },
];
return (
<>
<div className="bg-emphasis flex h-screen">
<div className="bg-default m-auto rounded p-5 md:w-[560px] md:p-10">
<div className="flex flex-col space-y-5 md:flex-row md:space-x-5 md:space-y-0">
<div>
{/* eslint-disable @next/next/no-img-element */}
<img
src="/api/app-store/exchangecalendar/icon.svg"
alt="Microsoft Exchange"
className="h-12 w-12 max-w-2xl"
/>
</div>
<div className="grow">
<h1 className="text-default">{t("exchange_add")}</h1>
<div className="text-sm">{t("credentials_stored_encrypted")}</div>
<div className="my-2 mt-5">
<Form
form={form}
handleSubmit={async (values) => {
setErrorMessage("");
const res = await fetch("/api/integrations/exchangecalendar/add", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (!res.ok) {
setErrorMessage(json?.message || t("something_went_wrong"));
} else {
router.push(json.url);
}
}}>
<fieldset className="space-y-4" disabled={form.formState.isSubmitting}>
<TextField
required
type="url"
{...form.register("url")}
label={t("url")}
placeholder="https://example.com/Ews/Exchange.asmx"
inputMode="url"
/>
<EmailField
required
{...form.register("username")}
label={t("email_address")}
placeholder="[email protected]"
/>
<PasswordField
required
{...form.register("password")}
label={t("password")}
autoComplete="password"
/>
<Controller
name="authenticationMethod"
control={form.control}
render={({ field: { onChange } }) => {
const ntlmAuthenticationMethod = authenticationMethods.find(
(method) => method.value === ExchangeAuthentication.NTLM
);
return (
<SelectField
label={t("exchange_authentication")}
options={authenticationMethods}
defaultValue={ntlmAuthenticationMethod}
onChange={(authentication) => {
if (authentication) {
onChange(authentication.value);
form.setValue("authenticationMethod", authentication.value);
}
}}
/>
);
}}
/>
{authenticationMethod === ExchangeAuthentication.STANDARD ? (
<Controller
name="exchangeVersion"
control={form.control}
render={({ field: { onChange } }) => {
const exchangeVersion2016 = exchangeVersions.find(
(exchangeVersion) => exchangeVersion.value === ExchangeVersion.Exchange2016
);
return (
<SelectField
label={t("exchange_version")}
options={exchangeVersions}
defaultValue={exchangeVersion2016}
onChange={(version) => {
onChange(version?.value);
if (version) {
form.setValue("exchangeVersion", version.value);
}
}}
/>
);
}}
/>
) : null}
</fieldset>
{errorMessage && <Alert severity="error" title={errorMessage} className="my-4" />}
<div className="mt-4 flex justify-end space-x-2 rtl:space-x-reverse">
<Button type="button" color="secondary" onClick={() => router.back()}>
{t("cancel")}
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
{t("save")}
</Button>
</div>
</Form>
</div>
</div>
</div>
</div>
<Toaster position="bottom-right" />
</div>
</>
);
}
@@ -0,0 +1,103 @@
"use client";
import { useRouter } from "next/navigation";
import qs from "qs";
import { useEffect, useRef } from "react";
import { z } from "zod";
import { useHitPayDropIn } from "@calcom/app-store/hitpay/components/HitPayDropIn";
const PaymentHitpayDataSchema = z.object({
id: z.string(),
url: z.string(),
defaultLink: z.string(),
eventTypeSlug: z.string(),
bookingUid: z.string(),
email: z.string(),
bookingUserName: z.string(),
});
interface IPaymentComponentProps {
payment: {
data: unknown;
};
}
export const HitpayPaymentComponent = (props: IPaymentComponentProps) => {
const { isInitialized, init } = useHitPayDropIn();
const isSucceeded = useRef<boolean>(false);
const router = useRouter();
const { payment } = props;
const { data } = payment;
const wrongUrl = (
<>
<p className="mt-3 text-center">Couldn&apos;t obtain payment URL</p>
</>
);
const parsedData = PaymentHitpayDataSchema.safeParse(data);
useEffect(() => {
if (parsedData.success) {
if (window.self !== window.top && window.top) {
if (!isInitialized) {
const subUrl = parsedData.data.url.substring("https://securecheckout.".length);
const arr = subUrl.split("/");
const domain = arr[0];
init(
parsedData.data.defaultLink || "",
{
domain,
},
{
paymentRequest: parsedData.data.id,
},
{
onClose: onClose,
onSuccess: onSuccess,
onError: onError,
}
);
}
} else {
router.replace(parsedData.data.url);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onSuccess = () => {
isSucceeded.current = true;
};
const onClose = () => {
if (isSucceeded.current) {
if (parsedData.success) {
const queryParams = {
"flag.coep": false,
isSuccessBookingPage: true,
email: parsedData.data.email,
eventTypeSlug: parsedData.data.eventTypeSlug,
};
const query = qs.stringify(queryParams);
const url = `/booking/${parsedData.data.bookingUid}?${query}`;
router.replace(url);
}
}
};
const onError = (error: unknown) => {
if (parsedData.success) {
const url = `/${parsedData.data.bookingUserName}/${parsedData.data.eventTypeSlug}`;
router.replace(url);
}
};
if (!parsedData.success || !parsedData.data?.url) {
return wrongUrl;
}
return <div />;
};
+302
View File
@@ -0,0 +1,302 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { Toaster } from "sonner";
import { z } from "zod";
import AppNotInstalledMessage from "@calcom/app-store/_components/AppNotInstalledMessage";
import KeyField from "@calcom/app-store/hitpay/components/KeyInput";
import { hitpayCredentialKeysSchema } from "@calcom/app-store/hitpay/lib/hitpayCredentialKeysSchema";
import type { IHitPaySetupProps } from "@calcom/app-store/hitpay/pages/setup/_getServerSideProps";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { Button } from "@calcom/ui/components/button";
import { Switch } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
export default function HitPaySetup(props: IHitPaySetupProps) {
const params = useCompatSearchParams();
if (params?.get("callback") === "true") {
return <HitPaySetupCallback />;
}
return <HitPaySetupPage {...props} />;
}
function HitPaySetupCallback() {
const [error, setError] = useState<string | null>(null);
const searchParams = useCompatSearchParams();
useEffect(() => {
if (!searchParams) {
return;
}
if (!window.opener) {
setError("Something went wrong. Opener not available. Please contact [email protected]");
return;
}
const code = searchParams?.get("code");
const error = searchParams?.get("error");
if (!code) {
setError("declined");
}
if (error) {
setError(error);
return;
}
window.opener.postMessage({
type: "hitpay:oauth:success",
payload: { code },
});
window.close();
}, [searchParams]);
return (
<div>
{error && <p>Authorization failed: {error}</p>}
{!error && <p>Connecting...</p>}
</div>
);
}
function HitPaySetupPage(props: IHitPaySetupProps) {
const [loading, setLoading] = useState<boolean>(false);
const [updatable, setUpdatable] = useState<boolean>(false);
const [isSandbox, SetIsSandbox] = useState<boolean>(props.isSandbox || false);
const [keyData, setKeyData] = useState<
| {
apiKey: string;
saltKey: string;
}
| undefined
>();
const session = useSession();
const router = useRouter();
const { t } = useLocale();
const settingsSchema = z.object({
apiKey: z
.string()
.trim()
.min(64)
.max(128, {
message: t("max_limit_allowed_hint", { limit: 128 }),
}),
saltKey: z
.string()
.trim()
.min(64)
.max(128, {
message: t("max_limit_allowed_hint", { limit: 128 }),
}),
});
const integrations = trpc.viewer.apps.integrations.useQuery({ variant: "payment", appId: "hitpay" });
const [HitPayPaymentAppCredentials] = integrations.data?.items || [];
const [credentialId] = HitPayPaymentAppCredentials?.userCredentialIds || [-1];
const showContent = !!integrations.data && integrations.isSuccess && !!credentialId;
const saveKeysMutation = trpc.viewer.apps.updateAppCredentials.useMutation({
onSuccess: () => {
showToast(t("keys_have_been_saved"), "success");
router.push("/event-types");
},
onError: (error) => {
showToast(error.message, "error");
},
});
const deleteMutation = trpc.viewer.credentials.delete.useMutation({
onSuccess: () => {
router.push("/apps/hitpay");
},
onError: () => {
showToast(t("error_removing_app"), "error");
},
});
const {
register,
handleSubmit,
formState: { errors },
watch,
reset,
} = useForm<z.infer<typeof settingsSchema>>({
reValidateMode: "onChange",
resolver: zodResolver(settingsSchema),
});
useEffect(() => {
const keyObj = isSandbox ? props.sandbox : props.prod;
const _keyData = {
apiKey: keyObj?.apiKey || "",
saltKey: keyObj?.saltKey || "",
};
reset(_keyData);
setKeyData(_keyData);
}, [isSandbox]);
useEffect(() => {
const subscription = watch((value) => {
const { apiKey, saltKey } = value;
if (apiKey && saltKey && (keyData?.apiKey !== apiKey || keyData?.saltKey !== saltKey)) {
setUpdatable(true);
} else {
setUpdatable(false);
}
});
return () => subscription.unsubscribe();
}, [watch, keyData]);
const onSubmit = handleSubmit(async (data) => {
if (loading) return;
setLoading(true);
try {
const keyParams = {
isSandbox,
prod: isSandbox ? props.prod : data,
sandbox: isSandbox ? data : props.sandbox,
};
saveKeysMutation.mutate({
credentialId,
key: hitpayCredentialKeysSchema.parse(keyParams),
});
} catch (error: unknown) {
let message = "";
if (error instanceof Error) {
message = error.message;
}
showToast(message, "error");
} finally {
setLoading(false);
}
});
const onCancel = () => {
deleteMutation.mutate({ id: credentialId });
};
const hitpayIcon = (
<>
<img className="h-5 w-5" src="/app-store/hitpay/icon.svg" alt="HitPay Icon" />
</>
);
if (session.status === "loading") return <></>;
if (integrations.isPending) {
return <div className="absolute z-50 flex h-screen w-full items-center bg-gray-200" />;
}
return (
<>
<div className="bg-default flex h-screen items-center justify-center">
{showContent ? (
<div className="flex w-full w-full max-w-[43em] flex-col items-center justify-center space-y-4 p-4 lg:space-y-5">
<div className="rounded bg-blue-50 p-3 text-sm text-blue-700 dark:bg-blue-950 dark:text-blue-300">
<Icon name="info" className="mb-0.5 inline-flex h-4 w-4" /> Create or connect to an existing
HitPay account to receive payments for your paid bookings.
</div>
<form className="w-full space-y-4" onSubmit={onSubmit}>
<div className="bg-default border-subtle overflow-auto rounded border">
<div className="border-subtle flex items-center justify-between border-b-[1px] p-4 md:p-5">
<h2 className="text-2xl font-semibold">Account Information</h2>
<div className="ml-auto flex items-center">
<Switch
onCheckedChange={(value) => SetIsSandbox(value as boolean)}
checked={isSandbox}
label="Sandbox"
/>
</div>
</div>
<div className="w-full space-y-4 p-4 md:p-5">
<div className="w-full">
<KeyField
{...register("apiKey", {
required: true,
})}
id="apiKey"
name="apiKey"
containerClassName="w-full"
label={t("api_key")}
autoComplete="off"
autoCorrect="off"
defaultValue={keyData?.apiKey || ""}
/>
{errors.apiKey && (
<p data-testid="required" className="py-2 text-xs text-red-500">
{errors.apiKey?.message}
</p>
)}
</div>
<div className="w-full">
<KeyField
{...register("saltKey", {
required: true,
})}
id="saltKey"
name="saltKey"
containerClassName="w-full"
label="Salt"
autoComplete="off"
autoCorrect="off"
defaultValue={keyData?.saltKey || ""}
/>
{errors.saltKey && (
<p data-testid="required" className="py-2 text-xs text-red-500">
{errors.saltKey?.message}
</p>
)}
</div>
</div>
</div>
{!props.prod && !props.sandbox ? (
<div className="flex justify-end gap-4">
<Button color="secondary" className="h-10 text-base" onClick={onCancel}>
Cancel
</Button>
<button
className="font-body flex h-10 w-56 items-center justify-center gap-2 rounded-md font-bold text-black shadow transition-all hover:brightness-90 active:scale-95"
style={{
background: "linear-gradient(180deg, #FFDE6E 63.72%, #F8C455 95.24%)",
}}
type="submit"
disabled={loading}>
{hitpayIcon}
<span className="mr-2">Connect with HitPay</span>
</button>
</div>
) : (
<div className="flex justify-end gap-4">
<Link href="/apps/hitpay" className="inline-block">
<Button color="secondary">Go to App Store</Button>
</Link>
<Button color="primary" type="submit" disabled={!updatable}>
Update
</Button>
</div>
)}
</form>
</div>
) : (
<AppNotInstalledMessage appName="hitpay" />
)}
<Toaster position="bottom-right" />
</div>
</>
);
}
@@ -0,0 +1,131 @@
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Toaster } from "sonner";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
import { Button } from "@calcom/ui/components/button";
import { Form } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
export default function ICSFeedSetup() {
const { t } = useLocale();
const router = useRouter();
const form = useForm({
defaultValues: {},
});
const [urls, setUrls] = useState<string[]>([""]);
const [errorMessage, setErrorMessage] = useState("");
const [errorActionUrl, setErrorActionUrl] = useState("");
return (
<div className="bg-emphasis flex h-screen">
<div className="bg-default m-auto rounded p-5 md:w-[560px] md:p-10">
<div className="flex flex-col space-y-5 md:flex-row md:space-x-5 md:space-y-0">
<div>
{/* eslint-disable @next/next/no-img-element */}
<img
src="/api/app-store/ics-feedcalendar/icon.svg"
alt="ICS Feed"
className="h-12 w-12 max-w-2xl"
/>
</div>
<div className="flex w-10/12 flex-col">
<h1 className="text-default">{t("connect_ics_feed")}</h1>
<div className="mt-1 text-sm">{t("credentials_stored_encrypted")}</div>
<div className="my-2 mt-3">
<Form
form={form}
handleSubmit={async (_) => {
setErrorMessage("");
const res = await fetch("/api/integrations/ics-feedcalendar/add", {
method: "POST",
body: JSON.stringify({ urls }),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (!res.ok) {
setErrorMessage(json?.message || t("something_went_wrong"));
if (json.actionUrl) {
setErrorActionUrl(json.actionUrl);
}
} else {
router.push(json.url);
}
}}>
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
{urls.map((url, i) => (
<div key={i} className="flex w-full items-center gap-2">
<TextField
required
type="text"
label={t("calendar_url")}
value={url}
containerClassName={`w-full ${i === 0 ? "mr-6" : ""}`}
onChange={(e) => {
const newVal = e.target.value as string;
setUrls((urls) => urls.map((x, ii) => (ii === i ? newVal : x)));
}}
placeholder="https://example.com/calendar.ics"
/>
{i !== 0 ? (
<button
type="button"
className="mb-2 h-min text-sm"
onClick={() => setUrls((urls) => urls.filter((_, ii) => i !== ii))}>
<Icon name="trash" size={16} />
</button>
) : null}
</div>
))}
</fieldset>
<button
className="text-sm"
type="button"
onClick={() => {
setUrls((urls) => urls.concat(""));
}}>
{t("add")} <Icon className="inline" name="plus" size={16} />
</button>
{errorMessage && (
<Alert
severity="error"
title={errorMessage}
actions={
errorActionUrl !== "" ? (
<Button
href={errorActionUrl}
color="secondary"
target="_blank"
className="ml-5 w-32 !p-5">
Go to Admin
</Button>
) : undefined
}
className="my-4"
/>
)}
<div className="mt-5 justify-end space-x-2 rtl:space-x-reverse sm:mt-4 sm:flex">
<Button type="button" color="secondary" onClick={() => router.back()}>
{t("cancel")}
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
{t("save")}
</Button>
</div>
</Form>
</div>
</div>
</div>
</div>
<Toaster position="bottom-right" />
</div>
);
}
+175
View File
@@ -0,0 +1,175 @@
import type { InferGetServerSidePropsType } from "next";
import Link from "next/link";
import { useState } from "react";
import { Toaster } from "sonner";
import AppNotInstalledMessage from "@calcom/app-store/_components/AppNotInstalledMessage";
import type { getServerSideProps } from "@calcom/app-store/make/pages/setup/_getServerSideProps";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
const MAKE = "make";
export default function MakeSetup({ inviteLink }: InferGetServerSidePropsType<typeof getServerSideProps>) {
const [newApiKeys, setNewApiKeys] = useState<Record<string, string>>({});
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 makeCredentials: { userCredentialIds: number[] } | undefined = integrations.data?.items.find(
(item: { type: string }) => item.type === "make_automation"
);
const [credentialId] = makeCredentials?.userCredentialIds || [false];
const showContent = integrations.data && integrations.isSuccess && credentialId;
async function createApiKey(teamId?: number) {
const event = { note: "Make", expiresAt: null, appId: MAKE, teamId };
const apiKey = await utils.client.viewer.apiKeys.create.mutate(event);
if (oldApiKey.data) {
const oldKey = teamId
? oldApiKey.data.find((key) => key.teamId === teamId)
: oldApiKey.data.find((key) => !key.teamId);
if (oldKey) {
deleteApiKey.mutate({
id: oldKey.id,
});
}
}
return apiKey;
}
async function generateApiKey(teamId?: number) {
const apiKey = await createApiKey(teamId);
setNewApiKeys({ ...newApiKeys, [teamId || ""]: apiKey });
}
if (integrations.isPending) {
return <div className="bg-emphasis absolute z-50 flex h-screen w-full items-center" />;
}
return (
<div className="bg-emphasis flex h-screen">
{showContent ? (
<div className="bg-default m-auto max-w-[43em] overflow-auto rounded pb-10 md:p-10">
<div className="md:flex md:flex-row">
<div className="invisible md:visible">
<img className="h-11" src="/api/app-store/make/icon.svg" alt="Make Logo" />
</div>
<div className="ml-2 ltr:mr-2 rtl:ml-2 md:ml-5">
<div className="text-default">{t("setting_up_make")}</div>
<>
<div className="mt-1 text-xl">{t("generate_api_key")}:</div>
{!teams ? (
<Button color="secondary" onClick={() => createApiKey()} className="mb-4 mt-2">
{t("generate_api_key")}
</Button>
) : (
<>
<div className="mt-8 text-sm font-semibold">Your event types:</div>
{!newApiKeys[""] ? (
<Button color="secondary" onClick={() => generateApiKey()} className="mb-4 mt-2">
{t("generate_api_key")}
</Button>
) : (
<CopyApiKey apiKey={newApiKeys[""]} />
)}
{teams.map((team) => {
return (
<div key={team.name}>
<div className="mt-2 text-sm font-semibold">{team.name}:</div>
{!newApiKeys[team.id] ? (
<Button
color="secondary"
onClick={() => generateApiKey(team.id)}
className="mb-4 mt-2">
{t("generate_api_key")}
</Button>
) : (
<CopyApiKey apiKey={newApiKeys[team.id]} />
)}
</div>
);
})}
</>
)}
</>
<ol className="mb-5 ml-5 mt-5 list-decimal ltr:mr-5 rtl:ml-5">
<li>
<ServerTrans
t={t}
i18nKey="make_setup_instructions_1"
components={[
<a
key="make-invite-link"
href={inviteLink}
className="ml-1 mr-1 text-orange-600 underline">
Make Invite Link
</a>,
]}
/>
</li>
<li>{t("make_setup_instructions_2")}</li>
<li>{t("make_setup_instructions_3")}</li>
<li>{t("make_setup_instructions_4")}</li>
<li>{t("make_setup_instructions_5")}</li>
<li>{t("make_setup_instructions_6")}</li>
</ol>
<Link href="/apps/installed/automation?hl=make" passHref={true} legacyBehavior>
<Button color="secondary">{t("done")}</Button>
</Link>
</div>
</div>
</div>
) : (
<AppNotInstalledMessage appName="make" />
)}
<Toaster position="bottom-right" />
</div>
);
}
const CopyApiKey = ({ apiKey }: { apiKey: string }) => {
const { t } = useLocale();
return (
<div>
<div className="my-2 mt-3 flex-wrap sm:flex sm:flex-nowrap">
<code className="bg-subtle h-full w-full whitespace-pre-wrap rounded-md py-[6px] pl-2 pr-2 sm:rounded-r-none sm:pr-5">
{apiKey}
</code>
<Tooltip side="top" content={t("copy_to_clipboard")}>
<Button
onClick={() => {
navigator.clipboard.writeText(apiKey);
showToast(t("api_key_copied"), "success");
}}
type="button"
className="mt-4 text-base sm:mt-0 sm:rounded-l-none">
<Icon name="clipboard" className="h-4 w-4 ltr:mr-2 rtl:ml-2" />
{t("copy")}
</Button>
</Tooltip>
</div>
<div className="text-subtle mb-5 mt-2 text-sm">{t("copy_somewhere_safe")}</div>
</div>
);
};
@@ -0,0 +1,62 @@
"use client";
import Link from "next/link";
import z from "zod";
interface IPaypalPaymentComponentProps {
payment: {
// Will be parsed on render
data: unknown;
};
}
// Create zod schema for data
const PaymentPaypalDataSchema = z.object({
order: z
.object({
id: z.string(),
status: z.string(),
links: z.array(
z.object({
href: z.string(),
rel: z.string(),
method: z.string(),
})
),
})
.optional(),
capture: z.object({}).optional(),
});
export const PaypalPaymentComponent = (props: IPaypalPaymentComponentProps) => {
const { payment } = props;
const { data } = payment;
const wrongUrl = (
<>
<p className="mt-3 text-center">Couldn&apos;t obtain payment URL</p>
</>
);
const parsedData = PaymentPaypalDataSchema.safeParse(data);
if (!parsedData.success || !parsedData.data?.order?.links) {
return wrongUrl;
}
const paymentUrl = parsedData.data.order.links.find(
(link) => link.rel === "approve" || link.rel === "payer-action"
)?.href;
if (!paymentUrl) {
return wrongUrl;
}
return (
<div className="mt-4 flex h-full w-full flex-col items-center justify-center">
<Link
href={`${paymentUrl}`}
className="inline-flex items-center justify-center rounded-2xl rounded-md border border-transparent bg-[#ffc439] px-12 py-2 text-base
font-medium text-black shadow-sm hover:brightness-95 focus:outline-none focus:ring-offset-2">
Pay with
<img src="/app-store/paypal/paypal-logo.svg" alt="Paypal" className="mx-2 mb-1 mt-2 w-16" />
<span />
</Link>
</div>
);
};
+164
View File
@@ -0,0 +1,164 @@
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Toaster } from "sonner";
import AppNotInstalledMessage from "@calcom/app-store/_components/AppNotInstalledMessage";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import { Button } from "@calcom/ui/components/button";
import { TextField } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
export default function PayPalSetup() {
const [newClientId, setNewClientId] = useState("");
const [newSecretKey, setNewSecretKey] = useState("");
const router = useRouter();
const { t } = useLocale();
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");
router.push("/event-types");
},
onError: (error) => {
showToast(error.message, "error");
},
});
if (integrations.isPending) {
return <div className="absolute z-50 flex h-screen w-full items-center bg-gray-200" />;
}
return (
<div className="bg-default flex h-screen">
{showContent ? (
<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="Paypal Payment Logo" />
<p className="text-default mt-5 text-lg">Paypal</p>
</div>
<form autoComplete="off" className="mt-5">
<TextField
label="Client Id"
type="text"
name="client_id"
id="client_id"
value={newClientId}
onChange={(e) => setNewClientId(e.target.value)}
role="presentation"
/>
<TextField
label="Secret Key"
type="password"
name="access_token"
id="access_token"
value={newSecretKey}
autoComplete="new-password"
role="presentation"
onChange={(e) => setNewSecretKey(e.target.value)}
/>
{/* Button to submit */}
<div className="mt-5 flex flex-row justify-end">
<Button
color="secondary"
onClick={() => {
saveKeysMutation.mutate({
credentialId,
key: {
client_id: newClientId,
secret_key: newSecretKey,
},
});
}}>
{t("save")}
</Button>
</div>
</form>
<div>
<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.com 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">
<Icon name="circle-alert" 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>Paypal Business account</li>
<li>Paypal Developer account</li>
</ul>
<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">
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">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>
Log into your Paypal Developer account and create a new app{" "}
<a
target="_blank"
href="https://developer.paypal.com/dashboard/applications/live"
className="text-orange-600 underline">
{t("here")}
</a>
.
</li>
<li>Choose a name for your application.</li>
<li>Click on the Create App button</li>
<li>
Go back to{" "}
<a
className="text-orange-600 underline"
href="https://developer.paypal.com/dashboard/applications/live">
dashboard
</a>
, click on new app created.
</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">
<Icon name="circle-alert" className="mr-2 mt-1 h-4 w-4" />
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>
</div>
</div>
</div>
) : (
<AppNotInstalledMessage appName="paypal" />
)}
<Toaster position="bottom-right" />
</div>
);
}
@@ -0,0 +1,568 @@
import { useRouter } from "next/navigation";
import { createContext, forwardRef, useContext, useState } from "react";
import { useForm } from "react-hook-form";
import { v4 as uuidv4 } from "uuid";
import getFieldIdentifier from "@calcom/app-store/routing-forms/lib/getFieldIdentifier";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { dataTableQueryParamsSerializer } from "@calcom/features/data-table/lib/serializers";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { RoutingFormEmbedButton, RoutingFormEmbedDialog } from "@calcom/features/embed/RoutingFormEmbed";
import { EmbedDialogProvider } from "@calcom/features/embed/lib/hooks/useEmbedDialogCtx";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import slugify from "@calcom/lib/slugify";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
import type { ButtonProps } from "@calcom/ui/components/button";
import { Button } from "@calcom/ui/components/button";
import {
DialogContent,
DialogFooter,
DialogClose,
ConfirmationDialogContent,
} from "@calcom/ui/components/dialog";
import {
Dropdown,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@calcom/ui/components/dropdown";
import { TextAreaField } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { Form } from "@calcom/ui/components/form";
import { Switch } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
type FormField = {
identifier?: string;
id: string;
type: string;
label: string;
routerId?: string | null;
};
type RoutingForm = {
id: string;
name: string;
disabled: boolean;
fields?: FormField[];
};
export type NewFormDialogState = { action: "new" | "duplicate"; target: string | null } | null;
export type SetNewFormDialogState = React.Dispatch<React.SetStateAction<NewFormDialogState>>;
function NewFormDialog({
appUrl,
newFormDialogState,
setNewFormDialogState,
}: {
appUrl: string;
newFormDialogState: NewFormDialogState;
setNewFormDialogState: SetNewFormDialogState;
}) {
const { t } = useLocale();
const router = useRouter();
const utils = trpc.useUtils();
const action = newFormDialogState?.action;
const target = newFormDialogState?.target;
const mutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
onSuccess: (_data, variables) => {
router.push(`${appUrl}/form-edit/${variables.id}`);
},
onError: (err) => {
showToast(err.message || t("something_went_wrong"), "error");
},
onSettled: () => {
utils.viewer.appRoutingForms.forms.invalidate();
},
});
const hookForm = useForm<{
name: string;
description: string;
shouldConnect: boolean;
}>();
const formToDuplicate = action === "duplicate" ? target : null;
const teamId = action === "new" ? Number(target) : null;
const { register } = hookForm;
return (
<Dialog open={newFormDialogState !== null} onOpenChange={(open) => !open && setNewFormDialogState(null)}>
<DialogContent className="overflow-y-auto">
<div className="mb-1">
<h3
className="text-emphasis !font-cal text-semibold leading-20 text-xl font-medium"
id="modal-title">
{teamId ? t("add_new_team_form") : t("add_new_form")}
</h3>
<div>
<p className="text-subtle text-sm">{t("form_description")}</p>
</div>
</div>
<Form
form={hookForm}
handleSubmit={(values) => {
const formId = uuidv4();
mutation.mutate({
id: formId,
...values,
addFallback: true,
teamId,
duplicateFrom: formToDuplicate,
});
}}>
<div className="mt-3 space-y-5">
<TextField label={t("title")} required placeholder={t("a_routing_form")} {...register("name")} />
<div className="mb-5">
<TextAreaField
id="description"
label={t("description")}
{...register("description")}
data-testid="description"
placeholder={t("form_description_placeholder")}
/>
</div>
{/* Disable this feature for new forms till we get it fully working with Routing Form with Attributes. This isn't much used feature */}
{/* {action === "duplicate" && (
<Controller
name="shouldConnect"
render={({ field: { value, onChange } }) => {
return (
<SettingsToggle
title={t("keep_me_connected_with_form")}
description={t("fields_in_form_duplicated")}
checked={value}
onCheckedChange={(checked) => {
onChange(checked);
}}
/>
);
}}
/>
)} */}
</div>
<DialogFooter showDivider className="mt-12">
<DialogClose />
<Button loading={mutation.isPending} data-testid="add-form" type="submit">
{t("continue")}
</Button>
</DialogFooter>
</Form>
</DialogContent>
</Dialog>
);
}
const dropdownCtx = createContext<{ dropdown: boolean }>({ dropdown: false });
export const FormActionsDropdown = ({
children,
disabled,
}: {
disabled?: boolean;
children: React.ReactNode;
}) => {
return (
<dropdownCtx.Provider value={{ dropdown: true }}>
<Dropdown>
<DropdownMenuTrigger disabled={disabled} data-testid="form-dropdown" asChild>
<Button
type="button"
variant="icon"
color="secondary"
className={classNames(disabled && "opacity-30")}
StartIcon="ellipsis"
/>
</DropdownMenuTrigger>
<DropdownMenuContent>{children}</DropdownMenuContent>
</Dropdown>
</dropdownCtx.Provider>
);
};
function Dialogs({
appUrl,
deleteDialogOpen,
setDeleteDialogOpen,
deleteDialogFormId,
newFormDialogState,
setNewFormDialogState,
}: {
appUrl: string;
deleteDialogOpen: boolean;
setDeleteDialogOpen: (open: boolean) => void;
deleteDialogFormId: string | null;
newFormDialogState: NewFormDialogState | null;
setNewFormDialogState: SetNewFormDialogState;
}) {
const utils = trpc.useUtils();
const router = useRouter();
const { t } = useLocale();
const deleteMutation = trpc.viewer.appRoutingForms.deleteForm.useMutation({
onMutate: async ({ id: formId }) => {
await utils.viewer.appRoutingForms.forms.cancel();
const previousValue = utils.viewer.appRoutingForms.forms.getData();
if (previousValue) {
const filtered = previousValue.filtered.filter(({ form: { id } }) => id !== formId);
utils.viewer.appRoutingForms.forms.setData(
{},
{
...previousValue,
filtered,
}
);
}
return { previousValue };
},
onSuccess: () => {
showToast(t("form_deleted"), "success");
setDeleteDialogOpen(false);
router.push(`${appUrl}/forms`);
},
onSettled: () => {
utils.viewer.appRoutingForms.forms.invalidate();
setDeleteDialogOpen(false);
},
onError: (err, newTodo, context) => {
if (context?.previousValue) {
utils.viewer.appRoutingForms.forms.setData({}, context.previousValue);
}
showToast(err.message || t("something_went_wrong"), "error");
},
});
return (
<div id="form-dialogs">
<RoutingFormEmbedDialog />
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<ConfirmationDialogContent
isPending={deleteMutation.isPending}
variety="danger"
title={t("delete_form")}
confirmBtnText={t("delete_form_action")}
loadingText={t("delete_form_action")}
onConfirm={(e) => {
if (!deleteDialogFormId) {
return;
}
e.preventDefault();
deleteMutation.mutate({
id: deleteDialogFormId,
});
}}>
<ul className="list-disc pl-3">
<li> {t("delete_form_confirmation")}</li>
<li> {t("delete_form_confirmation_2")}</li>
</ul>
</ConfirmationDialogContent>
</Dialog>
<NewFormDialog
appUrl={appUrl}
newFormDialogState={newFormDialogState}
setNewFormDialogState={setNewFormDialogState}
/>
</div>
);
}
const actionsCtx = createContext({
appUrl: "",
// eslint-disable-next-line @typescript-eslint/no-empty-function
setNewFormDialogState: null as SetNewFormDialogState | null,
newFormDialogState: null as NewFormDialogState,
_delete: {
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onAction: (_arg: { routingForm: RoutingForm | null }) => {},
isPending: false,
},
toggle: {
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onAction: (_arg: { routingForm: RoutingForm | null; checked: boolean }) => {},
isPending: false,
},
});
interface FormActionsProviderProps {
appUrl: string;
children: React.ReactNode;
newFormDialogState: NewFormDialogState;
setNewFormDialogState: SetNewFormDialogState;
}
export function FormActionsProvider({
appUrl,
children,
newFormDialogState,
setNewFormDialogState,
}: FormActionsProviderProps) {
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deleteDialogFormId, setDeleteDialogFormId] = useState<string | null>(null);
const { t } = useLocale();
const utils = trpc.useUtils();
const toggleMutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
onMutate: async ({ id: formId, disabled }) => {
await utils.viewer.appRoutingForms.forms.cancel();
const previousValue = utils.viewer.appRoutingForms.forms.getData();
if (previousValue) {
const formIndex = previousValue.filtered.findIndex(({ form: { id } }) => id === formId);
const previousListOfForms = [...previousValue.filtered];
if (formIndex !== -1 && previousListOfForms[formIndex] && disabled !== undefined) {
previousListOfForms[formIndex].form.disabled = disabled;
}
utils.viewer.appRoutingForms.forms.setData(
{},
{
filtered: previousListOfForms,
totalCount: previousValue.totalCount,
}
);
}
return { previousValue };
},
onSuccess: () => {
showToast(t("form_updated_successfully"), "success");
},
onSettled: (routingForm) => {
utils.viewer.appRoutingForms.forms.invalidate();
if (routingForm) {
utils.viewer.appRoutingForms.formQuery.invalidate({
id: routingForm.id,
});
}
},
onError: (err, value, context) => {
if (context?.previousValue) {
utils.viewer.appRoutingForms.forms.setData({}, context.previousValue);
}
showToast(err.message || t("something_went_wrong"), "error");
},
});
return (
<>
<EmbedDialogProvider>
<actionsCtx.Provider
value={{
appUrl,
setNewFormDialogState,
newFormDialogState,
_delete: {
onAction: ({ routingForm }) => {
if (!routingForm) {
return;
}
setDeleteDialogOpen(true);
setDeleteDialogFormId(routingForm.id);
},
isPending: false,
},
toggle: {
onAction: ({ routingForm, checked }) => {
if (!routingForm) {
return;
}
toggleMutation.mutate({
...routingForm,
disabled: !checked,
});
},
isPending: toggleMutation.isPending,
},
}}>
{children}
</actionsCtx.Provider>
<Dialogs
appUrl={appUrl}
deleteDialogFormId={deleteDialogFormId}
deleteDialogOpen={deleteDialogOpen}
setDeleteDialogOpen={setDeleteDialogOpen}
newFormDialogState={newFormDialogState}
setNewFormDialogState={setNewFormDialogState}
/>
</EmbedDialogProvider>
</>
);
}
type FormActionType =
| "preview"
| "incompleteBooking"
| "edit"
| "copyLink"
| "toggle"
| "_delete"
| "embed"
| "duplicate"
| "download"
| "copyRedirectUrl"
| "viewResponses"
| "create";
type FormActionProps<T> = {
routingForm: RoutingForm | null;
as?: T;
label?: string;
//TODO: Provide types here
action: FormActionType;
children?: React.ReactNode;
render?: (props: {
routingForm: RoutingForm | null;
className?: string;
label?: string;
disabled?: boolean | null | undefined;
}) => JSX.Element;
extraClassNames?: string;
} & ButtonProps;
export const FormAction = forwardRef(function FormAction<T extends typeof Button>(
props: FormActionProps<T>,
forwardedRef: React.ForwardedRef<HTMLAnchorElement | HTMLButtonElement>
) {
const {
action: actionName,
routingForm,
children,
as: asFromElement,
extraClassNames,
...additionalProps
} = props;
const { appUrl, _delete, toggle, setNewFormDialogState } = useContext(actionsCtx);
const dropdownCtxValue = useContext(dropdownCtx);
const dropdown = dropdownCtxValue?.dropdown;
const embedLink = `forms/${routingForm?.id}`;
const orgBranding = useOrgBranding();
const formLink = `${orgBranding?.fullDomain ?? WEBSITE_URL}/${embedLink}`;
let redirectUrl = `${orgBranding?.fullDomain ?? WEBSITE_URL}/router?form=${routingForm?.id}`;
routingForm?.fields?.forEach((field) => {
redirectUrl += `&${getFieldIdentifier(field)}={Recalled_Response_For_This_Field}`;
});
const { t } = useLocale();
const actionData: Record<
FormActionType,
ButtonProps & { as?: React.ElementType; render?: FormActionProps<unknown>["render"] }
> = {
preview: {
href: formLink,
},
copyLink: {
onClick: () => {
showToast(t("link_copied"), "success");
navigator.clipboard.writeText(formLink);
},
},
duplicate: {
onClick: () => setNewFormDialogState?.({ action: "duplicate", target: routingForm?.id ?? null }),
},
embed: {
as: RoutingFormEmbedButton,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
embedUrl: embedLink,
// We are okay with namespace clashing here if just in case names clash
namespace: slugify((routingForm?.name || "").substring(0, 5)),
},
edit: {
href: `${appUrl}/form-edit/${routingForm?.id}`,
},
incompleteBooking: {
href: `${appUrl}/incomplete-booking/${routingForm?.id}`,
},
download: {
href: `/api/integrations/routing-forms/responses/${routingForm?.id}`,
},
_delete: {
onClick: () => _delete.onAction({ routingForm }),
loading: _delete.isPending,
},
create: {
onClick: () => setNewFormDialogState?.({ action: "new", target: "" }),
},
viewResponses: {
href: `/insights/routing${
routingForm?.id
? dataTableQueryParamsSerializer({
activeFilters: [
{ f: "formId", v: { type: ColumnFilterType.SINGLE_SELECT, data: routingForm.id } },
],
})
: ""
}`,
},
copyRedirectUrl: {
onClick: () => {
navigator.clipboard.writeText(redirectUrl);
showToast(t("typeform_redirect_url_copied"), "success");
},
},
toggle: {
render: ({ routingForm, label = "", disabled, ...restProps }) => {
if (!routingForm) {
return <></>;
}
return (
<div
{...restProps}
className={classNames(
"sm:hover:bg-subtle self-center rounded-md p-2 transition hover:bg-gray-200",
extraClassNames
)}>
<Switch
data-testid="toggle-form-switch"
disabled={!!disabled}
checked={!routingForm.disabled}
label={label}
onCheckedChange={(checked) => toggle.onAction({ routingForm, checked })}
labelOnLeading
/>
</div>
);
},
loading: toggle.isPending,
},
};
const { as: asFromAction, ...action } = actionData[actionName];
const as = asFromElement || asFromAction;
const actionProps = {
...action,
...(additionalProps as ButtonProps),
} as ButtonProps & { render?: FormActionProps<unknown>["render"] };
if (actionProps.render) {
return actionProps.render({
routingForm,
...additionalProps,
});
}
const Component = as || Button;
if (!dropdown) {
return (
<Component data-testid={`form-action-${actionName}`} ref={forwardedRef} {...actionProps}>
{children}
</Component>
);
}
return (
<DropdownMenuItem className="hover:bg-[initial]">
<Component
ref={forwardedRef}
{...actionProps}
className={classNames(
props.className,
"text-default w-full transition-none",
props.color === "destructive" && "border-0"
)}>
{children}
</Component>
</DropdownMenuItem>
);
});
@@ -0,0 +1,205 @@
"use client";
import Link from "next/link";
import { useRef } from "react";
import { Controller } from "react-hook-form";
import type { UseFormReturn } from "react-hook-form";
import { TeamMemberSelect } from "@calcom/app-store/routing-forms/components/_components/TeamMemberSelect";
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
import { IS_CALCOM } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { Switch, TextAreaField, TextField } from "@calcom/ui/components/form";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from "@calcom/ui/components/sheet";
type FormSettingsSlideoverProps = {
form: RoutingFormWithResponseCount;
hookForm: UseFormReturn<RoutingFormWithResponseCount>;
isOpen: boolean;
onOpenChange: (open: boolean) => void;
appUrl: string;
};
export const FormSettingsSlideover = ({
form,
hookForm,
isOpen,
onOpenChange,
appUrl,
}: FormSettingsSlideoverProps) => {
const { t } = useLocale();
const { data: user } = useMeQuery();
const sendUpdatesTo = hookForm.watch("settings.sendUpdatesTo") || [];
const sendToAll = hookForm.watch("settings.sendToAll") || false;
// Store initial form values
const initialValuesRef = useRef({
name: hookForm.getValues("name"),
description: hookForm.getValues("description"),
settings: {
sendUpdatesTo: hookForm.getValues("settings.sendUpdatesTo") || [],
sendToAll: hookForm.getValues("settings.sendToAll") || false,
emailOwnerOnSubmission: hookForm.getValues("settings.emailOwnerOnSubmission") || false,
},
});
const handleCancel = () => {
// Revert only the fields we edit
const initialValues = initialValuesRef.current;
hookForm.setValue("name", initialValues.name);
hookForm.setValue("description", initialValues.description);
hookForm.setValue("settings.sendUpdatesTo", initialValues.settings.sendUpdatesTo);
hookForm.setValue("settings.sendToAll", initialValues.settings.sendToAll);
hookForm.setValue("settings.emailOwnerOnSubmission", initialValues.settings.emailOwnerOnSubmission);
onOpenChange(false);
};
return (
<Sheet
open={isOpen}
onOpenChange={(open) => {
if (!open) {
handleCancel();
} else {
onOpenChange(open);
}
}}>
<SheetContent className="flex flex-col">
<SheetHeader>
<SheetTitle>{t("form_settings")}</SheetTitle>
</SheetHeader>
<div className="mt-6 flex-1 overflow-y-auto">
<TextField
type="text"
containerClassName="mb-6"
placeholder={t("title")}
{...hookForm.register("name")}
data-testid="name"
/>
<TextAreaField
rows={3}
id="description"
data-testid="description"
placeholder={t("form_description_placeholder")}
{...hookForm.register("description")}
defaultValue={form.description || ""}
/>
<div className="mt-6">
{form.teamId ? (
<div className="flex flex-col">
<TeamMemberSelect
teamMembers={form.teamMembers}
selectedMembers={sendUpdatesTo}
onChange={(memberIds) => {
hookForm.setValue("settings.sendUpdatesTo", memberIds, { shouldDirty: true });
hookForm.setValue("settings.emailOwnerOnSubmission", false, {
shouldDirty: true,
});
}}
onSelectAll={(selectAll) => {
hookForm.setValue("settings.sendToAll", selectAll, { shouldDirty: true });
}}
selectAllEnabled={true}
sendToAll={sendToAll}
placeholder={t("select_members")}
/>
</div>
) : (
<Controller
name="settings.emailOwnerOnSubmission"
control={hookForm.control}
render={({ field: { value, onChange } }) => {
return (
<div className="flex items-center gap-2">
<label
htmlFor="emailOwnerOnSubmission"
className="text-default text-sm font-medium leading-none">
{t("routing_forms_send_email_owner")}
</label>
<Switch
size="sm"
id="emailOwnerOnSubmission"
checked={value}
onCheckedChange={(val) => {
onChange(val);
hookForm.unregister("settings.sendUpdatesTo");
}}
/>
</div>
);
}}
/>
)}
</div>
{form.routers.length ? (
<div className="mt-6">
<div className="text-emphasis mb-2 block text-sm font-semibold leading-none">
{t("routers")}
</div>
<p className="text-default -mt-1 text-xs leading-normal">
{t("modifications_in_fields_warning")}
</p>
<div className="flex">
{form.routers.map((router) => {
return (
<div key={router.id} className="mr-2">
<Link href={`${appUrl}/route-builder/${router.id}`}>
<Badge variant="gray">{router.name}</Badge>
</Link>
</div>
);
})}
</div>
</div>
) : null}
{form.connectedForms?.length ? (
<div className="mt-6">
<div className="text-emphasis mb-2 block text-sm font-semibold leading-none">
{t("connected_forms")}
</div>
<p className="text-default -mt-1 text-xs leading-normal">{t("form_modifications_warning")}</p>
<div className="flex">
{form.connectedForms.map((router) => {
return (
<div key={router.id} className="mr-2">
<Link href={`${appUrl}/route-builder/${router.id}`}>
<Badge variant="default">{router.name}</Badge>
</Link>
</div>
);
})}
</div>
</div>
) : null}
<div className="mt-6 flex gap-2">
{IS_CALCOM && (
<Button
target="_blank"
color="minimal"
href={`https://i.cal.com/support/routing-support-session?email=${encodeURIComponent(
user?.email ?? ""
)}&name=${encodeURIComponent(user?.name ?? "")}&form=${encodeURIComponent(form.id)}`}>
{t("need_help")}
</Button>
)}
</div>
</div>
<SheetFooter className="flex-shrink-0 ">
<Button color="minimal" onClick={handleCancel} data-testid="settings-slider-over-cancel">
{t("cancel")}
</Button>
<Button onClick={() => onOpenChange(false)} data-testid="settings-slider-over-done">
{t("done")}
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
);
};
@@ -0,0 +1,382 @@
"use client";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
import { useFormContext } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RoutingFormWithResponseCount } from "@calcom/routing-forms/types/types";
import { Button } from "@calcom/ui/components/button";
import { DropdownMenuSeparator } from "@calcom/ui/components/dropdown";
import { ToggleGroup } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { Tooltip } from "@calcom/ui/components/tooltip";
import { FormAction, FormActionsDropdown } from "./FormActions";
import { FormSettingsSlideover } from "./FormSettingsSlideover";
// Toggle group doesnt support HREF navigation, so we need to use this hook to handle navigation
const useRoutingFormNavigation = (
form: RoutingFormWithResponseCount,
appUrl: string,
setShowInfoLostDialog: (value: boolean) => void
) => {
const pathname = usePathname();
const router = useRouter();
const formContext = useFormContext<RoutingFormWithResponseCount>();
// Get the current page based on the pathname since we use a custom routing system
const getCurrentPage = () => {
const path = pathname || "";
if (path.includes("/form-edit/")) return "form-edit";
if (path.includes("/route-builder/")) return "route-builder";
if (path.includes("/incomplete-booking/")) return "incomplete-booking";
return "form-edit"; // default to form-edit if no match
};
const handleNavigation = (value: string) => {
if (!value) return;
const baseUrl = `${appUrl}/${value}/${form.id}`;
if (value === "route-builder" && formContext.formState.isDirty) {
setShowInfoLostDialog(true);
} else {
router.push(baseUrl);
}
};
return {
getCurrentPage,
handleNavigation,
};
};
const Actions = ({
form,
isSaving,
appUrl,
setIsTestPreviewOpen,
isTestPreviewOpen,
isMobile = false,
permissions,
}: {
form: RoutingFormWithResponseCount;
setIsTestPreviewOpen: (value: boolean) => void;
isSaving: boolean;
appUrl: string;
isTestPreviewOpen: boolean;
isMobile?: boolean;
permissions: {
canCreate: boolean;
canRead: boolean;
canEdit: boolean;
canDelete: boolean;
};
}) => {
const { t } = useLocale();
const formContext = useFormContext<RoutingFormWithResponseCount>();
const [isSettingsDialogOpen, setIsSettingsDialogOpen] = useState(false);
return (
<>
<div className="flex items-center">
<div className="flex gap-2">
<Tooltip sideOffset={4} content={t("preview")} side="bottom">
<Button
color="secondary"
data-testid={isMobile ? "preview-button-mobile" : "preview-button"}
type="button"
variant="icon"
onClick={() => {
setIsTestPreviewOpen(!isTestPreviewOpen);
}}>
{t("preview")}
</Button>
</Tooltip>
<Tooltip sideOffset={4} content={t("settings")} side="bottom">
<Button
color="secondary"
type="button"
StartIcon="settings"
data-testid={isMobile ? "settings-button-mobile" : "settings-button"}
onClick={() => {
setIsSettingsDialogOpen(true);
}}
/>
</Tooltip>
<FormActionsDropdown>
<FormAction
routingForm={form}
color="minimal"
target="_blank"
type="button"
rel="noreferrer"
action="preview"
StartIcon="external-link">
{t("view_form")}
</FormAction>
<FormAction
action="incompleteBooking"
className="w-full"
routingForm={form}
color="minimal"
type="button"
StartIcon="calendar">
{t("routing_incomplete_booking_tab")}
</FormAction>
<FormAction
action="copyLink"
className="w-full"
routingForm={form}
color="minimal"
type="button"
StartIcon="link">
{t("copy_link_to_form")}
</FormAction>
<FormAction
action="download"
routingForm={form}
className="w-full"
color="minimal"
type="button"
data-testid="download-responses"
StartIcon="download">
{t("download_responses")}
</FormAction>
{form?.id && (
<FormAction
action="viewResponses"
routingForm={form}
className="w-full"
color="minimal"
type="button"
data-testid="view-responses"
StartIcon="eye">
{t("view_responses")}
</FormAction>
)}
<FormAction
action="embed"
routingForm={form}
color="minimal"
type="button"
className="w-full"
StartIcon="code">
{t("embed")}
</FormAction>
<DropdownMenuSeparator className="hidden sm:block" />
<FormAction
action="_delete"
routingForm={form}
className="w-full"
type="button"
color="destructive"
disabled={!permissions.canDelete}
StartIcon="trash">
{t("delete")}
</FormAction>
<div className="block sm:hidden">
<DropdownMenuSeparator />
<FormAction
data-testid="toggle-form"
action="toggle"
routingForm={form}
label="Disable Form"
extraClassNames="hover:bg-subtle cursor-pointer rounded-[5px] pr-4 transition"
/>
</div>
</FormActionsDropdown>
<Button
data-testid={isMobile ? "update-form-mobile" : "update-form"}
loading={isSaving}
disabled={!permissions.canEdit}
type="submit"
color="primary">
{t("save")}
</Button>
</div>
</div>
<FormSettingsSlideover
hookForm={formContext}
form={form}
isOpen={isSettingsDialogOpen}
onOpenChange={setIsSettingsDialogOpen}
appUrl={appUrl}
/>
</>
);
};
export function Header({
routingForm,
isSaving,
appUrl,
setShowInfoLostDialog,
setIsTestPreviewOpen,
isTestPreviewOpen,
permissions,
}: {
routingForm: RoutingFormWithResponseCount;
isSaving: boolean;
appUrl: string;
setShowInfoLostDialog: (value: boolean) => void;
setIsTestPreviewOpen: (value: boolean) => void;
isTestPreviewOpen: boolean;
permissions: {
canCreate: boolean;
canRead: boolean;
canEdit: boolean;
canDelete: boolean;
};
}) {
const { t } = useLocale();
const [isEditing, setIsEditing] = useState(false);
const [title, setTitle] = useState(routingForm.name);
const form = useFormContext<RoutingFormWithResponseCount>();
const { getCurrentPage, handleNavigation } = useRoutingFormNavigation(
routingForm,
appUrl,
setShowInfoLostDialog
);
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setTitle(e.target.value);
};
const handleTitleSubmit = () => {
setIsEditing(false);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
form.setValue("name", title);
handleTitleSubmit();
} else if (e.key === "Escape") {
form.setValue("name", routingForm.name);
setIsEditing(false);
}
};
const watchedName = form.watch("name");
return (
<div className="bg-default flex flex-col lg:grid lg:grid-cols-3 lg:items-center">
{/* Left - Back button and title */}
<div className="border-muted flex items-center gap-2 border-b px-4 py-3">
<Button
color="minimal"
variant="icon"
StartIcon="arrow-left"
href={`${appUrl}`}
data-testid="back-button"
/>
<div className="flex min-w-0 items-center">
<span className="text-subtle min-w-content text-sm font-semibold leading-none">
{t("routing_form")}
</span>
<span className="text-subtle mx-1 text-sm font-semibold leading-none">/</span>
{isEditing ? (
<input
{...form.register("name")}
onChange={handleTitleChange}
onKeyDown={handleKeyDown}
onBlur={handleTitleSubmit}
className="text-default h-auto w-full whitespace-nowrap border-none p-0 text-sm font-semibold leading-none focus:ring-0"
autoFocus
/>
) : (
<div className="group flex items-center gap-1">
<span
className="text-default hover:bg-muted min-w-[100px] cursor-pointer truncate whitespace-nowrap rounded px-1 text-sm font-semibold leading-none"
onClick={() => setIsEditing(true)}>
{watchedName || "Loading..."}
</span>
<Button
variant="icon"
color="minimal"
onClick={() => setIsEditing(true)}
CustomStartIcon={
<Icon name="pencil" className="text-subtle group-hover:text-default h-3 w-3" />
}>
<span className="sr-only">Edit</span>
</Button>
</div>
)}
</div>
</div>
{/* Mobile/Tablet layout - Second row with toggle group and actions on the same row */}
<div className="border-muted flex items-center justify-between border-b px-4 py-3 lg:hidden">
{/* Navigation Tabs - Left aligned */}
<div className="flex">
<ToggleGroup
defaultValue={getCurrentPage()}
value={getCurrentPage()}
onValueChange={handleNavigation}
options={[
{
value: "form-edit",
label: t("form"),
iconLeft: <Icon name="menu" className="h-3 w-3" />,
dataTestId: "toggle-group-item-form-edit",
},
{
value: "route-builder",
label: t("routing"),
iconLeft: <Icon name="waypoints" className="h-3 w-3" />,
},
]}
/>
</div>
{/* Actions - Right aligned */}
<div className="flex">
<Actions
form={routingForm}
setIsTestPreviewOpen={setIsTestPreviewOpen}
isTestPreviewOpen={isTestPreviewOpen}
isSaving={isSaving}
appUrl={appUrl}
isMobile={true}
permissions={permissions}
/>{" "}
</div>
</div>
{/* Desktop layout - Toggle group in center column */}
<div className="border-muted hidden justify-center border-b px-4 py-3 lg:flex">
<ToggleGroup
defaultValue={getCurrentPage()}
value={getCurrentPage()}
onValueChange={handleNavigation}
options={[
{
value: "form-edit",
label: t("form"),
iconLeft: <Icon name="menu" className="h-3 w-3" />,
},
{
value: "route-builder",
label: t("routing"),
iconLeft: <Icon name="waypoints" className="h-3 w-3" />,
},
]}
/>
</div>
{/* Desktop layout - Actions in right column */}
<div className="border-muted hidden justify-end border-b px-4 py-3 lg:flex">
<Actions
form={routingForm}
setIsTestPreviewOpen={setIsTestPreviewOpen}
isTestPreviewOpen={isTestPreviewOpen}
isSaving={isSaving}
appUrl={appUrl}
permissions={permissions}
/>
</div>
</div>
);
}
@@ -0,0 +1,270 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useState } from "react";
import { useFormContext } from "react-hook-form";
import type { UseFormReturn } from "react-hook-form";
import { InfoLostWarningDialog } from "@calcom/app-store/routing-forms/components/InfoLostWarningDialog";
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import classNames from "@calcom/ui/classNames";
import { Form } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import type { getServerSidePropsForSingleFormView } from "@lib/apps/routing-forms/[...pages]/getServerSidePropsSingleForm";
import type { NewFormDialogState } from "./FormActions";
import { FormActionsProvider } from "./FormActions";
import { Header } from "./Header";
import type { UptoDateForm } from "./TestForm";
import { TestFormRenderer } from "./TestForm";
export type SingleFormComponentProps = {
form: RoutingFormWithResponseCount;
appUrl: string;
Page: React.FC<{
form: RoutingFormWithResponseCount;
appUrl: string;
hookForm: UseFormReturn<RoutingFormWithResponseCount>;
}>;
enrichedWithUserProfileForm: inferSSRProps<
typeof getServerSidePropsForSingleFormView
>["enrichedWithUserProfileForm"];
permissions: inferSSRProps<typeof getServerSidePropsForSingleFormView>["permissions"];
};
const BREAKPOINTS = {
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
"2xl": 1536,
} as const;
type Breakpoint = keyof typeof BREAKPOINTS;
type BreakpointState = Record<Breakpoint, boolean>;
function useBreakPoints() {
const [breakpoints, setBreakpoints] = useState<BreakpointState>({
sm: false,
md: false,
lg: false,
xl: false,
"2xl": false,
});
useEffect(() => {
const updateBreakpoints = () => {
const width = window.innerWidth;
setBreakpoints({
sm: width >= BREAKPOINTS.sm,
md: width >= BREAKPOINTS.md,
lg: width >= BREAKPOINTS.lg,
xl: width >= BREAKPOINTS.xl,
"2xl": width >= BREAKPOINTS["2xl"],
});
};
// Initial check
updateBreakpoints();
// Add resize listener
window.addEventListener("resize", updateBreakpoints);
return () => window.removeEventListener("resize", updateBreakpoints);
}, []);
return {
...breakpoints,
// Convenience properties
isMobile: !breakpoints.md,
isTablet: breakpoints.md && !breakpoints.lg,
isDesktop: breakpoints.lg,
};
}
/**
* It has the the ongoing changes in the form along with enrichedWithUserProfileForm specific data.
* So, it can be used to test the form in the test preview dialog without saving the changes even.
*/
function SingleForm({
form,
appUrl,
Page,
enrichedWithUserProfileForm,
permissions,
}: SingleFormComponentProps) {
const utils = trpc.useUtils();
const { t } = useLocale();
const [newFormDialogState, setNewFormDialogState] = useState<NewFormDialogState>(null);
const [isTestPreviewOpen, setIsTestPreviewOpen] = useState(false);
const [skipFirstUpdate, setSkipFirstUpdate] = useState(true);
const [showInfoLostDialog, setShowInfoLostDialog] = useState(false);
const hookForm = useFormContext<RoutingFormWithResponseCount>();
const { isDesktop } = useBreakPoints();
useEffect(() => {
// The first time a tab is opened, the hookForm copies the form data (saved version, from the backend),
// and then it is considered the source of truth.
// There are two events we need to overwrite the hookForm data with the form data coming from the server.
// 1 - When we change the edited form.
// 2 - When the form is saved elsewhere (such as in another browser tab)
// In the second case. We skipped the first execution of useEffect to differentiate a tab change from a form change,
// because each time a tab changes, a new component is created and another useEffect is executed.
// An update from the form always occurs after the first useEffect execution.
if (Object.keys(hookForm.getValues()).length === 0 || hookForm.getValues().id !== form.id) {
hookForm.reset(form);
}
if (skipFirstUpdate) {
setSkipFirstUpdate(false);
} else {
hookForm.reset(form);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form]);
const mutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
onSuccess() {
showToast(t("form_updated_successfully"), "success");
},
onError(e) {
if (e.message) {
showToast(e.message, "error");
return;
}
showToast(`Something went wrong`, "error");
},
onSettled() {
utils.viewer.appRoutingForms.formQuery.invalidate({ id: form.id });
},
});
const uptoDateForm = {
...hookForm.getValues(),
routes: hookForm.watch("routes"),
user: enrichedWithUserProfileForm.user,
team: enrichedWithUserProfileForm.team,
nonOrgUsername: enrichedWithUserProfileForm.nonOrgUsername,
nonOrgTeamslug: enrichedWithUserProfileForm.nonOrgTeamslug,
userOrigin: enrichedWithUserProfileForm.userOrigin,
teamOrigin: enrichedWithUserProfileForm.teamOrigin,
} as UptoDateForm;
const handleSubmit = (data: RoutingFormWithResponseCount) => {
mutation.mutate({
...data,
});
};
return (
<>
<Form form={hookForm} handleSubmit={handleSubmit}>
<FormActionsProvider
appUrl={appUrl}
newFormDialogState={newFormDialogState}
setNewFormDialogState={setNewFormDialogState}>
<div className="flex h-full min-h-screen w-full flex-col">
<Header
routingForm={form}
isSaving={mutation.isPending}
appUrl={appUrl}
setShowInfoLostDialog={setShowInfoLostDialog}
setIsTestPreviewOpen={setIsTestPreviewOpen}
isTestPreviewOpen={isTestPreviewOpen}
permissions={permissions}
/>
<div
className={classNames(
"bg-default flex-1",
isDesktop && "grid gap-8",
isDesktop && isTestPreviewOpen && "grid-cols-[1fr,400px]",
isDesktop && !isTestPreviewOpen && "grid-cols-1",
!isDesktop && "flex flex-col"
)}>
{isDesktop ? (
<motion.div
layout
className="mx-auto w-full max-w-4xl px-2 lg:px-4 xl:px-0"
transition={{ duration: 0.3, ease: "easeInOut" }}>
<Page hookForm={hookForm} form={form} appUrl={appUrl} />
</motion.div>
) : (
<div className="mx-auto w-full max-w-4xl px-2">
<Page hookForm={hookForm} form={form} appUrl={appUrl} />
</div>
)}
<AnimatePresence>
{isTestPreviewOpen && isDesktop ? (
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
transition={{ duration: 0.3, ease: "easeInOut" }}>
<TestFormRenderer
isMobile={!isDesktop}
testForm={uptoDateForm}
isTestPreviewOpen={isTestPreviewOpen}
setIsTestPreviewOpen={setIsTestPreviewOpen}
/>
</motion.div>
) : isTestPreviewOpen ? (
<div>
<TestFormRenderer
isMobile={!isDesktop}
testForm={uptoDateForm}
isTestPreviewOpen={isTestPreviewOpen}
setIsTestPreviewOpen={setIsTestPreviewOpen}
/>
</div>
) : null}
</AnimatePresence>
</div>
</div>
</FormActionsProvider>
{showInfoLostDialog && (
<InfoLostWarningDialog
handleSubmit={() => {
mutation.mutate({
...hookForm.getValues(),
});
}}
goToRoute={`${appUrl}/route-builder/${form?.id}`}
isOpenInfoLostDialog={showInfoLostDialog}
setIsOpenInfoLostDialog={setShowInfoLostDialog}
/>
)}
</Form>
</>
);
}
export default function SingleFormWrapper({ form: _form, ...props }: SingleFormComponentProps) {
const { data: form, isPending } = trpc.viewer.appRoutingForms.formQuery.useQuery(
{ id: _form.id },
{
initialData: _form,
trpc: {},
}
);
const { t } = useLocale();
if (isPending) {
// It shouldn't be possible because we are passing the data from SSR to it as initialData. So, no need for skeleton here
return null;
}
if (!form) {
throw new Error(t("something_went_wrong"));
}
return (
<LicenseRequired>
<SingleForm form={form} {...props} />
</LicenseRequired>
);
}
@@ -0,0 +1,375 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import type { Dispatch, SetStateAction } from "react";
import { useState, useMemo } from "react";
import FormInputFields from "@calcom/app-store/routing-forms/components/FormInputFields";
import { ResultsView as Results } from "@calcom/app-store/routing-forms/components/_components/ResultSection";
import { TeamMembersMatchResult } from "@calcom/app-store/routing-forms/components/_components/TeamMembersMatchResult";
import type { MembersMatchResultType } from "@calcom/app-store/routing-forms/components/_components/TeamMembersMatchResult";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { substituteVariables } from "@calcom/app-store/routing-forms/lib/substituteVariables";
import type { RoutingForm, FormResponse, NonRouterRoute } from "@calcom/app-store/routing-forms/types/types";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import { WEBSITE_URL } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import type { Brand } from "@calcom/types/utils";
import { Button } from "@calcom/ui/components/button";
import { Dialog, DialogContent, DialogHeader, DialogFooter } from "@calcom/ui/components/dialog";
import { showToast } from "@calcom/ui/components/toast";
import type { getServerSidePropsForSingleFormView } from "@lib/apps/routing-forms/[...pages]/getServerSidePropsSingleForm";
import { TRPCClientError } from "@trpc/react-query";
export type UptoDateForm = Brand<
NonNullable<inferSSRProps<typeof getServerSidePropsForSingleFormView>["enrichedWithUserProfileForm"]>,
"UptoDateForm"
>;
const FormView = ({
form,
response,
setResponse,
areRequiredFieldsFilled,
onClose,
onSubmit,
renderFooter,
}: {
form: UptoDateForm | RoutingForm;
response: FormResponse;
setResponse: Dispatch<SetStateAction<FormResponse>>;
areRequiredFieldsFilled: boolean;
onClose: () => void;
onSubmit: () => void;
renderFooter?: (onClose: () => void, onSubmit: () => void, isValid: boolean) => React.ReactNode;
}) => {
const { t } = useLocale();
return (
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
transition={{ duration: 0.2 }}>
<form
noValidate
onSubmit={(e) => {
e.preventDefault();
}}>
{form && <FormInputFields form={form} response={response} setResponse={setResponse} />}
</form>
{!renderFooter ? (
<div className="mt-4">
<Button onClick={onSubmit} disabled={!areRequiredFieldsFilled} data-testid="submit-button">
{t("submit")}
</Button>
</div>
) : (
renderFooter(onClose, onSubmit, areRequiredFieldsFilled)
)}
</motion.div>
);
};
export const TestForm = ({
form,
supportsTeamMembersMatchingLogic,
renderFooter,
isDialog = false,
onClose: onCloseProp,
showRRData = false,
}: {
form: UptoDateForm | RoutingForm;
supportsTeamMembersMatchingLogic: boolean;
renderFooter?: (onClose: () => void, onSubmit: () => void, isValid: boolean) => React.ReactNode;
isDialog?: boolean;
onClose?: () => void;
showRRData?: boolean;
}) => {
const { t } = useLocale();
const [response, setResponse] = useState<FormResponse>({});
const [chosenRoute, setChosenRoute] = useState<NonRouterRoute | null>(null);
const searchParams = useCompatSearchParams();
const [membersMatchResult, setMembersMatchResult] = useState<MembersMatchResultType | null>(null);
const [showResults, setShowResults] = useState(false);
const [formKey, setFormKey] = useState<number>(0);
const orgBranding = useOrgBranding();
const embedLink = `forms/${form.id}`;
const formLink = `${orgBranding?.fullDomain ?? WEBSITE_URL}/${embedLink}`;
const areRequiredFieldsFilled = useMemo(() => {
if (!form.fields) return true;
const requiredFields = form.fields.filter((field) => field.required);
if (!requiredFields.length) return true;
return requiredFields.every((field) => {
const fieldResponse = response[field.id];
if (!fieldResponse) return false;
const value = fieldResponse.value;
if (Array.isArray(value)) {
return value.length > 0;
}
return value !== undefined && value !== null && value !== "";
});
}, [form.fields, response]);
const resetMembersMatchResult = () => {
setMembersMatchResult(null);
setShowResults(false);
};
function testRouting() {
const route = findMatchingRoute({ form, response });
// Create a copy of the route with substituted variables for display
let displayRoute = route;
if (route && form.fields && route.action.type === "eventTypeRedirectUrl") {
const substitutedUrl = substituteVariables(route.action.value, response, form.fields);
displayRoute = {
...route,
action: {
...route.action,
value: substitutedUrl,
},
};
}
setChosenRoute(displayRoute || null);
setShowResults(true);
if (!route) return;
// Custom Event Type Redirect URL has eventTypeId=0. Also, findTeamMembersMatchingAttributeLogicMutation can't work without eventTypeId
if (supportsTeamMembersMatchingLogic && route.action.eventTypeId) {
findTeamMembersMatchingAttributeLogicMutation.mutate({
formId: form.id,
response,
route,
isPreview: true,
_enablePerf: searchParams.get("enablePerf") === "true",
});
}
}
const onClose = () => {
setChosenRoute(null);
setResponse({});
setShowResults(false);
onCloseProp?.();
};
function resetForm() {
setChosenRoute(null);
setResponse({});
setShowResults(false);
// This is a hack to force the form to reset RAQB doesnt seem to be resetting the form when the form is re-rendered
setFormKey((prevKey) => prevKey + 1);
}
const findTeamMembersMatchingAttributeLogicMutation =
trpc.viewer.routingForms.findTeamMembersMatchingAttributeLogicOfRoute.useMutation({
onSuccess(data) {
setMembersMatchResult({
isUsingAttributeWeights: data.isUsingAttributeWeights,
eventTypeRedirectUrl: data.eventTypeRedirectUrl,
contactOwnerEmail: data.contactOwnerEmail,
teamMembersMatchingAttributeLogic: data.result ? data.result.users : data.result,
perUserData: data.result ? data.result.perUserData : null,
checkedFallback: data.checkedFallback,
mainWarnings: data.mainWarnings,
fallbackWarnings: data.fallbackWarnings,
});
},
onError(e) {
if (e instanceof TRPCClientError) {
showToast(e.message, "error");
} else {
showToast(t("something_went_wrong"), "error");
}
},
});
return (
<div>
<AnimatePresence mode="wait">
{!showResults ? (
<>
{isDialog ? (
<DialogHeader title={t("test_routing_form")} subtitle={t("test_preview_description")} />
) : !showRRData ? (
<div className="mb-6 flex items-center justify-between">
<h3 className="text-emphasis text-xl font-semibold">{t("preview")}</h3>
<div className="flex items-center gap-1">
<Button
color="secondary"
href={formLink}
target="_blank"
variant="icon"
StartIcon="external-link"
data-testid="open-form-in-new-tab"
size="sm">
<span className="sr-only">{t("open_in_new_tab")}</span>
</Button>
<Button
color="secondary"
onClick={resetForm}
variant="icon"
StartIcon="refresh-cw"
size="sm">
<span className="sr-only">{t("reset")}</span>
</Button>
<Button color="secondary" onClick={onClose} variant="icon" StartIcon="x" size="sm">
<span className="sr-only">{t("close")}</span>
</Button>
</div>
</div>
) : (
<></>
)}
<FormView
key={formKey}
form={form}
response={response}
setResponse={setResponse}
areRequiredFieldsFilled={areRequiredFieldsFilled}
onClose={onClose}
onSubmit={() => {
resetMembersMatchResult();
testRouting();
}}
renderFooter={renderFooter}
/>
</>
) : (
<>
{isDialog ? (
<DialogHeader title={t("test_routing_form")} subtitle={t("test_preview_description")} />
) : !showRRData ? (
<div className="mb-6 flex items-center justify-between">
<h3 className="text-emphasis text-xl font-semibold">{t("results")}</h3>
<div className="flex items-center gap-1">
<Button
color="secondary"
href={formLink}
target="_blank"
variant="icon"
StartIcon="external-link"
size="sm">
<span className="sr-only">{t("open_in_new_tab")}</span>
</Button>
<Button
color="secondary"
onClick={resetForm}
variant="icon"
StartIcon="refresh-cw"
size="sm">
<span className="sr-only">{t("reset")}</span>
</Button>
<Button
color="secondary"
onClick={onClose}
variant="icon"
StartIcon="x"
size="sm"
data-testid="close-results-button">
<span className="sr-only">{t("close")}</span>
</Button>
</div>
</div>
) : (
<></>
)}
{showRRData ? (
<>
<Button color="secondary" onClick={resetForm} variant="icon" StartIcon="refresh-cw">
{t("reset_form")}
</Button>
<TeamMembersMatchResult membersMatchResult={membersMatchResult} />
</>
) : (
<Results
chosenRoute={chosenRoute}
supportsTeamMembersMatchingLogic={supportsTeamMembersMatchingLogic}
membersMatchResult={membersMatchResult}
isPending={findTeamMembersMatchingAttributeLogicMutation.isPending}
/>
)}
{isDialog && (
<DialogFooter>
<Button onClick={onClose} color="secondary">
{t("back")}
</Button>
</DialogFooter>
)}
</>
)}
</AnimatePresence>
</div>
);
};
export const TestFormRenderer = ({
testForm,
isTestPreviewOpen,
setIsTestPreviewOpen,
isMobile,
}: {
testForm: UptoDateForm;
isTestPreviewOpen: boolean;
setIsTestPreviewOpen: (value: boolean) => void;
isMobile: boolean;
}) => {
const { t } = useLocale();
const isSubTeamForm = !!testForm.team?.parentId;
if (!isMobile) {
if (isTestPreviewOpen) {
return (
<div className="border-muted bg-muted h-full border-l p-6">
<TestForm
form={testForm}
supportsTeamMembersMatchingLogic={isSubTeamForm}
onClose={() => setIsTestPreviewOpen(false)}
/>
</div>
);
}
}
return (
<Dialog open={isTestPreviewOpen} onOpenChange={setIsTestPreviewOpen}>
<DialogContent size="md" enableOverflow>
<TestForm
isDialog
form={testForm}
supportsTeamMembersMatchingLogic={isSubTeamForm}
renderFooter={(onClose, onSubmit, isValid) => (
<DialogFooter>
<Button
onClick={() => {
onClose();
setIsTestPreviewOpen(false);
}}
color="secondary">
{t("close")}
</Button>
<Button onClick={onSubmit} disabled={!isValid}>
{t("submit")}
</Button>
</DialogFooter>
)}
/>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,487 @@
import { render, screen, fireEvent } from "@testing-library/react";
import type { Mock } from "vitest";
import { vi } from "vitest";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { TestFormRenderer } from "./TestForm";
vi.mock("framer-motion", async () => {
return {
motion: {
div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
},
AnimatePresence: ({ children }: any) => <>{children}</>,
};
});
vi.mock("@calcom/app-store/routing-forms/lib/processRoute", () => ({
findMatchingRoute: vi.fn(),
}));
vi.mock("next/navigation", async (importOriginal) => {
const actual = await importOriginal<typeof import("next/navigation")>();
return {
...actual,
useRouter: vi.fn(() => ({
push: vi.fn(() => {
return;
}),
})),
};
});
function mockMatchingRoute(route: any) {
(findMatchingRoute as Mock<typeof findMatchingRoute>).mockReturnValue({
...route,
id: "matching-route-id",
});
}
function mockCustomPageMessageMatchingRoute() {
mockMatchingRoute({
action: {
type: "customPageMessage",
value: "Thank you for submitting!",
},
});
}
function mockEventTypeRedirectUrlMatchingRoute() {
mockMatchingRoute({
action: {
type: "eventTypeRedirectUrl",
value: "john/30min",
eventTypeId: 123,
},
});
}
/**
* fixes the error due to Formbricks
*/
vi.mock("@calcom/features/shell/Shell", () => ({
ShellMain: vi.fn(),
}));
vi.mock("@calcom/lib/hooks/useApp", () => ({
default: vi.fn(),
}));
/**
* Avoids the error due to Formbricks
*/
vi.mock("./FormActions", () => ({
FormAction: vi.fn(),
FormActionsDropdown: vi.fn(),
FormActionsProvider: vi.fn(),
}));
vi.mock(
"@calcom/app-store/routing-forms/components/react-awesome-query-builder/widgets",
async (importOriginal) => {
return await importOriginal();
}
);
// Mock the necessary dependencies
vi.mock("@calcom/lib/hooks/useLocale", () => ({
useLocale: vi.fn(() => ({ t: (key: string) => key })),
}));
let findTeamMembersMatchingAttributeLogicResponse: {
result: { users: { email: string }[] } | null;
checkedFallback: boolean;
mainWarnings?: string[] | null;
fallbackWarnings?: string[] | null;
} = {
result: null,
checkedFallback: false,
mainWarnings: null,
fallbackWarnings: null,
};
function resetFindTeamMembersMatchingAttributeLogicResponse() {
findTeamMembersMatchingAttributeLogicResponse = {
result: null,
checkedFallback: false,
mainWarnings: null,
fallbackWarnings: null,
};
}
function mockFindTeamMembersMatchingAttributeLogicResponse(
response: typeof findTeamMembersMatchingAttributeLogicResponse
) {
findTeamMembersMatchingAttributeLogicResponse = response;
}
vi.mock("@calcom/trpc/react", () => ({
trpc: {
viewer: {
routingForms: {
findTeamMembersMatchingAttributeLogicOfRoute: {
useMutation: vi.fn(({ onSuccess }) => {
return {
mutate: vi.fn(() => {
onSuccess(findTeamMembersMatchingAttributeLogicResponse);
}),
};
}),
},
},
},
},
}));
const mockSubTeamForm = {
id: "routing-form-id",
teamId: "test-team-id",
name: "Test Form",
description: "Test form description",
fields: [
{
id: "name",
identifier: "name",
type: "text",
label: "Name",
required: true,
},
],
routes: [
{
id: "non-matching-route-id",
isFallback: false,
action: {
type: "customPageMessage",
value: "Not matching",
},
},
{
id: "matching-route-id",
isFallback: false,
action: {
type: "customPageMessage",
value: "Thank you for submitting!",
},
},
{
id: "fallback-route",
isFallback: true,
action: {
type: "customPageMessage",
value: "Thank you for submitting!",
},
},
],
team: {
parentId: "org-1",
},
} as any;
const mockRegularTeamForm = {
...mockSubTeamForm,
team: {
parentId: null,
},
} as any;
describe("TestFormDialog", () => {
beforeEach(() => {
resetFindTeamMembersMatchingAttributeLogicResponse();
vi.clearAllMocks();
});
it("renders the dialog when open", () => {
render(
<TestFormRenderer
isMobile={true}
testForm={mockSubTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
expect(screen.getByText("test_routing_form")).toBeInTheDocument();
expect(screen.getByText("test_preview_description")).toBeInTheDocument();
});
it("doesn't render the dialog when closed", () => {
render(
<TestFormRenderer
isMobile={true}
testForm={mockSubTeamForm}
isTestPreviewOpen={false}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
expect(screen.queryByText("test_routing_form")).not.toBeInTheDocument();
});
it("renders form fields", () => {
render(
<TestFormRenderer
isMobile={true}
testForm={mockSubTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
expect(screen.getByTestId("form-field-name")).toBeInTheDocument();
});
describe("Sub-Team Form", () => {
const form = mockSubTeamForm;
it("submits the form and shows test results for Custom Page", async () => {
mockCustomPageMessageMatchingRoute();
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("Thank you for submitting!");
});
it("submits the form and shows test results for Event Type", async () => {
mockEventTypeRedirectUrlMatchingRoute();
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("john/30min");
expect(screen.getByTestId("attribute-logic-matched")).toHaveTextContent("Yes");
expect(screen.getByTestId("attribute-logic-fallback-matched")).toHaveTextContent("Not needed");
// Skip the matching members check as it's giving issues
});
it("suggests to add fallback when matching members is empty and fallback is not checked", async () => {
mockEventTypeRedirectUrlMatchingRoute();
mockFindTeamMembersMatchingAttributeLogicResponse({
result: {
users: [],
},
checkedFallback: false,
});
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("john/30min");
expect(screen.getByTestId("attribute-logic-matched")).toHaveTextContent("Yes");
expect(screen.getByTestId("attribute-logic-fallback-matched")).toHaveTextContent("Not needed");
// Skip the matching members check as it's giving issues
});
it("shows warnings when there are warnings", async () => {
mockEventTypeRedirectUrlMatchingRoute();
mockFindTeamMembersMatchingAttributeLogicResponse({
result: null,
checkedFallback: false,
mainWarnings: ["Main-Error-1", "Main-Error-2"],
fallbackWarnings: ["Fallback-Error-1", "Fallback-Error-2"],
});
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
// Get all alerts without checking their specific count
const alerts = screen.getAllByTestId("alert");
// Verify that at least the main and fallback warnings are present
expect(alerts.some((alert) => alert.textContent?.includes("Main-Error-1"))).toBe(true);
expect(alerts.some((alert) => alert.textContent?.includes("Main-Error-2"))).toBe(true);
expect(alerts.some((alert) => alert.textContent?.includes("Fallback-Error-1"))).toBe(true);
expect(alerts.some((alert) => alert.textContent?.includes("Fallback-Error-2"))).toBe(true);
});
it("should not show warnings when there are no warnings", async () => {
mockEventTypeRedirectUrlMatchingRoute();
mockFindTeamMembersMatchingAttributeLogicResponse({
result: null,
checkedFallback: false,
mainWarnings: null,
fallbackWarnings: null,
});
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
screen.logTestingPlaygroundURL();
const alerts = screen.queryAllByTestId("alert");
expect(alerts).toHaveLength(0);
});
it("should show No in main and fallback matched", async () => {
mockEventTypeRedirectUrlMatchingRoute();
mockFindTeamMembersMatchingAttributeLogicResponse({
result: {
users: [],
},
checkedFallback: true,
mainWarnings: null,
fallbackWarnings: null,
});
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("attribute-logic-matched")).toHaveTextContent("No");
expect(screen.getByTestId("attribute-logic-fallback-matched")).toHaveTextContent("Yes");
// Skip the matching members check as it's giving issues
});
});
describe("Regular Team Form", () => {
const form = mockRegularTeamForm;
it("submits the form and shows test results for Custom Page", async () => {
mockCustomPageMessageMatchingRoute();
render(
<TestFormRenderer
isMobile={true}
testForm={mockRegularTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("Thank you for submitting!");
});
it("submits the form and shows test results for Event Type", async () => {
mockEventTypeRedirectUrlMatchingRoute();
render(
<TestFormRenderer
isMobile={true}
testForm={form}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("john/30min");
// When we support showing matching route we can add this back
// expect(screen.getByTestId("chosen-route")).toHaveTextContent("Route 2");
});
it("should substitute variables in event redirect URL", async () => {
// Mock a route with variables using the name field that already exists
mockMatchingRoute({
action: {
type: "eventTypeRedirectUrl",
value: "/team/{name}/meeting",
},
});
render(
<TestFormRenderer
isMobile={true}
testForm={mockRegularTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
// Fill in the name field
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "Sales Team" } });
fireEvent.click(screen.getByText("submit"));
// Verify the URL shows the substituted value, not the variable
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("/team/sales-team/meeting");
expect(screen.getByTestId("test-routing-result")).not.toHaveTextContent("{name}");
});
it("should NOT substitute variables in external redirect URL", async () => {
// Mock a route with variables for external redirect
mockMatchingRoute({
action: {
type: "externalRedirectUrl",
value: "https://example.com/user/{name}",
},
});
render(
<TestFormRenderer
isMobile={true}
testForm={mockRegularTeamForm}
isTestPreviewOpen={true}
setIsTestPreviewOpen={() => {
return;
}}
/>
);
fireEvent.change(screen.getByTestId("form-field-name"), { target: { value: "John Doe" } });
fireEvent.click(screen.getByText("submit"));
// Verify the URL shows the variable as-is, without substitution
expect(screen.getByTestId("test-routing-result")).toHaveTextContent("https://example.com/user/{name}");
expect(screen.getByTestId("test-routing-result")).not.toHaveTextContent("john-doe");
});
});
});
+152
View File
@@ -0,0 +1,152 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { Toaster } from "sonner";
import z from "zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { Form } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
const formSchema = z.object({
api_key: z.string(),
});
export default function SendgridSetup() {
const { t } = useLocale();
const router = useRouter();
const [testPassed, setTestPassed] = useState<boolean | undefined>(undefined);
const [testLoading, setTestLoading] = useState<boolean>(false);
const form = useForm<{
api_key: string;
}>({
resolver: zodResolver(formSchema),
});
useEffect(() => {
const timer = setTimeout(() => {
if (testPassed === false) {
setTestPassed(undefined);
}
}, 3000);
return () => clearTimeout(timer);
}, [testPassed]);
return (
<div className="bg-emphasis flex h-screen">
<div className="bg-default m-auto rounded p-5 md:w-[520px] md:p-10">
<div className="flex flex-col space-y-5 md:flex-row md:space-x-5 md:space-y-0">
<div>
<img src="/api/app-store/sendgrid/logo.png" alt="Sendgrid" className="h-12 w-12 max-w-2xl" />
</div>
<div>
<h1 className="text-default">{t("provide_api_key")}</h1>
<div className="mt-1 text-sm">
{t("generate_api_key_description", { appName: "Sendgrid" })}{" "}
<a
className="text-indigo-400"
href="https://app.sendgrid.com/settings/api_keys"
target="_blank"
rel="noopener noreferrer">
Sendgrid
</a>
. {t("it_stored_encrypted")}
</div>
<div className="my-2 mt-3">
<Form
form={form}
handleSubmit={async (values) => {
const res = await fetch("/api/integrations/sendgrid/add", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (res.ok) {
router.push(json.url);
} else {
showToast(json.message, "error");
}
}}>
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
<Controller
name="api_key"
control={form.control}
render={({ field: { onBlur, onChange } }) => (
<TextField
className="my-0"
onBlur={onBlur}
disabled={testPassed === true}
name="api_key"
placeholder="SG.xxxxxx..."
onChange={async (e) => {
onChange(e.target.value);
form.setValue("api_key", e.target.value);
await form.trigger("api_key");
}}
/>
)}
/>
</fieldset>
<div className="mt-5 justify-end space-x-2 rtl:space-x-reverse sm:mt-4 sm:flex">
<Button type="button" color="secondary" onClick={() => router.back()}>
{t("cancel")}
</Button>
<Button
type="submit"
loading={testLoading}
disabled={testPassed === true}
StartIcon={testPassed === undefined ? undefined : testPassed ? "check" : "x"}
className={
testPassed !== undefined
? testPassed
? " !bg-success hover:bg-success !text-green-700"
: "bg-error hover:bg-error !border-red-700 !text-red-700"
: "secondary"
}
color={testPassed === true ? "minimal" : "secondary"}
onClick={async () => {
const check = await form.trigger("api_key");
if (!check) return;
const api_key = form.getValues("api_key");
setTestLoading(true);
const res = await fetch("/api/integrations/sendgrid/check", {
method: "POST",
body: JSON.stringify({ api_key }),
headers: {
"Content-Type": "application/json",
},
});
if (res.status === 200) {
setTestPassed(true);
} else {
setTestPassed(false);
}
setTestLoading(false);
}}>
{t(
testPassed !== undefined ? (testPassed ? "test_passed" : "test_failed") : "test_api_key"
)}
</Button>
<Button type="submit" loading={form.formState.isSubmitting}>
{t("save")}
</Button>
</div>
</Form>
</div>
</div>
</div>
</div>
<Toaster position="bottom-right" />
</div>
);
}
@@ -0,0 +1,3 @@
export default function StripePaymentSetup() {
return null;
}
@@ -0,0 +1,124 @@
import { useMutation } from "@tanstack/react-query";
import type { Dispatch, SetStateAction } from "react";
import { useState } from "react";
import dayjs from "@calcom/dayjs";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import logger from "@calcom/lib/logger";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
interface IConfirmDialogWipe {
isOpenDialog: boolean;
setIsOpenDialog: Dispatch<SetStateAction<boolean>>;
}
interface IWipeMyCalAction {
initialDate: string;
endDate: string;
}
const wipeMyCalAction = async (props: IWipeMyCalAction) => {
const { initialDate, endDate } = props;
const body = {
initialDate,
endDate,
};
try {
const endpoint = "/api/integrations/wipemycalother/wipe";
return fetch(`${process.env.NEXT_PUBLIC_WEBAPP_URL}${endpoint}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
} catch (error: unknown) {
if (error instanceof Error) {
showToast("Error occurred while trying to cancel bookings", "error");
}
}
};
export const ConfirmDialog = (props: IConfirmDialogWipe) => {
const { t } = useLocale();
const { isOpenDialog, setIsOpenDialog } = props;
const [isPending, setIsPending] = useState(false);
const today = dayjs();
const initialDate = today.startOf("day");
const endDate = today.endOf("day");
const dateFormat = "ddd, MMM D, YYYY h:mm A";
const utils = trpc.useUtils();
const rescheduleApi = useMutation({
mutationFn: async () => {
setIsPending(true);
try {
const result = await wipeMyCalAction({
initialDate: initialDate.toISOString(),
endDate: endDate.toISOString(),
});
if (result) {
showToast(t("reschedule_request_sent"), "success");
setIsOpenDialog(false);
}
} catch (error) {
showToast(t("unexpected_error_try_again"), "error");
// @TODO: notify
}
setIsPending(false);
},
async onSettled() {
await utils.viewer.bookings.invalidate();
},
});
return (
<Dialog open={isOpenDialog} onOpenChange={setIsOpenDialog}>
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()}>
<div className="flex flex-row space-x-3">
<div className="flex h-10 w-10 flex-shrink-0 justify-center rounded-full bg-[#FAFAFA]">
<Icon name="clock" className="m-auto h-5 w-5" />
</div>
<div className="pt-1">
<DialogHeader title="Wipe My Calendar" />
<p className="text-subtle mt-2 text-sm">
This will cancel all upcoming meetings from: <br />{" "}
<strong className="text-emphasis">
{initialDate.format(dateFormat)} - {endDate.format(dateFormat)}
</strong>
</p>
<p className="mb-2 mt-6 text-sm">Are you sure? This can&apos;t be undone</p>
</div>
</div>
<DialogFooter>
<Button color="secondary" onClick={() => setIsOpenDialog(false)}>
{t("cancel")}
</Button>
<Button
color="primary"
data-testid="send_request"
disabled={isPending}
onClick={async () => {
try {
rescheduleApi.mutate();
} catch (error) {
if (error instanceof Error) {
logger.error(error.message);
}
}
}}>
{t("confirm")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,42 @@
import { useState } from "react";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { ConfirmDialog } from "./confirmDialog";
interface IWipeMyCalActionButtonProps {
bookingsEmpty: boolean;
bookingStatus: "upcoming" | "recurring" | "past" | "cancelled" | "unconfirmed";
}
const WipeMyCalActionButton = (props: IWipeMyCalActionButtonProps) => {
const { bookingsEmpty, bookingStatus } = props;
const [openDialog, setOpenDialog] = useState(false);
const { isSuccess, isPending, data } = trpc.viewer.apps.integrations.useQuery({
variant: "other",
onlyInstalled: undefined,
});
if (bookingStatus !== "upcoming" || bookingsEmpty) {
return <></>;
}
const wipeMyCalCredentials = data?.items.find((item: { type: string }) => item.type === "wipemycal_other");
const [credentialId] = wipeMyCalCredentials?.userCredentialIds || [false];
return (
<>
{data && isSuccess && !isPending && credentialId && (
<div className="mb-4">
<ConfirmDialog isOpenDialog={openDialog} setIsOpenDialog={setOpenDialog} />
<Button color="primary" onClick={() => setOpenDialog(true)} data-testid="wipe-today-button">
Wipe Today
</Button>
</div>
)}
</>
);
};
export { WipeMyCalActionButton };
+179
View File
@@ -0,0 +1,179 @@
import Link from "next/link";
import { useState } from "react";
import { Toaster } from "sonner";
import AppNotInstalledMessage from "@calcom/app-store/_components/AppNotInstalledMessage";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
export interface IZapierSetupProps {
inviteLink?: string;
}
const ZAPIER = "zapier";
export default function ZapierSetup(props: IZapierSetupProps) {
const [newApiKeys, setNewApiKeys] = useState<Record<string, string>>({});
const { t } = useLocale();
const utils = trpc.useUtils();
const integrations = trpc.viewer.apps.integrations.useQuery({ variant: "automation" });
const oldApiKey = trpc.viewer.apiKeys.findKeyOfType.useQuery({ appId: ZAPIER });
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 zapierCredentials: { userCredentialIds: number[] } | undefined = integrations.data?.items.find(
(item: { type: string }) => item.type === "zapier_automation"
);
const [credentialId] = zapierCredentials?.userCredentialIds || [false];
const showContent = integrations.data && integrations.isSuccess && credentialId;
const isCalDev = process.env.NEXT_PUBLIC_WEBAPP_URL === "https://app.cal.dev";
async function createApiKey(teamId?: number) {
const event = { note: "Zapier", expiresAt: null, appId: ZAPIER, teamId };
const apiKey = await utils.client.viewer.apiKeys.create.mutate(event);
if (oldApiKey.data) {
const oldKey = teamId
? oldApiKey.data.find((key) => key.teamId === teamId)
: oldApiKey.data.find((key) => !key.teamId);
if (oldKey) {
deleteApiKey.mutate({
id: oldKey.id,
});
}
}
return apiKey;
}
async function generateApiKey(teamId?: number) {
const apiKey = await createApiKey(teamId);
setNewApiKeys({ ...newApiKeys, [teamId || ""]: apiKey });
}
if (integrations.isPending) {
return <div className="bg-emphasis absolute z-50 flex h-screen w-full items-center" />;
}
return (
<div className="bg-emphasis flex h-screen">
{showContent ? (
<div className="bg-default m-auto max-w-[43em] overflow-auto rounded pb-10 md:p-10">
<div className="md:flex md:flex-row">
<div className="invisible md:visible">
<img className="h-11" src="/api/app-store/zapier/icon.svg" alt="Zapier Logo" />
</div>
<div className="ml-2 ltr:mr-2 rtl:ml-2 md:ml-5">
<div className="text-default">{t("setting_up_zapier")}</div>
<>
<div className="mt-1 text-xl">{t("generate_api_key")}:</div>
{!teams ? (
<Button color="secondary" onClick={() => createApiKey()} className="mb-4 mt-2">
{t("generate_api_key")}
</Button>
) : (
<>
<div className="mt-8 text-sm font-semibold">Your event types:</div>
{!newApiKeys[""] ? (
<Button color="secondary" onClick={() => generateApiKey()} className="mb-4 mt-2">
{t("generate_api_key")}
</Button>
) : (
<CopyApiKey apiKey={newApiKeys[""]} />
)}
{teams.map((team) => {
return (
<div key={team.name}>
<div className="mt-2 text-sm font-semibold">{team.name}:</div>
{!newApiKeys[team.id] ? (
<Button
color="secondary"
onClick={() => generateApiKey(team.id)}
className="mb-4 mt-2">
{t("generate_api_key")}
</Button>
) : (
<CopyApiKey apiKey={newApiKeys[team.id]} />
)}
</div>
);
})}
</>
)}
</>
<ol className="mb-5 ml-5 mt-5 list-decimal ltr:mr-5 rtl:ml-5">
{isCalDev && (
<li>
{t("go_to")}
<a href={props.inviteLink} className="text-orange-600 underline">
{t("zapier_invite_link")}
</a>
</li>
)}
<ServerTrans
t={t}
i18nKey="zapier_setup_instructions"
components={[
<li key="instruction_1">Log into your Zapier account and create a new Zap.</li>,
<li key="instruction_2">
Select Cal.com as your Trigger app. Also choose a Trigger event.
</li>,
<li key="instruction_3">Choose your account and then enter your Unique API Key.</li>,
<li key="instruction_4">Test your Trigger.</li>,
<li key="instruction_5">You&apos;re set!</li>,
]}
/>
</ol>
<Link href="/apps/installed/automation?hl=zapier" passHref={true} legacyBehavior>
<Button color="secondary">{t("done")}</Button>
</Link>
</div>
</div>
</div>
) : (
<AppNotInstalledMessage appName="zapier" />
)}
<Toaster position="bottom-right" />
</div>
);
}
const CopyApiKey = ({ apiKey }: { apiKey: string }) => {
const { t } = useLocale();
return (
<div>
<div className="my-2 mt-3 flex-wrap sm:flex sm:flex-nowrap">
<code className="bg-subtle h-full w-full whitespace-pre-wrap rounded-md py-[6px] pl-2 pr-2 sm:rounded-r-none sm:pr-5">
{apiKey}
</code>
<Tooltip side="top" content={t("copy_to_clipboard")}>
<Button
onClick={() => {
navigator.clipboard.writeText(apiKey);
showToast(t("api_key_copied"), "success");
}}
type="button"
className="mt-4 text-base sm:mt-0 sm:rounded-l-none">
<Icon name="clipboard" className="h-4 w-4 ltr:mr-2 rtl:ml-2" />
{t("copy")}
</Button>
</Tooltip>
</div>
<div className="text-subtle mb-5 mt-2 text-sm">{t("copy_somewhere_safe")}</div>
</div>
);
};
+1 -1
View File
@@ -12,12 +12,12 @@ import 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 { getUrlSearchParamsToForwardForReroute } from "@calcom/app-store/routing-forms/pages/routing-link/getUrlSearchParamsToForward";
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 { 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 { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { EventType, User, Team, Attendee, Booking as PrismaBooking } from "@calcom/prisma/client";