Skip to content

Scheduling infrastructure for absolutely everyone.

refactor webhooks UI (#982)

Alex Johanssond8dac426eb0c
diff --git a/components/Dialog.tsx b/components/Dialog.tsx
index 9465662c9ff..86e4de64a01 100644
--- a/components/Dialog.tsx
+++ b/components/Dialog.tsx
@@ -25,17 +25,17 @@ export const DialogContent = React.forwardRef<HTMLDivElement, DialogContentProps
);
type DialogHeaderProps = {
- title: React.ReactElement | string;
- subtitle: React.ReactElement | string;
+ title: React.ReactNode;
+ subtitle?: React.ReactNode;
};
-export function DialogHeader({ title, subtitle }: DialogHeaderProps) {
+export function DialogHeader(props: DialogHeaderProps) {
return (
<div className="mb-8">
<h3 className="font-cal text-gray-900 text-lg font-bold leading-6" id="modal-title">
- {title}
+ {props.title}
</h3>
- <div className="text-gray-400 text-sm">{subtitle}</div>
+ {props.subtitle && <div className="text-gray-400 text-sm">{props.subtitle}</div>}
</div>
);
}
diff --git a/components/form/fields.tsx b/components/form/fields.tsx
index 88b0c7155b4..f4b27cc8c79 100644
--- a/components/form/fields.tsx
+++ b/components/form/fields.tsx
@@ -4,7 +4,8 @@ import { FormProvider, UseFormReturn } from "react-hook-form";
import classNames from "@lib/classNames";
-export const Input = forwardRef<HTMLInputElement, JSX.IntrinsicElements["input"]>(function Input(props, ref) {
+type InputProps = Omit<JSX.IntrinsicElements["input"], "name"> & { name: string };
+export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(props, ref) {
return (
<input
{...props}
@@ -61,3 +62,21 @@ export const Form = forwardRef<HTMLFormElement, { form: UseFormReturn<any> } & J
);
}
);
+
+export function FieldsetLegend(props: JSX.IntrinsicElements["legend"]) {
+ return (
+ <legend {...props} className={classNames("text-sm font-medium text-gray-700", props.className)}>
+ {props.children}
+ </legend>
+ );
+}
+
+export function InputGroupBox(props: JSX.IntrinsicElements["div"]) {
+ return (
+ <div
+ {...props}
+ className={classNames("p-2 bg-white border border-gray-300 rounded-sm space-y-2", props.className)}>
+ {props.children}
+ </div>
+ );
+}
diff --git a/components/ui/Switch.tsx b/components/ui/Switch.tsx
index 20bbb386ebc..d645661ff90 100644
--- a/components/ui/Switch.tsx
+++ b/components/ui/Switch.tsx
@@ -1,13 +1,14 @@
import { useId } from "@radix-ui/react-id";
import * as Label from "@radix-ui/react-label";
import * as PrimitiveSwitch from "@radix-ui/react-switch";
-import { useState } from "react";
+import React, { useState } from "react";
-function classNames(...classes) {
- return classes.filter(Boolean).join(" ");
-}
+import classNames from "@lib/classNames";
-export default function Switch(props) {
+type SwitchProps = React.ComponentProps<typeof PrimitiveSwitch.Root> & {
+ label: string;
+};
+export default function Switch(props: SwitchProps) {
const { label, onCheckedChange, ...primitiveProps } = props;
const [checked, setChecked] = useState(props.defaultChecked || false);
diff --git a/components/webhook/EditWebhook.tsx b/components/webhook/EditWebhook.tsx
deleted file mode 100644
index 5487a5c6342..00000000000
--- a/components/webhook/EditWebhook.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-import { ArrowLeftIcon } from "@heroicons/react/solid";
-import { useEffect, useRef, useState } from "react";
-
-import { useLocale } from "@lib/hooks/useLocale";
-import showToast from "@lib/notification";
-import { Webhook } from "@lib/webhook";
-
-import Button from "@components/ui/Button";
-import Switch from "@components/ui/Switch";
-
-export default function EditTeam(props: { webhook: Webhook; onCloseEdit: () => void }) {
- const { t } = useLocale();
- const [bookingCreated, setBookingCreated] = useState(
- props.webhook.eventTriggers.includes("booking_created")
- );
- const [bookingRescheduled, setBookingRescheduled] = useState(
- props.webhook.eventTriggers.includes("booking_rescheduled")
- );
- const [bookingCancelled, setBookingCancelled] = useState(
- props.webhook.eventTriggers.includes("booking_cancelled")
- );
- const [webhookEnabled, setWebhookEnabled] = useState(props.webhook.active);
- const [webhookEventTrigger, setWebhookEventTriggers] = useState([
- "BOOKING_CREATED",
- "BOOKING_RESCHEDULED",
- "BOOKING_CANCELLED",
- ]);
- const [btnLoading, setBtnLoading] = useState(false);
- const subUrlRef = useRef<HTMLInputElement>() as React.MutableRefObject<HTMLInputElement>;
-
- useEffect(() => {
- const arr = [];
- bookingCreated && arr.push("BOOKING_CREATED");
- bookingRescheduled && arr.push("BOOKING_RESCHEDULED");
- bookingCancelled && arr.push("BOOKING_CANCELLED");
- setWebhookEventTriggers(arr);
- }, [bookingCreated, bookingRescheduled, bookingCancelled, webhookEnabled]);
-
- const handleErrors = async (resp: Response) => {
- if (!resp.ok) {
- const err = await resp.json();
- throw new Error(err.message);
- }
- return resp.json();
- };
-
- const updateWebhookHandler = (event) => {
- event.preventDefault();
- setBtnLoading(true);
- return fetch("/api/webhooks/" + props.webhook.id, {
- method: "PATCH",
- body: JSON.stringify({
- subscriberUrl: subUrlRef.current.value,
- eventTriggers: webhookEventTrigger,
- enabled: webhookEnabled,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- })
- .then(handleErrors)
- .then(() => {
- showToast(t("webhook_updated_successfully"), "success");
- setBtnLoading(false);
- });
- };
-
- return (
- <div className="divide-y divide-gray-200 lg:col-span-9">
- <div className="py-6 lg:pb-8">
- <div className="mb-4">
- <Button
- type="button"
- color="secondary"
- size="sm"
- loading={btnLoading}
- StartIcon={ArrowLeftIcon}
- onClick={() => props.onCloseEdit()}>
- {t("back")}
- </Button>
- </div>
- <div>
- <div className="pb-5 pr-4 sm:pb-6">
- <h3 className="text-lg font-bold leading-6 text-gray-900">{t("manage_your_webhook")}</h3>
- </div>
- </div>
- <hr className="mt-2" />
- <form className="divide-y divide-gray-200 lg:col-span-9" onSubmit={updateWebhookHandler}>
- <div className="my-4">
- <div className="mb-4">
- <label htmlFor="subUrl" className="block text-sm font-medium text-gray-700">
- {t("subscriber_url")}
- </label>
- <input
- ref={subUrlRef}
- type="text"
- name="subUrl"
- id="subUrl"
- defaultValue={props.webhook.subscriberUrl || ""}
- placeholder="https://example.com/sub"
- required
- className="block w-full px-3 py-2 mt-1 border border-gray-300 rounded-sm shadow-sm focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"
- />
- <legend className="block pt-4 mb-2 text-sm font-medium text-gray-700">
- {" "}
- {t("event_triggers")}{" "}
- </legend>
- <div className="p-2 bg-white border border-gray-300 rounded-sm">
- <div className="flex p-2">
- <div className="w-10/12">
- <h2 className="text-sm text-gray-800">{t("booking_created")}</h2>
- </div>
- <div className="flex items-center justify-end w-2/12 text-right">
- <Switch
- defaultChecked={bookingCreated}
- onCheckedChange={() => {
- setBookingCreated(!bookingCreated);
- }}
- />
- </div>
- </div>
- <div className="flex px-2 py-1">
- <div className="w-10/12">
- <h2 className="text-sm text-gray-800">{t("booking_rescheduled")}</h2>
- </div>
- <div className="flex items-center justify-end w-2/12 text-right">
- <Switch
- defaultChecked={bookingRescheduled}
- onCheckedChange={() => {
- setBookingRescheduled(!bookingRescheduled);
- }}
- />
- </div>
- </div>
- <div className="flex p-2">
- <div className="w-10/12">
- <h2 className="text-sm text-gray-800">{t("booking_cancelled")}</h2>
- </div>
- <div className="flex items-center justify-end w-2/12 text-right">
- <Switch
- defaultChecked={bookingCancelled}
- onCheckedChange={() => {
- setBookingCancelled(!bookingCancelled);
- }}
- />
- </div>
- </div>
- </div>
- <legend className="block pt-4 mb-2 text-sm font-medium text-gray-700">
- {" "}
- {t("webhook_status")}{" "}
- </legend>
- <div className="p-2 bg-white border border-gray-300 rounded-sm">
- <div className="flex p-2">
- <div className="w-10/12">
- <h2 className="text-sm text-gray-800">{t("webhook_enabled")}</h2>
- </div>
- <div className="flex items-center justify-end w-2/12 text-right">
- <Switch
- defaultChecked={webhookEnabled}
- onCheckedChange={() => {
- setWebhookEnabled(!webhookEnabled);
- }}
- />
- </div>
- </div>
- </div>
- </div>
- <div className="gap-2 mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
- <Button type="submit" color="primary" className="ml-2" loading={btnLoading}>
- {t("save")}
- </Button>
- </div>
- </div>
- </form>
- </div>
- </div>
- );
-}
diff --git a/components/webhook/WebhookList.tsx b/components/webhook/WebhookList.tsx
deleted file mode 100644
index a046a039b45..00000000000
--- a/components/webhook/WebhookList.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Webhook } from "@lib/webhook";
-
-import WebhookListItem from "./WebhookListItem";
-
-export default function WebhookList(props: {
- webhooks: Webhook[];
- onChange: () => void;
- onEditWebhook: (webhook: Webhook) => void;
-}) {
- return (
- <div>
- <ul className="px-4 mb-2 bg-white border divide-y divide-gray-200 rounded">
- {props.webhooks.map((webhook: Webhook) => (
- <WebhookListItem
- onChange={props.onChange}
- key={webhook.id}
- webhook={webhook}
- onEditWebhook={() => props.onEditWebhook(webhook)}></WebhookListItem>
- ))}
- </ul>
- </div>
- );
-}
diff --git a/components/webhook/WebhookListItem.tsx b/components/webhook/WebhookListItem.tsx
deleted file mode 100644
index 9f64837a5c8..00000000000
--- a/components/webhook/WebhookListItem.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import { TrashIcon, PencilAltIcon } from "@heroicons/react/outline";
-
-import { useLocale } from "@lib/hooks/useLocale";
-import showToast from "@lib/notification";
-import { Webhook } from "@lib/webhook";
-
-import { Dialog, DialogTrigger } from "@components/Dialog";
-import { Tooltip } from "@components/Tooltip";
-import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";
-import Button from "@components/ui/Button";
-
-export default function WebhookListItem(props: {
- onChange: () => void;
- key: string;
- webhook: Webhook;
- onEditWebhook: () => void;
-}) {
- const { t } = useLocale();
- const handleErrors = async (resp: Response) => {
- if (!resp.ok) {
- const err = await resp.json();
- throw new Error(err.message);
- }
- return resp.json();
- };
-
- const deleteWebhook = (webhookId: string) => {
- fetch("/api/webhooks/" + webhookId, {
- method: "DELETE",
- headers: {
- "Content-Type": "application/json",
- },
- })
- .then(handleErrors)
- .then(() => {
- showToast(t("webhook_removed_successfully"), "success");
- props.onChange();
- });
- };
-
- return (
- <li className="divide-y">
- <div className="flex justify-between my-4">
- <div className="flex pr-2 border-r border-gray-100">
- <span className="flex flex-col space-y-2 text-xs">
- {props.webhook.eventTriggers.map((eventTrigger, ind) => (
- <span key={ind} className="px-1 text-xs text-blue-700 rounded-md w-max bg-blue-50">
- {t(`${eventTrigger}`)}
- </span>
- ))}
- </span>
- </div>
- <div className="flex w-full">
- <div className="self-center inline-block ml-3 space-y-1">
- <span className="flex text-sm text-neutral-700">{props.webhook.subscriberUrl}</span>
- </div>
- </div>
- <div className="flex">
- {!props.webhook.active && (
- <span className="self-center h-6 px-3 py-1 text-xs text-red-700 capitalize rounded-md bg-red-50">
- {t("disabled")}
- </span>
- )}
- {!!props.webhook.active && (
- <span className="self-center h-6 px-3 py-1 text-xs text-green-700 capitalize rounded-md bg-green-50">
- {t("enabled")}
- </span>
- )}
-
- <Tooltip content={t("edit_webhook")}>
- <Button
- onClick={() => props.onEditWebhook()}
- color="minimal"
- size="icon"
- StartIcon={PencilAltIcon}
- className="self-center w-full p-2 ml-4"></Button>
- </Tooltip>
- <Dialog>
- <Tooltip content={t("delete_webhook")}>
- <DialogTrigger asChild>
- <Button
- onClick={(e) => {
- e.stopPropagation();
- }}
- color="minimal"
- size="icon"
- StartIcon={TrashIcon}
- className="self-center w-full p-2 ml-2"></Button>
- </DialogTrigger>
- </Tooltip>
- <ConfirmationDialogContent
- variety="danger"
- title={t("delete_webhook")}
- confirmBtnText={t("confirm_delete_webhook")}
- cancelBtnText={t("cancel")}
- onConfirm={() => {
- deleteWebhook(props.webhook.id);
- }}>
- {t("delete_webhook_confirmation_message")}
- </ConfirmationDialogContent>
- </Dialog>
- </div>
- </div>
- </li>
- );
-}
diff --git a/package.json b/package.json
index 4c965bab58b..19c189ebf53 100644
--- a/package.json
+++ b/package.json
@@ -77,7 +77,7 @@
"react": "17.0.2",
"react-dom": "17.0.2",
"react-easy-crop": "^3.5.2",
- "react-hook-form": "^7.16.1",
+ "react-hook-form": "^7.17.4",
"react-hot-toast": "^2.1.0",
"react-intl": "^5.20.7",
"react-multi-email": "^0.5.3",
diff --git a/pages/integrations/embed.tsx b/pages/integrations/embed.tsx
deleted file mode 100644
index ca1504a2555..00000000000
--- a/pages/integrations/embed.tsx
+++ /dev/null
@@ -1,285 +0,0 @@
-import { useSession } from "next-auth/client";
-import Image from "next/image";
-import { useEffect, useRef, useState } from "react";
-
-import classNames from "@lib/classNames";
-import { useLocale } from "@lib/hooks/useLocale";
-import { trpc } from "@lib/trpc";
-import { Webhook } from "@lib/webhook";
-
-import { Dialog, DialogClose, DialogContent, DialogHeader, DialogTrigger } from "@components/Dialog";
-import { List, ListItem, ListItemText, ListItemTitle } from "@components/List";
-import Loader from "@components/Loader";
-import { ShellSubHeading } from "@components/Shell";
-import Button from "@components/ui/Button";
-import Switch from "@components/ui/Switch";
-import EditWebhook from "@components/webhook/EditWebhook";
-import WebhookList from "@components/webhook/WebhookList";
-
-export default function Embed() {
- const user = trpc.useQuery(["viewer.me"]).data;
- const [, loading] = useSession();
- const { t } = useLocale();
-
- const [isLoading, setLoading] = useState(false);
- const [bookingCreated, setBookingCreated] = useState(true);
- const [bookingRescheduled, setBookingRescheduled] = useState(true);
- const [bookingCancelled, setBookingCancelled] = useState(true);
- const [editWebhookEnabled, setEditWebhookEnabled] = useState(false);
- const [webhooks, setWebhooks] = useState([]);
- const [webhookToEdit, setWebhookToEdit] = useState<Webhook | null>();
- const [webhookEventTrigger, setWebhookEventTriggers] = useState([
- "BOOKING_CREATED",
- "BOOKING_RESCHEDULED",
- "BOOKING_CANCELLED",
- ]);
-
- const subUrlRef = useRef<HTMLInputElement>() as React.MutableRefObject<HTMLInputElement>;
-
- useEffect(() => {
- const arr = [];
- bookingCreated && arr.push("BOOKING_CREATED");
- bookingRescheduled && arr.push("BOOKING_RESCHEDULED");
- bookingCancelled && arr.push("BOOKING_CANCELLED");
- setWebhookEventTriggers(arr);
- }, [bookingCreated, bookingRescheduled, bookingCancelled]);
-
- useEffect(() => {
- getWebhooks();
- }, []);
-
- const iframeTemplate = `<iframe src="${process.env.NEXT_PUBLIC_BASE_URL}/${user?.username}" frameborder="0" allowfullscreen></iframe>`;
- const htmlTemplate = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>${t(
- "schedule_a_meeting"
- )}</title><style>body {margin: 0;}iframe {height: calc(100vh - 4px);width: calc(100vw - 4px);box-sizing: border-box;}</style></head><body>${iframeTemplate}</body></html>`;
- const handleErrors = async (resp: Response) => {
- if (!resp.ok) {
- const err = await resp.json();
- throw new Error(err.message);
- }
- return resp.json();
- };
-
- const getWebhooks = () => {
- fetch("/api/webhook")
- .then(handleErrors)
- .then((data) => {
- setWebhooks(
- data.webhooks.map((webhook: Webhook) => {
- return {
- ...webhook,
- eventTriggers: webhook.eventTriggers.map((eventTrigger: string) => eventTrigger.toLowerCase()),
- };
- })
- );
- console.log(data.webhooks);
- })
- .catch(console.log);
- setLoading(false);
- };
-
- const createWebhook = () => {
- setLoading(true);
- fetch("/api/webhook", {
- method: "POST",
- body: JSON.stringify({
- subscriberUrl: subUrlRef.current.value,
- eventTriggers: webhookEventTrigger,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- })
- .then(getWebhooks)
- .catch(console.log);
- };
-
- const editWebhook = (webhook: Webhook) => {
- setEditWebhookEnabled(true);
- setWebhookToEdit(webhook);
- };
-
- const onCloseEdit = () => {
- getWebhooks();
- setEditWebhookEnabled(false);
- };
-
- if (loading) {
- return <Loader />;
- }
-
- return (
- <>
- {!editWebhookEnabled && (
- <>
- <ShellSubHeading className="mt-10" title={t("Webhooks")} subtitle={t("receive_cal_meeting_data")} />
- <List>
- <ListItem className={classNames("flex-col")}>
- <div className={classNames("flex flex-1 space-x-2 w-full p-3 items-center")}>
- <Image width={40} height={40} src="/integrations/webhooks.svg" alt="Webhooks" />
- <div className="flex-grow pl-2 truncate">
- <ListItemTitle component="h3">Webhooks</ListItemTitle>
- <ListItemText component="p">Automation</ListItemText>
- </div>
- <div>
- <Dialog>
- <DialogTrigger>
- <Button color="secondary">{t("new_webhook")}</Button>
- </DialogTrigger>
- <DialogContent>
- <DialogHeader
- title={t("create_new_webhook")}
- subtitle={t("create_new_webhook_to_account")}
- />
- <div className="my-4">
- <div className="mb-4">
- <label htmlFor="subUrl" className="block text-sm font-medium text-gray-700">
- {t("subscriber_url")}
- </label>
- <input
- ref={subUrlRef}
- type="text"
- name="subUrl"
- id="subUrl"
- placeholder="https://example.com/sub"
- required
- className="block w-full px-3 py-2 mt-1 border border-gray-300 rounded-sm shadow-sm focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"
- />
- <legend className="block pt-4 mb-2 text-sm font-medium text-gray-700">
- {" "}
- {t("event_triggers")}{" "}
- </legend>
- <div className="p-2 border border-gray-300 rounded-sm">
- <div className="flex pb-4">
- <div className="w-10/12">
- <h2 className="font-medium text-gray-800">{t("booking_created")}</h2>
- </div>
- <div className="flex items-center justify-center w-2/12 text-right">
- <Switch
- defaultChecked={true}
- id="booking-created"
- value={bookingCreated}
- onCheckedChange={() => {
- setBookingCreated(!bookingCreated);
- }}
- />
- </div>
- </div>
- <div className="flex py-1">
- <div className="w-10/12">
- <h2 className="font-medium text-gray-800">{t("booking_rescheduled")}</h2>
- </div>
- <div className="flex items-center justify-center w-2/12 text-right">
- <Switch
- defaultChecked={true}
- id="booking-rescheduled"
- value={bookingRescheduled}
- onCheckedChange={() => {
- setBookingRescheduled(!bookingRescheduled);
- }}
- />
- </div>
- </div>
- <div className="flex pt-4">
- <div className="w-10/12">
- <h2 className="font-medium text-gray-800">{t("booking_cancelled")}</h2>
- </div>
- <div className="flex items-center justify-center w-2/12 text-right">
- <Switch
- defaultChecked={true}
- id="booking-cancelled"
- value={bookingCancelled}
- onCheckedChange={() => {
- setBookingCancelled(!bookingCancelled);
- }}
- />
- </div>
- </div>
- </div>
- </div>
- <div className="gap-2 mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
- <DialogClose asChild>
- <Button
- type="button"
- loading={isLoading}
- onClick={createWebhook}
- color="primary"
- className="ml-2">
- {t("create_webhook")}
- </Button>
- </DialogClose>
- <DialogClose asChild>
- <Button color="secondary">{t("cancel")}</Button>
- </DialogClose>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- </div>
- </div>
- </ListItem>
- </List>
-
- <div className="divide-y divide-gray-200 lg:col-span-9">
- <div className="py-6 lg:pb-8">
- <div>
- {!!webhooks.length && (
- <WebhookList
- webhooks={webhooks}
- onChange={getWebhooks}
- onEditWebhook={editWebhook}></WebhookList>
- )}
- </div>
- </div>
- </div>
-
- <ShellSubHeading className="mt-10" title={t("iframe_embed")} subtitle={t("embed_calcom")} />
- <div className="py-6 lg:pb-8 lg:col-span-9">
- <div className="mb-6">
- <h2 className="text-lg font-medium leading-6 text-gray-900 font-cal"></h2>
- <p className="mt-1 text-sm text-gray-500"></p>
- </div>
- <div className="grid grid-cols-2 space-x-4">
- <div>
- <label htmlFor="iframe" className="block text-sm font-medium text-gray-700">
- {t("standard_iframe")}
- </label>
- <div className="mt-1">
- <textarea
- id="iframe"
- className="block w-full h-32 border-gray-300 rounded-sm shadow-sm focus:ring-black focus:border-black sm:text-sm"
- placeholder={t("loading")}
- defaultValue={iframeTemplate}
- readOnly
- />
- </div>
- </div>
- <div>
- <label htmlFor="fullscreen" className="block text-sm font-medium text-gray-700">
- {t("responsive_fullscreen_iframe")}
- </label>
- <div className="mt-1">
- <textarea
- id="fullscreen"
- className="block w-full h-32 border-gray-300 rounded-sm shadow-sm focus:ring-black focus:border-black sm:text-sm"
- placeholder={t("loading")}
- defaultValue={htmlTemplate}
- readOnly
- />
- </div>
- </div>
- </div>
-
- <ShellSubHeading className="mt-10" title="Cal.com API" subtitle={t("leverage_our_api")} />
- <a href="https://developer.cal.com/api" className="btn btn-primary">
- {t("browse_api_documentation")}
- </a>
- </div>
- </>
- )}
- {!!editWebhookEnabled && webhookToEdit && (
- <EditWebhook webhook={webhookToEdit} onCloseEdit={onCloseEdit} />
- )}
- </>
- );
-}
diff --git a/pages/integrations/index.tsx b/pages/integrations/index.tsx
index 31ec3c14136..ffdd113b4ac 100644
--- a/pages/integrations/index.tsx
+++ b/pages/integrations/index.tsx
@@ -1,25 +1,31 @@
+import { PencilAltIcon, TrashIcon } from "@heroicons/react/outline";
+import { WebhookTriggerEvents } from "@prisma/client";
import Image from "next/image";
+import { getErrorFromUnknown } from "pages/_error";
import { Fragment, ReactNode, useState } from "react";
+import { Controller, useForm } from "react-hook-form";
import { useMutation } from "react-query";
import { QueryCell } from "@lib/QueryCell";
import classNames from "@lib/classNames";
+import * as fetcher from "@lib/core/http/fetch-wrapper";
+import { useLocale } from "@lib/hooks/useLocale";
import { AddAppleIntegrationModal } from "@lib/integrations/Apple/components/AddAppleIntegration";
import { AddCalDavIntegrationModal } from "@lib/integrations/CalDav/components/AddCalDavIntegration";
import showToast from "@lib/notification";
-import { trpc } from "@lib/trpc";
+import { inferQueryOutput, trpc } from "@lib/trpc";
-import { Dialog } from "@components/Dialog";
+import { Dialog, DialogContent, DialogFooter, DialogTrigger } from "@components/Dialog";
import { List, ListItem, ListItemText, ListItemTitle } from "@components/List";
import Shell, { ShellSubHeading } from "@components/Shell";
+import { Tooltip } from "@components/Tooltip";
import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";
+import { FieldsetLegend, Form, InputGroupBox, TextField } from "@components/form/fields";
import { Alert } from "@components/ui/Alert";
import Badge from "@components/ui/Badge";
import Button, { ButtonBaseProps } from "@components/ui/Button";
import Switch from "@components/ui/Switch";
-import Embed from "./embed";
-
function pluralize(opts: { num: number; plural: string; singular: string }) {
if (opts.num === 0) {
return opts.singular;
@@ -27,6 +33,321 @@ function pluralize(opts: { num: number; plural: string; singular: string }) {
return opts.singular;
}
+type TIntegrations = inferQueryOutput<"viewer.integrations">;
+type TWebhook = TIntegrations["webhooks"][number];
+
+const ALL_TRIGGERS: WebhookTriggerEvents[] = [
+ //
+ "BOOKING_CREATED",
+ "BOOKING_RESCHEDULED",
+ "BOOKING_CANCELLED",
+];
+function WebhookListItem(props: { webhook: TWebhook; onEditWebhook: () => void }) {
+ const { t } = useLocale();
+ const utils = trpc.useContext();
+ const deleteWebhook = useMutation(async () => fetcher.remove(`/api/webhooks/${props.webhook.id}`, null), {
+ async onSuccess() {
+ await utils.invalidateQueries(["viewer.integrations"]);
+ },
+ });
+
+ return (
+ <ListItem className="p-4 flex w-full">
+ <div className="flex w-full justify-between my-4">
+ <div className="flex pr-2 border-r border-gray-100">
+ <span className="flex flex-col space-y-2 text-xs">
+ {props.webhook.eventTriggers.map((eventTrigger, ind) => (
+ <span key={ind} className="px-1 text-xs text-blue-700 rounded-md w-max bg-blue-50">
+ {t(`${eventTrigger.toLowerCase()}`)}
+ </span>
+ ))}
+ </span>
+ </div>
+ <div className="flex w-full">
+ <div className="self-center inline-block ml-3 space-y-1">
+ <span className="flex text-sm text-neutral-700">{props.webhook.subscriberUrl}</span>
+ </div>
+ </div>
+ <div className="flex">
+ {!props.webhook.active && (
+ <span className="self-center h-6 px-3 py-1 text-xs text-red-700 capitalize rounded-md bg-red-50">
+ {t("disabled")}
+ </span>
+ )}
+ {!!props.webhook.active && (
+ <span className="self-center h-6 px-3 py-1 text-xs text-green-700 capitalize rounded-md bg-green-50">
+ {t("enabled")}
+ </span>
+ )}
+
+ <Tooltip content={t("edit_webhook")}>
+ <Button
+ onClick={() => props.onEditWebhook()}
+ color="minimal"
+ size="icon"
+ StartIcon={PencilAltIcon}
+ className="self-center w-full p-2 ml-4"></Button>
+ </Tooltip>
+ <Dialog>
+ <Tooltip content={t("delete_webhook")}>
+ <DialogTrigger asChild>
+ <Button
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ color="minimal"
+ size="icon"
+ StartIcon={TrashIcon}
+ className="self-center w-full p-2 ml-2"></Button>
+ </DialogTrigger>
+ </Tooltip>
+ <ConfirmationDialogContent
+ variety="danger"
+ title={t("delete_webhook")}
+ confirmBtnText={t("confirm_delete_webhook")}
+ cancelBtnText={t("cancel")}
+ onConfirm={() => deleteWebhook.mutate()}>
+ {t("delete_webhook_confirmation_message")}
+ </ConfirmationDialogContent>
+ </Dialog>
+ </div>
+ </div>
+ </ListItem>
+ );
+}
+
+function WebhookDialogForm(props: {
+ //
+ defaultValues?: TWebhook;
+ handleClose: () => void;
+}) {
+ const { t } = useLocale();
+
+ const utils = trpc.useContext();
+ const {
+ defaultValues = {
+ id: "",
+ eventTriggers: ALL_TRIGGERS,
+ subscriberUrl: "",
+ active: true,
+ },
+ } = props;
+
+ const form = useForm({
+ defaultValues,
+ });
+ return (
+ <Form
+ form={form}
+ onSubmit={(event) => {
+ form
+ .handleSubmit(async (values) => {
+ const { id } = values;
+ const body = {
+ subscriberUrl: values.subscriberUrl,
+ enabled: values.active,
+ eventTriggers: values.eventTriggers,
+ };
+ if (id) {
+ await fetcher.patch(`/api/webhooks/${id}`, body);
+ await utils.invalidateQueries(["viewer.integrations"]);
+ showToast(t("webhook_updated_successfully"), "success");
+ } else {
+ await fetcher.post("/api/webhook", body);
+ await utils.invalidateQueries(["viewer.integrations"]);
+ showToast(t("webhook_created_successfully"), "success");
+ }
+
+ props.handleClose();
+ })(event)
+ .catch((err) => {
+ showToast(`${getErrorFromUnknown(err).message}`, "error");
+ });
+ }}
+ className="space-y-4">
+ <input type="hidden" {...form.register("id")} />
+ <TextField label={t("subscriber_url")} {...form.register("subscriberUrl")} required type="url" />
+
+ <fieldset className="space-y-2">
+ <FieldsetLegend>{t("event_triggers")}</FieldsetLegend>
+ <InputGroupBox>
+ {ALL_TRIGGERS.map((key) => (
+ <Controller
+ key={key}
+ control={form.control}
+ name="eventTriggers"
+ render={({ field }) => (
+ <Switch
+ label={t(key.toLowerCase())}
+ defaultChecked={field.value.includes(key)}
+ onCheckedChange={(isChecked) => {
+ const value = field.value;
+ const newValue = isChecked ? [...value, key] : value.filter((v) => v !== key);
+
+ form.setValue("eventTriggers", newValue, {
+ shouldDirty: true,
+ });
+ }}
+ />
+ )}
+ />
+ ))}
+ </InputGroupBox>
+ </fieldset>
+ <fieldset className="space-y-2">
+ <FieldsetLegend>{t("webhook_status")}</FieldsetLegend>
+ <InputGroupBox>
+ <Controller
+ control={form.control}
+ name="active"
+ render={({ field }) => (
+ <Switch
+ label={t("webhook_enabled")}
+ defaultChecked={field.value}
+ onCheckedChange={(isChecked) => {
+ form.setValue("active", isChecked);
+ }}
+ />
+ )}
+ />
+ </InputGroupBox>
+ </fieldset>
+ <DialogFooter>
+ <Button type="button" color="secondary" onClick={props.handleClose} tabIndex={-1}>
+ {t("cancel")}
+ </Button>
+ <Button type="submit" loading={form.formState.isSubmitting}>
+ {t("save")}
+ </Button>
+ </DialogFooter>
+ </Form>
+ );
+}
+
+function WebhookEmbed(props: { webhooks: TWebhook[] }) {
+ const { t } = useLocale();
+ const user = trpc.useQuery(["viewer.me"]).data;
+
+ const iframeTemplate = `<iframe src="${process.env.NEXT_PUBLIC_BASE_URL}/${user?.username}" frameborder="0" allowfullscreen></iframe>`;
+ const htmlTemplate = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>${t(
+ "schedule_a_meeting"
+ )}</title><style>body {margin: 0;}iframe {height: calc(100vh - 4px);width: calc(100vw - 4px);box-sizing: border-box;}</style></head><body>${iframeTemplate}</body></html>`;
+
+ const [newWebhookModal, setNewWebhookModal] = useState(false);
+ const [editModalOpen, setEditModalOpen] = useState(false);
+ const [editing, setEditing] = useState<TWebhook | null>(null);
+ return (
+ <>
+ <ShellSubHeading className="mt-10" title={t("Webhooks")} subtitle={t("receive_cal_meeting_data")} />
+ <List>
+ <ListItem className={classNames("flex-col")}>
+ <div className={classNames("flex flex-1 space-x-2 w-full p-3 items-center")}>
+ <Image width={40} height={40} src="/integrations/webhooks.svg" alt="Webhooks" />
+ <div className="flex-grow pl-2 truncate">
+ <ListItemTitle component="h3">Webhooks</ListItemTitle>
+ <ListItemText component="p">Automation</ListItemText>
+ </div>
+ <div>
+ <Button color="secondary" onClick={() => setNewWebhookModal(true)}>
+ {t("new_webhook")}
+ </Button>
+ </div>
+ </div>
+ </ListItem>
+ </List>
+
+ {props.webhooks.length ? (
+ <List>
+ {props.webhooks.map((item) => (
+ <WebhookListItem
+ key={item.id}
+ webhook={item}
+ onEditWebhook={() => {
+ setEditing(item);
+ setEditModalOpen(true);
+ }}
+ />
+ ))}
+ </List>
+ ) : null}
+ <div className="divide-y divide-gray-200 lg:col-span-9">
+ <div className="py-6 lg:pb-8">
+ <div>
+ {/* {!!props.webhooks.length && (
+ <WebhookList
+ webhooks={props.webhooks}
+ onChange={() => {}}
+ onEditWebhook={editWebhook}></WebhookList>
+ )} */}
+ </div>
+ </div>
+ </div>
+
+ <ShellSubHeading className="mt-10" title={t("iframe_embed")} subtitle={t("embed_calcom")} />
+ <div className="py-6 lg:pb-8 lg:col-span-9">
+ <div className="mb-6">
+ <h2 className="text-lg font-medium leading-6 text-gray-900 font-cal"></h2>
+ <p className="mt-1 text-sm text-gray-500"></p>
+ </div>
+ <div className="grid grid-cols-2 space-x-4">
+ <div>
+ <label htmlFor="iframe" className="block text-sm font-medium text-gray-700">
+ {t("standard_iframe")}
+ </label>
+ <div className="mt-1">
+ <textarea
+ id="iframe"
+ className="block w-full h-32 border-gray-300 rounded-sm shadow-sm focus:ring-black focus:border-black sm:text-sm"
+ placeholder={t("loading")}
+ defaultValue={iframeTemplate}
+ readOnly
+ />
+ </div>
+ </div>
+ <div>
+ <label htmlFor="fullscreen" className="block text-sm font-medium text-gray-700">
+ {t("responsive_fullscreen_iframe")}
+ </label>
+ <div className="mt-1">
+ <textarea
+ id="fullscreen"
+ className="block w-full h-32 border-gray-300 rounded-sm shadow-sm focus:ring-black focus:border-black sm:text-sm"
+ placeholder={t("loading")}
+ defaultValue={htmlTemplate}
+ readOnly
+ />
+ </div>
+ </div>
+ </div>
+
+ <ShellSubHeading className="mt-10" title="Cal.com API" subtitle={t("leverage_our_api")} />
+ <a href="https://developer.cal.com/api" className="btn btn-primary">
+ {t("browse_api_documentation")}
+ </a>
+ </div>
+
+ {/* New webhook dialog */}
+ <Dialog open={newWebhookModal} onOpenChange={(isOpen) => !isOpen && setNewWebhookModal(false)}>
+ <DialogContent>
+ <WebhookDialogForm handleClose={() => setNewWebhookModal(false)} />
+ </DialogContent>
+ </Dialog>
+ {/* Edit webhook dialog */}
+ <Dialog open={editModalOpen} onOpenChange={(isOpen) => !isOpen && setEditModalOpen(false)}>
+ <DialogContent>
+ {editing && (
+ <WebhookDialogForm
+ key={editing.id}
+ handleClose={() => setEditModalOpen(false)}
+ defaultValues={editing}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
+
function SubHeadingTitleWithConnections(props: { title: ReactNode; numConnections?: number }) {
const num = props.numConnections;
return (
@@ -423,12 +744,11 @@ export default function IntegrationsPage() {
/>
))}
</List>
+ <WebhookEmbed webhooks={data.webhooks} />
</>
);
}}
/>
-
- <Embed />
</Shell>
);
}
diff --git a/public/static/locales/en/common.json b/public/static/locales/en/common.json
index a39e5eca0b9..a0c07c4c793 100644
--- a/public/static/locales/en/common.json
+++ b/public/static/locales/en/common.json
@@ -6,6 +6,7 @@
"webhook_status": "Webhook Status",
"webhook_enabled": "Webhook Enabled",
"manage_your_webhook": "Manage your webhook",
+ "webhook_created_successfully": "Webhook created successfully!",
"webhook_updated_successfully": "Webhook updated successfully!",
"webhook_removed_successfully": "Webhook removed successfully!",
"dismiss": "Dismiss",
diff --git a/server/createContext.ts b/server/createContext.ts
index e07fd6a80e8..89131a2f062 100644
--- a/server/createContext.ts
+++ b/server/createContext.ts
@@ -34,6 +34,7 @@ async function getUserFromSession({ session, req }: { session: Maybe<Session>; r
createdDate: true,
hideBranding: true,
avatar: true,
+ twoFactorEnabled: true,
credentials: {
select: {
id: true,
diff --git a/server/routers/viewer.tsx b/server/routers/viewer.tsx
index e58451f3df8..a9e60f0e9a5 100644
--- a/server/routers/viewer.tsx
+++ b/server/routers/viewer.tsx
@@ -139,7 +139,9 @@ const loggedInViewerRouter = createProtectedRouter()
},
});
- if (!user) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
+ if (!user) {
+ throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
+ }
// backwards compatibility, TMP:
const typesRaw = await prisma.eventType.findMany({
@@ -363,6 +365,12 @@ const loggedInViewerRouter = createProtectedRouter()
}
})
);
+
+ const webhooks = await ctx.prisma.webhook.findMany({
+ where: {
+ userId: user.id,
+ },
+ });
return {
conferencing: {
items: conferencing,
@@ -377,6 +385,7 @@ const loggedInViewerRouter = createProtectedRouter()
numActive: countActive(payment),
},
connectedCalendars,
+ webhooks,
};
},
})
diff --git a/yarn.lock b/yarn.lock
index e3910ed2950..db68479b35c 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -6752,10 +6752,10 @@ react-fit@^1.0.3:
detect-element-overflow "^1.2.0"
prop-types "^15.6.0"
-react-hook-form@^7.16.1:
- version "7.16.1"
- resolved "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.16.1.tgz#669046df378a71949e5cf8a2398cbe20d5cb27bc"
- integrity sha512-kcLDmSmlyLUFx2UU5bG/o4+3NeK753fhKodJa8gkplXohGkpAq0/p+TR24OWjZmkEc3ES7ppC5v5d6KUk+fJTA==
+react-hook-form@^7.17.4:
+ version "7.17.4"
+ resolved "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.17.4.tgz#232b6aaccddb91eb4a228ac20b154abd90866fdb"
+ integrity sha512-7XhbCr7d9fDC1TgcK/BUbt7D3q0VJMu7jPErfsa0JrxVjv/nni41xWdJcy0Zb7R+Np8OsCkQ2lMyloAtE3DLiQ==
react-hot-toast@^2.1.0:
version "2.1.1"