Skip to content

Scheduling infrastructure for absolutely everyone.

Revert "Revert "Webhooks to support event type association"" (#2033)

Omar López382d56ab5412
diff --git a/apps/web/components/webhook/WebhookDialogForm.tsx b/apps/web/components/webhook/WebhookDialogForm.tsx
new file mode 100644
index 00000000000..bbbc0182415
--- /dev/null
+++ b/apps/web/components/webhook/WebhookDialogForm.tsx
@@ -0,0 +1,162 @@
+import { useState } from "react";
+import { Controller, useForm } from "react-hook-form";
+
+import { useLocale } from "@lib/hooks/useLocale";
+import showToast from "@lib/notification";
+import { trpc } from "@lib/trpc";
+import { WEBHOOK_TRIGGER_EVENTS } from "@lib/webhooks/constants";
+import customTemplate, { hasTemplateIntegration } from "@lib/webhooks/integrationTemplate";
+
+import { DialogFooter } from "@components/Dialog";
+import { FieldsetLegend, Form, InputGroupBox, TextArea, TextField } from "@components/form/fields";
+import Button from "@components/ui/Button";
+import Switch from "@components/ui/Switch";
+import { TWebhook } from "@components/webhook/WebhookListItem";
+import WebhookTestDisclosure from "@components/webhook/WebhookTestDisclosure";
+
+export default function WebhookDialogForm(props: {
+ eventTypeId?: number;
+ defaultValues?: TWebhook;
+ handleClose: () => void;
+}) {
+ const { t } = useLocale();
+ const utils = trpc.useContext();
+ const handleSubscriberUrlChange = (e) => {
+ form.setValue("subscriberUrl", e.target.value);
+ if (hasTemplateIntegration({ url: e.target.value })) {
+ setUseCustomPayloadTemplate(true);
+ form.setValue("payloadTemplate", customTemplate({ url: e.target.value }));
+ }
+ };
+ const {
+ defaultValues = {
+ id: "",
+ eventTriggers: WEBHOOK_TRIGGER_EVENTS,
+ subscriberUrl: "",
+ active: true,
+ payloadTemplate: null,
+ } as Omit<TWebhook, "userId" | "createdAt" | "eventTypeId">,
+ } = props;
+
+ const [useCustomPayloadTemplate, setUseCustomPayloadTemplate] = useState(!!defaultValues.payloadTemplate);
+
+ const form = useForm({
+ defaultValues,
+ });
+ return (
+ <Form
+ data-testid="WebhookDialogForm"
+ form={form}
+ handleSubmit={async (event) => {
+ const e = { ...event, eventTypeId: props.eventTypeId };
+ if (!useCustomPayloadTemplate && event.payloadTemplate) {
+ event.payloadTemplate = null;
+ }
+ if (event.id) {
+ await utils.client.mutation("viewer.webhook.edit", e);
+ await utils.invalidateQueries(["viewer.webhook.list"]);
+ showToast(t("webhook_updated_successfully"), "success");
+ } else {
+ await utils.client.mutation("viewer.webhook.create", e);
+ await utils.invalidateQueries(["viewer.webhook.list"]);
+ showToast(t("webhook_created_successfully"), "success");
+ }
+ props.handleClose();
+ }}
+ className="space-y-4">
+ <input type="hidden" {...form.register("id")} />
+ <fieldset className="space-y-2">
+ <InputGroupBox className="border-0 bg-gray-50">
+ <Controller
+ control={form.control}
+ name="active"
+ render={({ field }) => (
+ <Switch
+ label={field.value ? t("webhook_enabled") : t("webhook_disabled")}
+ defaultChecked={field.value}
+ onCheckedChange={(isChecked) => {
+ form.setValue("active", isChecked);
+ }}
+ />
+ )}
+ />
+ </InputGroupBox>
+ </fieldset>
+ <TextField
+ label={t("subscriber_url")}
+ {...form.register("subscriberUrl")}
+ required
+ type="url"
+ onChange={handleSubscriberUrlChange}
+ />
+
+ <fieldset className="space-y-2">
+ <FieldsetLegend>{t("event_triggers")}</FieldsetLegend>
+ <InputGroupBox className="border-0 bg-gray-50">
+ {WEBHOOK_TRIGGER_EVENTS.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("payload_template")}</FieldsetLegend>
+ <div className="space-x-3 text-sm rtl:space-x-reverse">
+ <label>
+ <input
+ className="text-neutral-900 focus:ring-neutral-500"
+ type="radio"
+ name="useCustomPayloadTemplate"
+ onChange={(value) => setUseCustomPayloadTemplate(!value.target.checked)}
+ defaultChecked={!useCustomPayloadTemplate}
+ />{" "}
+ Default
+ </label>
+ <label>
+ <input
+ className="text-neutral-900 focus:ring-neutral-500"
+ onChange={(value) => setUseCustomPayloadTemplate(value.target.checked)}
+ name="useCustomPayloadTemplate"
+ type="radio"
+ defaultChecked={useCustomPayloadTemplate}
+ />{" "}
+ Custom
+ </label>
+ </div>
+ {useCustomPayloadTemplate && (
+ <TextArea
+ {...form.register("payloadTemplate")}
+ defaultValue={useCustomPayloadTemplate && (defaultValues.payloadTemplate || "")}
+ rows={3}
+ />
+ )}
+ </fieldset>
+ <WebhookTestDisclosure />
+ <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>
+ );
+}
diff --git a/apps/web/components/webhook/WebhookListContainer.tsx b/apps/web/components/webhook/WebhookListContainer.tsx
new file mode 100644
index 00000000000..253a16187ee
--- /dev/null
+++ b/apps/web/components/webhook/WebhookListContainer.tsx
@@ -0,0 +1,105 @@
+import classNames from "classnames";
+import Image from "next/image";
+import { useState } from "react";
+
+import { QueryCell } from "@lib/QueryCell";
+import { useLocale } from "@lib/hooks/useLocale";
+import { trpc } from "@lib/trpc";
+
+import { Dialog, DialogContent } from "@components/Dialog";
+import { List, ListItem, ListItemText, ListItemTitle } from "@components/List";
+import { ShellSubHeading } from "@components/Shell";
+import Button from "@components/ui/Button";
+import WebhookDialogForm from "@components/webhook/WebhookDialogForm";
+import WebhookListItem, { TWebhook } from "@components/webhook/WebhookListItem";
+
+export type WebhookListContainerType = {
+ eventTypeId?: number;
+};
+
+export default function WebhookListContainer(props: WebhookListContainerType) {
+ const { t } = useLocale();
+ const query = props.eventTypeId
+ ? trpc.useQuery(["viewer.webhook.list", { eventTypeId: props.eventTypeId }], {
+ suspense: true,
+ })
+ : trpc.useQuery(["viewer.webhook.list"], {
+ suspense: true,
+ });
+
+ const [newWebhookModal, setNewWebhookModal] = useState(false);
+ const [editModalOpen, setEditModalOpen] = useState(false);
+ const [editing, setEditing] = useState<TWebhook | null>(null);
+ return (
+ <QueryCell
+ query={query}
+ success={({ data }) => (
+ <>
+ <ShellSubHeading
+ className="mt-10"
+ title={t("Team Webhooks")}
+ subtitle={t("receive_cal_event_meeting_data")}
+ />
+ <List>
+ <ListItem className={classNames("flex-col")}>
+ <div
+ className={classNames("flex w-full flex-1 items-center space-x-2 p-3 rtl:space-x-reverse")}>
+ <Image width={40} height={40} src="/integrations/webhooks.svg" alt="Webhooks" />
+ <div className="flex-grow truncate pl-2">
+ <ListItemTitle component="h3">Webhooks</ListItemTitle>
+ <ListItemText component="p">{t("automation")}</ListItemText>
+ </div>
+ <div>
+ <Button
+ color="secondary"
+ onClick={() => setNewWebhookModal(true)}
+ data-testid="new_webhook">
+ {t("new_webhook")}
+ </Button>
+ </div>
+ </div>
+ </ListItem>
+ </List>
+
+ {data.length ? (
+ <List>
+ {data.map((item) => (
+ <WebhookListItem
+ key={item.id}
+ webhook={item}
+ onEditWebhook={() => {
+ setEditing(item);
+ setEditModalOpen(true);
+ }}
+ />
+ ))}
+ </List>
+ ) : null}
+
+ {/* New webhook dialog */}
+ <Dialog open={newWebhookModal} onOpenChange={(isOpen) => !isOpen && setNewWebhookModal(false)}>
+ <DialogContent>
+ <WebhookDialogForm
+ eventTypeId={props.eventTypeId}
+ handleClose={() => setNewWebhookModal(false)}
+ />
+ </DialogContent>
+ </Dialog>
+ {/* Edit webhook dialog */}
+ <Dialog open={editModalOpen} onOpenChange={(isOpen) => !isOpen && setEditModalOpen(false)}>
+ <DialogContent>
+ {editing && (
+ <WebhookDialogForm
+ key={editing.id}
+ eventTypeId={props.eventTypeId || undefined}
+ handleClose={() => setEditModalOpen(false)}
+ defaultValues={editing}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+ </>
+ )}
+ />
+ );
+}
diff --git a/apps/web/components/webhook/WebhookListItem.tsx b/apps/web/components/webhook/WebhookListItem.tsx
new file mode 100644
index 00000000000..6fb80815490
--- /dev/null
+++ b/apps/web/components/webhook/WebhookListItem.tsx
@@ -0,0 +1,93 @@
+import { PencilAltIcon, TrashIcon } from "@heroicons/react/outline";
+
+import classNames from "@calcom/lib/classNames";
+
+import { useLocale } from "@lib/hooks/useLocale";
+import { inferQueryOutput, trpc } from "@lib/trpc";
+
+import { Dialog, DialogTrigger } from "@components/Dialog";
+import { ListItem } from "@components/List";
+import { Tooltip } from "@components/Tooltip";
+import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";
+import Button from "@components/ui/Button";
+
+export type TWebhook = inferQueryOutput<"viewer.webhook.list">[number];
+
+export default function WebhookListItem(props: { webhook: TWebhook; onEditWebhook: () => void }) {
+ const { t } = useLocale();
+ const utils = trpc.useContext();
+ const deleteWebhook = trpc.useMutation("viewer.webhook.delete", {
+ async onSuccess() {
+ await utils.invalidateQueries(["viewer.webhook.list"]);
+ },
+ });
+
+ return (
+ <ListItem className="-mt-px flex w-full p-4">
+ <div className="flex w-full justify-between">
+ <div className="flex max-w-full flex-col truncate">
+ <div className="flex space-y-1">
+ <span
+ className={classNames(
+ "truncate text-sm",
+ props.webhook.active ? "text-neutral-700" : "text-neutral-200"
+ )}>
+ {props.webhook.subscriberUrl}
+ </span>
+ </div>
+ <div className="mt-2 flex">
+ <span className="flex flex-col space-x-2 space-y-1 text-xs sm:flex-row sm:space-y-0 sm:rtl:space-x-reverse">
+ {props.webhook.eventTriggers.map((eventTrigger, ind) => (
+ <span
+ key={ind}
+ className={classNames(
+ "w-max rounded-sm px-1 text-xs ",
+ props.webhook.active ? "bg-blue-100 text-blue-700" : "bg-blue-50 text-blue-200"
+ )}>
+ {t(`${eventTrigger.toLowerCase()}`)}
+ </span>
+ ))}
+ </span>
+ </div>
+ </div>
+ <div className="flex">
+ <Tooltip content={t("edit_webhook")}>
+ <Button
+ onClick={() => props.onEditWebhook()}
+ color="minimal"
+ size="icon"
+ StartIcon={PencilAltIcon}
+ className="ml-4 w-full self-center p-2"></Button>
+ </Tooltip>
+ <Dialog>
+ <Tooltip content={t("delete_webhook")}>
+ <DialogTrigger asChild>
+ <Button
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ color="minimal"
+ size="icon"
+ StartIcon={TrashIcon}
+ className="ml-2 w-full self-center p-2"></Button>
+ </DialogTrigger>
+ </Tooltip>
+ <ConfirmationDialogContent
+ variety="danger"
+ title={t("delete_webhook")}
+ confirmBtnText={t("confirm_delete_webhook")}
+ cancelBtnText={t("cancel")}
+ onConfirm={() =>
+ deleteWebhook.mutate({
+ id: props.webhook.id,
+ eventTypeId: props.webhook.eventTypeId || undefined,
+ })
+ }>
+ {t("delete_webhook_confirmation_message")}
+ </ConfirmationDialogContent>
+ </Dialog>
+ </div>
+ </div>
+ </ListItem>
+ );
+}
diff --git a/apps/web/components/webhook/WebhookTestDisclosure.tsx b/apps/web/components/webhook/WebhookTestDisclosure.tsx
new file mode 100644
index 00000000000..685f967c9d8
--- /dev/null
+++ b/apps/web/components/webhook/WebhookTestDisclosure.tsx
@@ -0,0 +1,64 @@
+import { ChevronRightIcon, SwitchHorizontalIcon } from "@heroicons/react/solid";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@radix-ui/react-collapsible";
+import { useState } from "react";
+import { useWatch } from "react-hook-form";
+
+import classNames from "@calcom/lib/classNames";
+
+import { useLocale } from "@lib/hooks/useLocale";
+import showToast from "@lib/notification";
+import { trpc } from "@lib/trpc";
+
+import { InputGroupBox } from "@components/form/fields";
+import Button from "@components/ui/Button";
+
+export default function WebhookTestDisclosure() {
+ const subscriberUrl: string = useWatch({ name: "subscriberUrl" });
+ const payloadTemplate = useWatch({ name: "payloadTemplate" }) || null;
+ const { t } = useLocale();
+ const [open, setOpen] = useState(false);
+ const mutation = trpc.useMutation("viewer.webhook.testTrigger", {
+ onError(err) {
+ showToast(err.message, "error");
+ },
+ });
+
+ return (
+ <Collapsible open={open} onOpenChange={() => setOpen(!open)}>
+ <CollapsibleTrigger type="button" className={"flex w-full cursor-pointer"}>
+ <ChevronRightIcon className={`${open ? "rotate-90 transform" : ""} h-5 w-5 text-neutral-500`} />
+ <span className="text-sm font-medium text-gray-700">{t("webhook_test")}</span>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <InputGroupBox className="space-y-0 border-0 px-0">
+ <div className="flex justify-between bg-gray-50 p-2">
+ <h3 className="self-center text-gray-700">{t("webhook_response")}</h3>
+ <Button
+ StartIcon={SwitchHorizontalIcon}
+ type="button"
+ color="minimal"
+ disabled={mutation.isLoading}
+ onClick={() => mutation.mutate({ url: subscriberUrl, type: "PING", payloadTemplate })}>
+ {t("ping_test")}
+ </Button>
+ </div>
+ <div className="border-8 border-gray-50 p-2 text-gray-500">
+ {!mutation.data && <em>{t("no_data_yet")}</em>}
+ {mutation.status === "success" && (
+ <>
+ <div
+ className={classNames(
+ "ml-auto w-max px-2 py-1 text-xs",
+ mutation.data.ok ? "bg-green-50 text-green-500" : "bg-red-50 text-red-500"
+ )}>
+ {mutation.data.ok ? t("success") : t("failed")}
+ </div>
+ <pre className="overflow-x-auto">{JSON.stringify(mutation.data, null, 4)}</pre>
+ </>
+ )}
+ </div>
+ </InputGroupBox>
+ </CollapsibleContent>
+ </Collapsible>
+ );
+}
diff --git a/apps/web/lib/webhooks/integrationTemplate.tsx b/apps/web/lib/webhooks/integrationTemplate.tsx
new file mode 100644
index 00000000000..242c8dcc8d3
--- /dev/null
+++ b/apps/web/lib/webhooks/integrationTemplate.tsx
@@ -0,0 +1,28 @@
+const supportedWebhookIntegrationList = ["https://discord.com/api/webhooks/"];
+
+type WebhookIntegrationProps = {
+ url: string;
+};
+
+export const hasTemplateIntegration = (props: WebhookIntegrationProps) => {
+ const ind = supportedWebhookIntegrationList.findIndex((integration) => {
+ return props.url.includes(integration);
+ });
+ return ind > -1 ? true : false;
+};
+
+const customTemplate = (props: WebhookIntegrationProps) => {
+ const ind = supportedWebhookIntegrationList.findIndex((integration) => {
+ return props.url.includes(integration);
+ });
+ return integrationTemplate(supportedWebhookIntegrationList[ind]) || "";
+};
+
+const integrationTemplate = (webhookIntegration: string) => {
+ switch (webhookIntegration) {
+ case "https://discord.com/api/webhooks/":
+ return '{"content": "A new event has been scheduled","embeds": [{"color": 2697513,"fields": [{"name": "What","value": "{{title}} ({{type}})"},{"name": "When","value": "Start: {{startTime}} \\n End: {{endTime}} \\n Timezone: ({{organizer.timeZone}})"},{"name": "Who","value": "Organizer: {{organizer.name}} ({{organizer.email}}) \\n Booker: {{attendees.0.name}} ({{attendees.0.email}})" },{"name":"Description", "value":": {{description}}"},{"name":"Where","value":": {{location}} "}]}]}';
+ }
+};
+
+export default customTemplate;
diff --git a/apps/web/lib/webhooks/subscriptions.tsx b/apps/web/lib/webhooks/subscriptions.tsx
index 7336fb3c681..dc8ac85cb47 100644
--- a/apps/web/lib/webhooks/subscriptions.tsx
+++ b/apps/web/lib/webhooks/subscriptions.tsx
@@ -2,13 +2,27 @@ import { WebhookTriggerEvents } from "@prisma/client";
import prisma from "@lib/prisma";
-const getSubscribers = async (userId: number, triggerEvent: WebhookTriggerEvents) => {
+export type GetSubscriberOptions = {
+ userId: number;
+ eventTypeId: number;
+ triggerEvent: WebhookTriggerEvents;
+};
+
+const getSubscribers = async (options: GetSubscriberOptions) => {
+ const { userId, eventTypeId } = options;
const allWebhooks = await prisma.webhook.findMany({
where: {
- userId: userId,
+ OR: [
+ {
+ userId,
+ },
+ {
+ eventTypeId,
+ },
+ ],
AND: {
eventTriggers: {
- has: triggerEvent,
+ has: options.triggerEvent,
},
active: {
equals: true,
diff --git a/apps/web/pages/api/book/event.ts b/apps/web/pages/api/book/event.ts
index b860eae8634..f448591a2fb 100644
--- a/apps/web/pages/api/book/event.ts
+++ b/apps/web/pages/api/book/event.ts
@@ -1,4 +1,4 @@
-import { Credential, Prisma, SchedulingType } from "@prisma/client";
+import { Credential, Prisma, SchedulingType, WebhookTriggerEvents } from "@prisma/client";
import async from "async";
import dayjs from "dayjs";
import dayjsBusinessTime from "dayjs-business-time";
@@ -594,9 +594,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
log.debug(`Booking ${user.username} completed`);
- const eventTrigger = rescheduleUid ? "BOOKING_RESCHEDULED" : "BOOKING_CREATED";
+ const eventTrigger: WebhookTriggerEvents = rescheduleUid ? "BOOKING_RESCHEDULED" : "BOOKING_CREATED";
+ const subscriberOptions = {
+ userId: user.id,
+ eventTypeId,
+ triggerEvent: eventTrigger,
+ };
+
// Send Webhook call if hooked to BOOKING_CREATED & BOOKING_RESCHEDULED
- const subscribers = await getSubscribers(user.id, eventTrigger);
+ const subscribers = await getSubscribers(subscriberOptions);
console.log("evt:", {
...evt,
metadata: reqBody.metadata,
diff --git a/apps/web/pages/api/cancel.ts b/apps/web/pages/api/cancel.ts
index 8e86b2e4b80..81cf17d5f21 100644
--- a/apps/web/pages/api/cancel.ts
+++ b/apps/web/pages/api/cancel.ts
@@ -1,4 +1,4 @@
-import { BookingStatus } from "@prisma/client";
+import { BookingStatus, WebhookTriggerEvents } from "@prisma/client";
import async from "async";
import dayjs from "dayjs";
import { NextApiRequest, NextApiResponse } from "next";
@@ -130,9 +130,14 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
};
// Hook up the webhook logic here
- const eventTrigger = "BOOKING_CANCELLED";
+ const eventTrigger: WebhookTriggerEvents = "BOOKING_CANCELLED";
// Send Webhook call if hooked to BOOKING.CANCELLED
- const subscribers = await getSubscribers(bookingToDelete.userId, eventTrigger);
+ const subscriberOptions = {
+ userId: bookingToDelete.userId,
+ eventTypeId: bookingToDelete.eventTypeId as number,
+ triggerEvent: eventTrigger,
+ };
+ const subscribers = await getSubscribers(subscriberOptions);
const promises = subscribers.map((sub) =>
sendPayload(eventTrigger, new Date().toISOString(), sub.subscriberUrl, evt, sub.payloadTemplate).catch(
(e) => {
diff --git a/apps/web/pages/event-types/[type].tsx b/apps/web/pages/event-types/[type].tsx
index 3fb8c88edf6..6093ee286fb 100644
--- a/apps/web/pages/event-types/[type].tsx
+++ b/apps/web/pages/event-types/[type].tsx
@@ -12,6 +12,7 @@ import {
UserAddIcon,
UsersIcon,
} from "@heroicons/react/solid";
+import { MembershipRole } from "@prisma/client";
import { Availability, EventTypeCustomInput, PeriodType, Prisma, SchedulingType } from "@prisma/client";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@radix-ui/react-collapsible";
import * as RadioGroup from "@radix-ui/react-radio-group";
@@ -40,8 +41,10 @@ import { slugify } from "@lib/slugify";
import { trpc } from "@lib/trpc";
import { inferSSRProps } from "@lib/types/inferSSRProps";
+import { ClientSuspense } from "@components/ClientSuspense";
import DestinationCalendarSelector from "@components/DestinationCalendarSelector";
import { Dialog, DialogContent, DialogTrigger } from "@components/Dialog";
+import Loader from "@components/Loader";
import Shell from "@components/Shell";
import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";
import { Form } from "@components/form/fields";
@@ -55,6 +58,7 @@ import CheckedSelect from "@components/ui/form/CheckedSelect";
import { DateRangePicker } from "@components/ui/form/DateRangePicker";
import MinutesField from "@components/ui/form/MinutesField";
import * as RadioArea from "@components/ui/form/radio-area";
+import WebhookListContainer from "@components/webhook/WebhookListContainer";
import bloxyApi from "../../web3/dummyResps/bloxyApi";
@@ -636,6 +640,9 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
);
};
+ const membership = team?.members.find((membership) => membership.user.id === props.session.user.id);
+ const isAdmin = membership?.role === MembershipRole.OWNER || membership?.role === MembershipRole.ADMIN;
+
return (
<div>
<Shell
@@ -669,853 +676,863 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
</div>
}
subtitle={eventType.description || ""}>
- <div className="mx-auto block sm:flex md:max-w-5xl">
- <div className="w-full ltr:mr-2 rtl:ml-2 sm:w-9/12">
- <div className="-mx-4 rounded-sm border border-neutral-200 bg-white p-4 py-6 sm:mx-0 sm:px-8">
- <Form
- form={formMethods}
- handleSubmit={async (values) => {
- const { periodDates, periodCountCalendarDays, smartContractAddress, ...input } = values;
-
- updateMutation.mutate({
- ...input,
- availability: availabilityState,
- periodStartDate: periodDates.startDate,
- periodEndDate: periodDates.endDate,
- periodCountCalendarDays: periodCountCalendarDays === "1",
- id: eventType.id,
- metadata: smartContractAddress
- ? {
- smartContractAddress,
- }
- : "",
- });
- }}
- className="space-y-6">
- <div className="space-y-3">
- <div className="block items-center sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
- <label htmlFor="slug" className="flex text-sm font-medium text-neutral-700">
- <LinkIcon className="mt-0.5 h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
- {t("url")}
- </label>
- </div>
- <div className="w-full">
- <div className="flex rounded-sm shadow-sm">
- <span className="inline-flex items-center rounded-l-sm border border-r-0 border-gray-300 bg-gray-50 px-3 text-gray-500 sm:text-sm">
- {process.env.NEXT_PUBLIC_APP_URL?.replace(/^(https?:|)\/\//, "")}/
- {team ? "team/" + team.slug : eventType.users[0].username}/
- </span>
- <input
- type="text"
- required
- className="focus:border-primary-500 focus:ring-primary-500 block w-full min-w-0 flex-1 rounded-none rounded-r-sm border-gray-300 sm:text-sm"
- defaultValue={eventType.slug}
- {...formMethods.register("slug", {
- setValueAs: (v) => slugify(v),
- })}
- />
+ <ClientSuspense fallback={<Loader />}>
+ <div className="mx-auto block sm:flex md:max-w-5xl">
+ <div className="w-full ltr:mr-2 rtl:ml-2 sm:w-9/12">
+ <div className="-mx-4 rounded-sm border border-neutral-200 bg-white p-4 py-6 sm:mx-0 sm:px-8">
+ <Form
+ form={formMethods}
+ handleSubmit={async (values) => {
+ const { periodDates, periodCountCalendarDays, smartContractAddress, ...input } = values;
+ updateMutation.mutate({
+ ...input,
+ availability: availabilityState,
+ periodStartDate: periodDates.startDate,
+ periodEndDate: periodDates.endDate,
+ periodCountCalendarDays: periodCountCalendarDays === "1",
+ id: eventType.id,
+ metadata: smartContractAddress
+ ? {
+ smartContractAddress,
+ }
+ : "",
+ });
+ }}
+ className="space-y-6">
+ <div className="space-y-3">
+ <div className="block items-center sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label htmlFor="slug" className="flex text-sm font-medium text-neutral-700">
+ <LinkIcon className="mt-0.5 h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
+ {t("url")}
+ </label>
+ </div>
+ <div className="w-full">
+ <div className="flex rounded-sm shadow-sm">
+ <span className="inline-flex items-center rounded-l-sm border border-r-0 border-gray-300 bg-gray-50 px-3 text-gray-500 sm:text-sm">
+ {process.env.NEXT_PUBLIC_APP_URL?.replace(/^(https?:|)\/\//, "")}/
+ {team ? "team/" + team.slug : eventType.users[0].username}/
+ </span>
+ <input
+ type="text"
+ required
+ className="focus:border-primary-500 focus:ring-primary-500 block w-full min-w-0 flex-1 rounded-none rounded-r-sm border-gray-300 sm:text-sm"
+ defaultValue={eventType.slug}
+ {...formMethods.register("slug", {
+ setValueAs: (v) => slugify(v),
+ })}
+ />
+ </div>
</div>
- </div>
- </div>
- <Controller
- name="length"
- control={formMethods.control}
- defaultValue={eventType.length || 15}
- render={() => (
- <MinutesField
- label={
- <>
- <ClockIcon className="mt-0.5 h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />{" "}
- {t("duration")}
- </>
- }
- id="length"
- required
- min="1"
- placeholder="15"
- defaultValue={eventType.length || 15}
- onChange={(e) => {
- formMethods.setValue("length", Number(e.target.value));
- }}
- />
- )}
- />
- </div>
- <hr />
- <div className="space-y-3">
- <div className="block sm:flex">
- <div className="min-w-48 sm:mb-0">
- <label htmlFor="location" className="mt-2.5 flex text-sm font-medium text-neutral-700">
- <LocationMarkerIcon className="mt-0.5 h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
- {t("location")}
- </label>
</div>
<Controller
- name="locations"
+ name="length"
control={formMethods.control}
- defaultValue={eventType.locations || []}
- render={() => <Locations />}
+ defaultValue={eventType.length || 15}
+ render={() => (
+ <MinutesField
+ label={
+ <>
+ <ClockIcon className="mt-0.5 h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />{" "}
+ {t("duration")}
+ </>
+ }
+ id="length"
+ required
+ min="1"
+ placeholder="15"
+ defaultValue={eventType.length || 15}
+ onChange={(e) => {
+ formMethods.setValue("length", Number(e.target.value));
+ }}
+ />
+ )}
/>
</div>
- </div>
- <hr className="border-neutral-200" />
- <div className="space-y-3">
- <div className="block sm:flex">
- <div className="min-w-48 mb-4 mt-2.5 sm:mb-0">
- <label htmlFor="description" className="mt-0 flex text-sm font-medium text-neutral-700">
- <DocumentIcon className="mt-0.5 h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
- {t("description")}
- </label>
- </div>
- <div className="w-full">
- <textarea
- id="description"
- className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 shadow-sm sm:text-sm"
- placeholder={t("quick_video_meeting")}
- {...formMethods.register("description")}
- defaultValue={asStringOrUndefined(eventType.description)}></textarea>
- </div>
- </div>
- </div>
- {team && <hr className="border-neutral-200" />}
- {team && (
+ <hr />
<div className="space-y-3">
<div className="block sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
+ <div className="min-w-48 sm:mb-0">
<label
- htmlFor="schedulingType"
- className="mt-2 flex text-sm font-medium text-neutral-700">
- <UsersIcon className="h-5 w-5 text-neutral-500 ltr:mr-2 rtl:ml-2" />{" "}
- {t("scheduling_type")}
+ htmlFor="location"
+ className="mt-2.5 flex text-sm font-medium text-neutral-700">
+ <LocationMarkerIcon className="mt-0.5 h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
+ {t("location")}
</label>
</div>
<Controller
- name="schedulingType"
+ name="locations"
control={formMethods.control}
- defaultValue={eventType.schedulingType}
- render={() => (
- <RadioArea.Select
- value={asStringOrUndefined(eventType.schedulingType)}
- options={schedulingTypeOptions}
- onChange={(val) => {
- // FIXME: Better types are needed
- formMethods.setValue("schedulingType", val as SchedulingType);
- }}
- />
- )}
+ defaultValue={eventType.locations || []}
+ render={() => <Locations />}
/>
</div>
-
+ </div>
+ <hr className="border-neutral-200" />
+ <div className="space-y-3">
<div className="block sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
- <label htmlFor="users" className="flex text-sm font-medium text-neutral-700">
- <UserAddIcon className="h-5 w-5 text-neutral-500 ltr:mr-2 rtl:ml-2" />{" "}
- {t("attendees")}
+ <div className="min-w-48 mb-4 mt-2.5 sm:mb-0">
+ <label
+ htmlFor="description"
+ className="mt-0 flex text-sm font-medium text-neutral-700">
+ <DocumentIcon className="mt-0.5 h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
+ {t("description")}
</label>
</div>
- <div className="w-full space-y-2">
+ <div className="w-full">
+ <textarea
+ id="description"
+ className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 shadow-sm sm:text-sm"
+ placeholder={t("quick_video_meeting")}
+ {...formMethods.register("description")}
+ defaultValue={asStringOrUndefined(eventType.description)}></textarea>
+ </div>
+ </div>
+ </div>
+ {team && <hr className="border-neutral-200" />}
+ {team && (
+ <div className="space-y-3">
+ <div className="block sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label
+ htmlFor="schedulingType"
+ className="mt-2 flex text-sm font-medium text-neutral-700">
+ <UsersIcon className="h-5 w-5 text-neutral-500 ltr:mr-2 rtl:ml-2" />{" "}
+ {t("scheduling_type")}
+ </label>
+ </div>
<Controller
- name="users"
+ name="schedulingType"
control={formMethods.control}
- defaultValue={eventType.users.map((user) => user.id.toString())}
+ defaultValue={eventType.schedulingType}
render={() => (
- <CheckedSelect
- disabled={false}
- onChange={(options) => {
- formMethods.setValue(
- "users",
- options.map((user) => user.value)
- );
+ <RadioArea.Select
+ value={asStringOrUndefined(eventType.schedulingType)}
+ options={schedulingTypeOptions}
+ onChange={(val) => {
+ // FIXME: Better types are needed
+ formMethods.setValue("schedulingType", val as SchedulingType);
}}
- defaultValue={eventType.users.map(mapUserToValue)}
- options={teamMembers.map(mapUserToValue)}
- placeholder={t("add_attendees")}
/>
)}
/>
</div>
+
+ <div className="block sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label htmlFor="users" className="flex text-sm font-medium text-neutral-700">
+ <UserAddIcon className="h-5 w-5 text-neutral-500 ltr:mr-2 rtl:ml-2" />{" "}
+ {t("attendees")}
+ </label>
+ </div>
+ <div className="w-full space-y-2">
+ <Controller
+ name="users"
+ control={formMethods.control}
+ defaultValue={eventType.users.map((user) => user.id.toString())}
+ render={() => (
+ <CheckedSelect
+ disabled={false}
+ onChange={(options) => {
+ formMethods.setValue(
+ "users",
+ options.map((user) => user.value)
+ );
+ }}
+ defaultValue={eventType.users.map(mapUserToValue)}
+ options={teamMembers.map(mapUserToValue)}
+ placeholder={t("add_attendees")}
+ />
+ )}
+ />
+ </div>
+ </div>
</div>
- </div>
- )}
- <Collapsible
- open={advancedSettingsVisible}
- onOpenChange={() => setAdvancedSettingsVisible(!advancedSettingsVisible)}>
- <>
- <CollapsibleTrigger type="button" className="flex w-full">
- <ChevronRightIcon
- className={`${
- advancedSettingsVisible ? "rotate-90 transform" : ""
- } ml-auto h-5 w-5 text-neutral-500`}
- />
- <span className="text-sm font-medium text-neutral-700">
- {t("show_advanced_settings")}
- </span>
- </CollapsibleTrigger>
- <CollapsibleContent className="mt-4 space-y-6">
- {/**
- * Only display calendar selector if user has connected calendars AND if it's not
- * a team event. Since we don't have logic to handle each attende calendar (for now).
- * This will fallback to each user selected destination calendar.
- */}
- {!!connectedCalendarsQuery.data?.connectedCalendars.length && !team && (
+ )}
+ <Collapsible
+ open={advancedSettingsVisible}
+ onOpenChange={() => setAdvancedSettingsVisible(!advancedSettingsVisible)}>
+ <>
+ <CollapsibleTrigger type="button" className="flex w-full">
+ <ChevronRightIcon
+ className={`${
+ advancedSettingsVisible ? "rotate-90 transform" : ""
+ } ml-auto h-5 w-5 text-neutral-500`}
+ />
+ <span className="text-sm font-medium text-neutral-700">
+ {t("show_advanced_settings")}
+ </span>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="mt-4 space-y-6">
+ {/**
+ * Only display calendar selector if user has connected calendars AND if it's not
+ * a team event. Since we don't have logic to handle each attende calendar (for now).
+ * This will fallback to each user selected destination calendar.
+ */}
+ {!!connectedCalendarsQuery.data?.connectedCalendars.length && !team && (
+ <div className="block items-center sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label
+ htmlFor="createEventsOn"
+ className="flex text-sm font-medium text-neutral-700">
+ {t("create_events_on")}
+ </label>
+ </div>
+ <div className="w-full">
+ <div className="relative mt-1 rounded-sm shadow-sm">
+ <Controller
+ control={formMethods.control}
+ name="destinationCalendar"
+ defaultValue={eventType.destinationCalendar || undefined}
+ render={({ field: { onChange, value } }) => (
+ <DestinationCalendarSelector
+ value={value ? value.externalId : undefined}
+ onChange={onChange}
+ hidePlaceholder
+ />
+ )}
+ />
+ </div>
+ </div>
+ </div>
+ )}
<div className="block items-center sm:flex">
<div className="min-w-48 mb-4 sm:mb-0">
- <label
- htmlFor="createEventsOn"
- className="flex text-sm font-medium text-neutral-700">
- {t("create_events_on")}
+ <label htmlFor="eventName" className="flex text-sm font-medium text-neutral-700">
+ {t("event_name")} <InfoBadge content={t("event_name_tooltip")} />
</label>
</div>
<div className="w-full">
<div className="relative mt-1 rounded-sm shadow-sm">
- <Controller
- control={formMethods.control}
- name="destinationCalendar"
- defaultValue={eventType.destinationCalendar || undefined}
- render={({ field: { onChange, value } }) => (
- <DestinationCalendarSelector
- value={value ? value.externalId : undefined}
- onChange={onChange}
- hidePlaceholder
- />
- )}
+ <input
+ type="text"
+ className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 shadow-sm sm:text-sm"
+ placeholder={t("meeting_with_user")}
+ defaultValue={eventType.eventName || ""}
+ {...formMethods.register("eventName")}
/>
</div>
</div>
</div>
- )}
- <div className="block items-center sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
- <label htmlFor="eventName" className="flex text-sm font-medium text-neutral-700">
- {t("event_name")} <InfoBadge content={t("event_name_tooltip")} />
- </label>
- </div>
- <div className="w-full">
- <div className="relative mt-1 rounded-sm shadow-sm">
- <input
- type="text"
- className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 shadow-sm sm:text-sm"
- placeholder={t("meeting_with_user")}
- defaultValue={eventType.eventName || ""}
- {...formMethods.register("eventName")}
- />
+ {eventType.isWeb3Active && (
+ <div className="block items-center sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label
+ htmlFor="smartContractAddress"
+ className="flex text-sm font-medium text-neutral-700">
+ {t("Smart Contract Address")}
+ </label>
+ </div>
+ <div className="w-full">
+ <div className="relative mt-1 rounded-sm shadow-sm">
+ {
+ <input
+ type="text"
+ className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 shadow-sm sm:text-sm"
+ placeholder={t("Example: 0x71c7656ec7ab88b098defb751b7401b5f6d8976f")}
+ defaultValue={(eventType.metadata.smartContractAddress || "") as string}
+ {...formMethods.register("smartContractAddress")}
+ />
+ }
+ </div>
+ </div>
</div>
- </div>
- </div>
- {eventType.isWeb3Active && (
+ )}
<div className="block items-center sm:flex">
<div className="min-w-48 mb-4 sm:mb-0">
<label
- htmlFor="smartContractAddress"
- className="flex text-sm font-medium text-neutral-700">
- {t("Smart Contract Address")}
+ htmlFor="additionalFields"
+ className="flexflex mt-2 text-sm font-medium text-neutral-700">
+ {t("additional_inputs")}
</label>
</div>
<div className="w-full">
- <div className="relative mt-1 rounded-sm shadow-sm">
- {
- <input
- type="text"
- className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 shadow-sm sm:text-sm"
- placeholder={t("Example: 0x71c7656ec7ab88b098defb751b7401b5f6d8976f")}
- defaultValue={(eventType.metadata.smartContractAddress || "") as string}
- {...formMethods.register("smartContractAddress")}
- />
- }
- </div>
- </div>
- </div>
- )}
- <div className="block items-center sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
- <label
- htmlFor="additionalFields"
- className="flexflex mt-2 text-sm font-medium text-neutral-700">
- {t("additional_inputs")}
- </label>
- </div>
- <div className="w-full">
- <ul className="mt-1">
- {customInputs.map((customInput: EventTypeCustomInput, idx: number) => (
- <li key={idx} className="bg-secondary-50 mb-2 border p-2">
- <div className="flex justify-between">
- <div className="w-0 flex-1">
- <div className="truncate">
- <span
- className="text-sm ltr:ml-2 rtl:mr-2"
- title={`${t("label")}: ${customInput.label}`}>
- {t("label")}: {customInput.label}
- </span>
- </div>
- {customInput.placeholder && (
+ <ul className="mt-1">
+ {customInputs.map((customInput: EventTypeCustomInput, idx: number) => (
+ <li key={idx} className="bg-secondary-50 mb-2 border p-2">
+ <div className="flex justify-between">
+ <div className="w-0 flex-1">
<div className="truncate">
<span
className="text-sm ltr:ml-2 rtl:mr-2"
- title={`${t("placeholder")}: ${customInput.placeholder}`}>
- {t("placeholder")}: {customInput.placeholder}
+ title={`${t("label")}: ${customInput.label}`}>
+ {t("label")}: {customInput.label}
+ </span>
+ </div>
+ {customInput.placeholder && (
+ <div className="truncate">
+ <span
+ className="text-sm ltr:ml-2 rtl:mr-2"
+ title={`${t("placeholder")}: ${customInput.placeholder}`}>
+ {t("placeholder")}: {customInput.placeholder}
+ </span>
+ </div>
+ )}
+ <div>
+ <span className="text-sm ltr:ml-2 rtl:mr-2">
+ {t("type")}: {customInput.type}
+ </span>
+ </div>
+ <div>
+ <span className="text-sm ltr:ml-2 rtl:mr-2">
+ {customInput.required ? t("required") : t("optional")}
</span>
</div>
- )}
- <div>
- <span className="text-sm ltr:ml-2 rtl:mr-2">
- {t("type")}: {customInput.type}
- </span>
</div>
- <div>
- <span className="text-sm ltr:ml-2 rtl:mr-2">
- {customInput.required ? t("required") : t("optional")}
- </span>
+ <div className="flex">
+ <Button
+ onClick={() => {
+ setSelectedCustomInput(customInput);
+ setSelectedCustomInputModalOpen(true);
+ }}
+ color="minimal"
+ type="button">
+ {t("edit")}
+ </Button>
+ <button type="button" onClick={() => removeCustom(idx)}>
+ <XIcon className="h-6 w-6 border-l-2 pl-1 hover:text-red-500 " />
+ </button>
</div>
</div>
- <div className="flex">
- <Button
- onClick={() => {
- setSelectedCustomInput(customInput);
- setSelectedCustomInputModalOpen(true);
- }}
- color="minimal"
- type="button">
- {t("edit")}
- </Button>
- <button type="button" onClick={() => removeCustom(idx)}>
- <XIcon className="h-6 w-6 border-l-2 pl-1 hover:text-red-500 " />
- </button>
- </div>
- </div>
+ </li>
+ ))}
+ <li>
+ <Button
+ onClick={() => {
+ setSelectedCustomInput(undefined);
+ setSelectedCustomInputModalOpen(true);
+ }}
+ color="secondary"
+ type="button"
+ StartIcon={PlusIcon}>
+ {t("add_input")}
+ </Button>
</li>
- ))}
- <li>
- <Button
- onClick={() => {
- setSelectedCustomInput(undefined);
- setSelectedCustomInputModalOpen(true);
- }}
- color="secondary"
- type="button"
- StartIcon={PlusIcon}>
- {t("add_input")}
- </Button>
- </li>
- </ul>
+ </ul>
+ </div>
</div>
- </div>
- <Controller
- name="requiresConfirmation"
- control={formMethods.control}
- defaultValue={eventType.requiresConfirmation}
- render={() => (
- <CheckboxField
- id="requiresConfirmation"
- name="requiresConfirmation"
- label={t("opt_in_booking")}
- description={t("opt_in_booking_description")}
- defaultChecked={eventType.requiresConfirmation}
- onChange={(e) => {
- formMethods.setValue("requiresConfirmation", e?.target.checked);
- }}
- />
- )}
- />
+ <Controller
+ name="requiresConfirmation"
+ control={formMethods.control}
+ defaultValue={eventType.requiresConfirmation}
+ render={() => (
+ <CheckboxField
+ id="requiresConfirmation"
+ name="requiresConfirmation"
+ label={t("opt_in_booking")}
+ description={t("opt_in_booking_description")}
+ defaultChecked={eventType.requiresConfirmation}
+ onChange={(e) => {
+ formMethods.setValue("requiresConfirmation", e?.target.checked);
+ }}
+ />
+ )}
+ />
- <Controller
- name="disableGuests"
- control={formMethods.control}
- defaultValue={eventType.disableGuests}
- render={() => (
- <CheckboxField
- id="disableGuests"
- name="disableGuests"
- label={t("disable_guests")}
- description={t("disable_guests_description")}
- defaultChecked={eventType.disableGuests}
- onChange={(e) => {
- formMethods.setValue("disableGuests", e?.target.checked);
- }}
- />
- )}
- />
+ <Controller
+ name="disableGuests"
+ control={formMethods.control}
+ defaultValue={eventType.disableGuests}
+ render={() => (
+ <CheckboxField
+ id="disableGuests"
+ name="disableGuests"
+ label={t("disable_guests")}
+ description={t("disable_guests_description")}
+ defaultChecked={eventType.disableGuests}
+ onChange={(e) => {
+ formMethods.setValue("disableGuests", e?.target.checked);
+ }}
+ />
+ )}
+ />
- <hr className="my-2 border-neutral-200" />
- <Controller
- name="minimumBookingNotice"
- control={formMethods.control}
- defaultValue={eventType.minimumBookingNotice}
- render={() => (
- <MinutesField
- label={t("minimum_booking_notice")}
- required
- min="0"
- placeholder="120"
- defaultValue={eventType.minimumBookingNotice}
- onChange={(e) => {
- formMethods.setValue("minimumBookingNotice", Number(e.target.value));
- }}
- />
- )}
- />
+ <hr className="my-2 border-neutral-200" />
+ <Controller
+ name="minimumBookingNotice"
+ control={formMethods.control}
+ defaultValue={eventType.minimumBookingNotice}
+ render={() => (
+ <MinutesField
+ label={t("minimum_booking_notice")}
+ required
+ min="0"
+ placeholder="120"
+ defaultValue={eventType.minimumBookingNotice}
+ onChange={(e) => {
+ formMethods.setValue("minimumBookingNotice", Number(e.target.value));
+ }}
+ />
+ )}
+ />
- <div className="block items-center sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
- <label htmlFor="eventName" className="flex text-sm font-medium text-neutral-700">
- {t("slot_interval")}
- </label>
+ <div className="block items-center sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label htmlFor="eventName" className="flex text-sm font-medium text-neutral-700">
+ {t("slot_interval")}
+ </label>
+ </div>
+ <div className="w-full">
+ <div className="relative mt-1 rounded-sm shadow-sm">
+ <Controller
+ name="slotInterval"
+ control={formMethods.control}
+ render={() => {
+ const slotIntervalOptions = [
+ {
+ label: t("slot_interval_default"),
+ value: -1,
+ },
+ ...[5, 10, 15, 20, 30, 45, 60].map((minutes) => ({
+ label: minutes + " " + t("minutes"),
+ value: minutes,
+ })),
+ ];
+ return (
+ <Select
+ isSearchable={false}
+ classNamePrefix="react-select"
+ className="react-select-container focus:border-primary-500 focus:ring-primary-500 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 sm:text-sm"
+ onChange={(val) => {
+ formMethods.setValue(
+ "slotInterval",
+ val && (val.value || 0) > 0 ? val.value : null
+ );
+ }}
+ defaultValue={
+ slotIntervalOptions.find(
+ (option) => option.value === eventType.slotInterval
+ ) || slotIntervalOptions[0]
+ }
+ options={slotIntervalOptions}
+ />
+ );
+ }}
+ />
+ </div>
+ </div>
</div>
- <div className="w-full">
- <div className="relative mt-1 rounded-sm shadow-sm">
+
+ <div className="block sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label
+ htmlFor="inviteesCanSchedule"
+ className="mt-2.5 flex text-sm font-medium text-neutral-700">
+ {t("invitees_can_schedule")}
+ </label>
+ </div>
+ <div className="w-full">
<Controller
- name="slotInterval"
+ name="periodType"
control={formMethods.control}
- render={() => {
- const slotIntervalOptions = [
- {
- label: t("slot_interval_default"),
- value: -1,
- },
- ...[5, 10, 15, 20, 30, 45, 60].map((minutes) => ({
- label: minutes + " " + t("minutes"),
- value: minutes,
- })),
- ];
- return (
- <Select
- isSearchable={false}
- classNamePrefix="react-select"
- className="react-select-container focus:border-primary-500 focus:ring-primary-500 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 sm:text-sm"
- onChange={(val) => {
- formMethods.setValue(
- "slotInterval",
- val && (val.value || 0) > 0 ? val.value : null
- );
- }}
- defaultValue={
- slotIntervalOptions.find(
- (option) => option.value === eventType.slotInterval
- ) || slotIntervalOptions[0]
- }
- options={slotIntervalOptions}
- />
- );
- }}
+ defaultValue={periodType?.type}
+ render={() => (
+ <RadioGroup.Root
+ defaultValue={periodType?.type}
+ onValueChange={(val) =>
+ formMethods.setValue("periodType", val as PeriodType)
+ }>
+ {PERIOD_TYPES.map((period) => (
+ <div className="mb-2 flex items-center text-sm" key={period.type}>
+ <RadioGroup.Item
+ id={period.type}
+ value={period.type}
+ className="flex h-4 w-4 cursor-pointer items-center rounded-full border border-black bg-white focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
+ <RadioGroup.Indicator className="relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full after:bg-black" />
+ </RadioGroup.Item>
+ {period.prefix ? <span>{period.prefix}&nbsp;</span> : null}
+ {period.type === "ROLLING" && (
+ <div className="inline-flex">
+ <input
+ type="number"
+ className="focus:border-primary-500 focus:ring-primary-500 block w-12 rounded-sm border-gray-300 shadow-sm [appearance:textfield] ltr:mr-2 rtl:ml-2 sm:text-sm"
+ placeholder="30"
+ {...formMethods.register("periodDays", { valueAsNumber: true })}
+ defaultValue={eventType.periodDays || 30}
+ />
+ <select
+ id=""
+ className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 py-2 pl-3 pr-10 text-base focus:outline-none sm:text-sm"
+ {...formMethods.register("periodCountCalendarDays")}
+ defaultValue={eventType.periodCountCalendarDays ? "1" : "0"}>
+ <option value="1">{t("calendar_days")}</option>
+ <option value="0">{t("business_days")}</option>
+ </select>
+ </div>
+ )}
+ {period.type === "RANGE" && (
+ <div className="inline-flex space-x-2 ltr:ml-2 rtl:mr-2 rtl:space-x-reverse">
+ <Controller
+ name="periodDates"
+ control={formMethods.control}
+ defaultValue={periodDates}
+ render={() => (
+ <DateRangePicker
+ startDate={formMethods.getValues("periodDates").startDate}
+ endDate={formMethods.getValues("periodDates").endDate}
+ onDatesChange={({ startDate, endDate }) => {
+ formMethods.setValue("periodDates", { startDate, endDate });
+ }}
+ />
+ )}
+ />
+ </div>
+ )}
+ {period.suffix ? (
+ <span className="ltr:ml-2 rtl:mr-2">&nbsp;{period.suffix}</span>
+ ) : null}
+ </div>
+ ))}
+ </RadioGroup.Root>
+ )}
/>
</div>
</div>
- </div>
- <div className="block sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
- <label
- htmlFor="inviteesCanSchedule"
- className="mt-2.5 flex text-sm font-medium text-neutral-700">
- {t("invitees_can_schedule")}
- </label>
- </div>
- <div className="w-full">
- <Controller
- name="periodType"
- control={formMethods.control}
- defaultValue={periodType?.type}
- render={() => (
- <RadioGroup.Root
- defaultValue={periodType?.type}
- onValueChange={(val) =>
- formMethods.setValue("periodType", val as PeriodType)
- }>
- {PERIOD_TYPES.map((period) => (
- <div className="mb-2 flex items-center text-sm" key={period.type}>
- <RadioGroup.Item
- id={period.type}
- value={period.type}
- className="flex h-4 w-4 cursor-pointer items-center rounded-full border border-black bg-white focus:border-2 focus:outline-none ltr:mr-2 rtl:ml-2">
- <RadioGroup.Indicator className="relative flex h-4 w-4 items-center justify-center after:block after:h-2 after:w-2 after:rounded-full after:bg-black" />
- </RadioGroup.Item>
- {period.prefix ? <span>{period.prefix}&nbsp;</span> : null}
- {period.type === "ROLLING" && (
- <div className="inline-flex">
- <input
- type="number"
- className="focus:border-primary-500 focus:ring-primary-500 block w-12 rounded-sm border-gray-300 shadow-sm [appearance:textfield] ltr:mr-2 rtl:ml-2 sm:text-sm"
- placeholder="30"
- {...formMethods.register("periodDays", { valueAsNumber: true })}
- defaultValue={eventType.periodDays || 30}
- />
- <select
- id=""
- className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 py-2 pl-3 pr-10 text-base focus:outline-none sm:text-sm"
- {...formMethods.register("periodCountCalendarDays")}
- defaultValue={eventType.periodCountCalendarDays ? "1" : "0"}>
- <option value="1">{t("calendar_days")}</option>
- <option value="0">{t("business_days")}</option>
- </select>
- </div>
- )}
- {period.type === "RANGE" && (
- <div className="inline-flex space-x-2 ltr:ml-2 rtl:mr-2 rtl:space-x-reverse">
- <Controller
- name="periodDates"
- control={formMethods.control}
- defaultValue={periodDates}
- render={() => (
- <DateRangePicker
- startDate={formMethods.getValues("periodDates").startDate}
- endDate={formMethods.getValues("periodDates").endDate}
- onDatesChange={({ startDate, endDate }) => {
- formMethods.setValue("periodDates", { startDate, endDate });
- }}
- />
- )}
- />
- </div>
- )}
- {period.suffix ? (
- <span className="ltr:ml-2 rtl:mr-2">&nbsp;{period.suffix}</span>
- ) : null}
- </div>
- ))}
- </RadioGroup.Root>
- )}
- />
- </div>
- </div>
-
- <hr className="border-neutral-200" />
-
- <div className="block sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
- <label htmlFor="availability" className="flex text-sm font-medium text-neutral-700">
- {t("availability")}
- </label>
- </div>
- <div className="w-full">
- <Controller
- name="availability"
- control={formMethods.control}
- render={() => (
- <Scheduler
- setAvailability={(val) => {
- const schedule = {
- openingHours: val.openingHours,
- dateOverrides: val.dateOverrides,
- };
- // Updating internal state that would be sent on mutation
- setAvailabilityState(schedule);
- // Updating form values displayed, but this one doesn't reach form submit scope
- formMethods.setValue("availability", schedule);
- }}
- setTimeZone={(timeZone) => {
- formMethods.setValue("timeZone", timeZone);
- setSelectedTimeZone(timeZone);
- }}
- timeZone={selectedTimeZone}
- availability={availability.map((schedule) => ({
- ...schedule,
- startTime: new Date(schedule.startTime),
- endTime: new Date(schedule.endTime),
- }))}
- />
- )}
- />
+ <hr className="border-neutral-200" />
+ <div className="block sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label
+ htmlFor="availability"
+ className="flex text-sm font-medium text-neutral-700">
+ {t("availability")}
+ </label>
+ </div>
+ <div className="w-full">
+ <Controller
+ name="availability"
+ control={formMethods.control}
+ render={() => (
+ <Scheduler
+ setAvailability={(val) => {
+ const schedule = {
+ openingHours: val.openingHours,
+ dateOverrides: val.dateOverrides,
+ };
+ // Updating internal state that would be sent on mutation
+ setAvailabilityState(schedule);
+ // Updating form values displayed, but this one doesn't reach form submit scope
+ formMethods.setValue("availability", schedule);
+ }}
+ setTimeZone={(timeZone) => {
+ formMethods.setValue("timeZone", timeZone);
+ setSelectedTimeZone(timeZone);
+ }}
+ timeZone={selectedTimeZone}
+ availability={availability.map((schedule) => ({
+ ...schedule,
+ startTime: new Date(schedule.startTime),
+ endTime: new Date(schedule.endTime),
+ }))}
+ />
+ )}
+ />
+ </div>
</div>
- </div>
-
- {hasPaymentIntegration && (
- <>
- <hr className="border-neutral-200" />
- <div className="block sm:flex">
- <div className="min-w-48 mb-4 sm:mb-0">
- <label
- htmlFor="payment"
- className="mt-2 flex text-sm font-medium text-neutral-700">
- {t("payment")}
- </label>
- </div>
- <div className="flex flex-col">
- <div className="w-full">
- <div className="block items-center sm:flex">
- <div className="w-full">
- <div className="relative flex items-start">
- <div className="flex h-5 items-center">
- <input
- onChange={(event) => {
- setRequirePayment(event.target.checked);
- if (!event.target.checked) {
- formMethods.setValue("price", 0);
- }
- }}
- id="requirePayment"
- name="requirePayment"
- type="checkbox"
- className="text-primary-600 focus:ring-primary-500 h-4 w-4 rounded border-gray-300"
- defaultChecked={requirePayment}
- />
- </div>
- <div className="text-sm ltr:ml-3 rtl:mr-3">
- <p className="text-neutral-900">
- {t("require_payment")} (0.5% +{" "}
- <IntlProvider locale="en">
- <FormattedNumber
- value={0.1}
- style="currency"
- currency={currency}
- />
- </IntlProvider>{" "}
- {t("commission_per_transaction")})
- </p>
- </div>
- </div>
- </div>
- </div>
+ {hasPaymentIntegration && (
+ <>
+ <hr className="border-neutral-200" />
+ <div className="block sm:flex">
+ <div className="min-w-48 mb-4 sm:mb-0">
+ <label
+ htmlFor="payment"
+ className="mt-2 flex text-sm font-medium text-neutral-700">
+ {t("payment")}
+ </label>
</div>
- {requirePayment && (
+
+ <div className="flex flex-col">
<div className="w-full">
<div className="block items-center sm:flex">
<div className="w-full">
- <div className="relative mt-1 rounded-sm shadow-sm">
- <Controller
- defaultValue={eventType.price}
- control={formMethods.control}
- name="price"
- render={({ field }) => (
- <input
- {...field}
- step="0.01"
- min="0.5"
- type="number"
- required
- className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 pl-2 pr-12 sm:text-sm"
- placeholder="Price"
- onChange={(e) => {
- field.onChange(e.target.valueAsNumber * 100);
- }}
- value={field.value > 0 ? field.value / 100 : 0}
- />
- )}
- />
- <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
- <span className="text-gray-500 sm:text-sm" id="duration">
- {new Intl.NumberFormat("en", {
- style: "currency",
- currency: currency,
- maximumSignificantDigits: 1,
- maximumFractionDigits: 0,
- })
- .format(0)
- .replace("0", "")}
- </span>
+ <div className="relative flex items-start">
+ <div className="flex h-5 items-center">
+ <input
+ onChange={(event) => {
+ setRequirePayment(event.target.checked);
+ if (!event.target.checked) {
+ formMethods.setValue("price", 0);
+ }
+ }}
+ id="requirePayment"
+ name="requirePayment"
+ type="checkbox"
+ className="text-primary-600 focus:ring-primary-500 h-4 w-4 rounded border-gray-300"
+ defaultChecked={requirePayment}
+ />
+ </div>
+ <div className="text-sm ltr:ml-3 rtl:mr-3">
+ <p className="text-neutral-900">
+ {t("require_payment")} (0.5% +{" "}
+ <IntlProvider locale="en">
+ <FormattedNumber
+ value={0.1}
+ style="currency"
+ currency={currency}
+ />
+ </IntlProvider>{" "}
+ {t("commission_per_transaction")})
+ </p>
</div>
</div>
</div>
</div>
</div>
- )}
+ {requirePayment && (
+ <div className="w-full">
+ <div className="block items-center sm:flex">
+ <div className="w-full">
+ <div className="relative mt-1 rounded-sm shadow-sm">
+ <Controller
+ defaultValue={eventType.price}
+ control={formMethods.control}
+ name="price"
+ render={({ field }) => (
+ <input
+ {...field}
+ step="0.01"
+ min="0.5"
+ type="number"
+ required
+ className="focus:border-primary-500 focus:ring-primary-500 block w-full rounded-sm border-gray-300 pl-2 pr-12 sm:text-sm"
+ placeholder="Price"
+ onChange={(e) => {
+ field.onChange(e.target.valueAsNumber * 100);
+ }}
+ value={field.value > 0 ? field.value / 100 : 0}
+ />
+ )}
+ />
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
+ <span className="text-gray-500 sm:text-sm" id="duration">
+ {new Intl.NumberFormat("en", {
+ style: "currency",
+ currency: currency,
+ maximumSignificantDigits: 1,
+ maximumFractionDigits: 0,
+ })
+ .format(0)
+ .replace("0", "")}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
</div>
- </div>
- </>
- )}
- </CollapsibleContent>
- </>
- {/* )} */}
- </Collapsible>
- <div className="mt-4 flex justify-end space-x-2 rtl:space-x-reverse">
- <Button href="/event-types" color="secondary" tabIndex={-1}>
- {t("cancel")}
- </Button>
- <Button type="submit" disabled={updateMutation.isLoading}>
- {t("update")}
- </Button>
- </div>
- </Form>
- </div>
- </div>
- <div className="mt-8 w-full min-w-[177px] px-2 ltr:ml-2 rtl:mr-2 sm:mt-0 sm:w-3/12 ">
- <div className="px-2">
- <Controller
- name="hidden"
- control={formMethods.control}
- defaultValue={eventType.hidden}
- render={({ field }) => (
- <Switch
- defaultChecked={field.value}
- onCheckedChange={(isChecked) => {
- formMethods.setValue("hidden", isChecked);
- }}
- label={t("hide_event_type")}
- />
- )}
- />
- </div>
- <div className="mt-4 space-y-1.5">
- <a
- href={permalink}
- target="_blank"
- rel="noreferrer"
- className="text-md inline-flex items-center rounded-sm px-2 py-1 text-sm font-medium text-neutral-700 hover:bg-gray-200 hover:text-gray-900">
- <ExternalLinkIcon className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" aria-hidden="true" />
- {t("preview")}
- </a>
- <button
- onClick={() => {
- navigator.clipboard.writeText(permalink);
- showToast("Link copied!", "success");
- }}
- type="button"
- className="text-md flex items-center rounded-sm px-2 py-1 text-sm font-medium text-gray-700 hover:bg-gray-200 hover:text-gray-900">
- <LinkIcon className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
- {t("copy_link")}
- </button>
- <Dialog>
- <DialogTrigger className="text-md flex items-center rounded-sm px-2 py-1 text-sm font-medium text-neutral-700 hover:bg-gray-200 hover:text-gray-900">
- <TrashIcon className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
- {t("delete")}
- </DialogTrigger>
- <ConfirmationDialogContent
- variety="danger"
- title={t("delete_event_type")}
- confirmBtnText={t("confirm_delete_event_type")}
- onConfirm={deleteEventTypeHandler}>
- {t("delete_event_type_description")}
- </ConfirmationDialogContent>
- </Dialog>
- </div>
- </div>
- </div>
- <Dialog open={showLocationModal} onOpenChange={setShowLocationModal}>
- <DialogContent asChild>
- <div className="inline-block transform rounded-sm bg-white px-4 pt-5 pb-4 text-left align-bottom shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6 sm:align-middle">
- <div className="mb-4 sm:flex sm:items-start">
- <div className="bg-secondary-100 mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full sm:mx-0 sm:h-10 sm:w-10">
- <LocationMarkerIcon className="text-primary-600 h-6 w-6" />
- </div>
- <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
- <h3 className="text-lg font-medium leading-6 text-gray-900" id="modal-title">
- {t("edit_location")}
- </h3>
- <div>
- <p className="text-sm text-gray-400">{t("this_input_will_shown_booking_this_event")}</p>
+ </>
+ )}
+ </CollapsibleContent>
+ </>
+ {/* )} */}
+ </Collapsible>
+ <div className="mt-4 flex justify-end space-x-2 rtl:space-x-reverse">
+ <Button href="/event-types" color="secondary" tabIndex={-1}>
+ {t("cancel")}
+ </Button>
+ <Button type="submit" disabled={updateMutation.isLoading}>
+ {t("update")}
+ </Button>
</div>
- </div>
+ </Form>
</div>
- <Form
- form={locationFormMethods}
- handleSubmit={async (values) => {
- const newLocation = values.locationType;
-
- let details = {};
- if (newLocation === LocationType.InPerson) {
- details = { address: values.locationAddress };
- }
-
- const existingIdx = formMethods
- .getValues("locations")
- .findIndex((loc) => values.locationType === loc.type);
- if (existingIdx !== -1) {
- const copy = formMethods.getValues("locations");
- copy[existingIdx] = {
- ...formMethods.getValues("locations")[existingIdx],
- ...details,
- };
- formMethods.setValue("locations", copy);
- } else {
- formMethods.setValue(
- "locations",
- formMethods.getValues("locations").concat({ type: values.locationType, ...details })
- );
- }
-
- setShowLocationModal(false);
- }}>
+ </div>
+ <div className="mt-8 w-full min-w-[177px] px-2 ltr:ml-2 rtl:mr-2 sm:mt-0 sm:w-3/12 ">
+ <div className="px-2">
<Controller
- name="locationType"
- control={locationFormMethods.control}
- render={() => (
- <Select
- maxMenuHeight={100}
- name="location"
- defaultValue={selectedLocation}
- options={locationOptions}
- isSearchable={false}
- classNamePrefix="react-select"
- className="react-select-container focus:border-primary-500 focus:ring-primary-500 my-4 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 sm:text-sm"
- onChange={(val) => {
- if (val) {
- locationFormMethods.setValue("locationType", val.value);
- setSelectedLocation(val);
- }
+ name="hidden"
+ control={formMethods.control}
+ defaultValue={eventType.hidden}
+ render={({ field }) => (
+ <Switch
+ defaultChecked={field.value}
+ onCheckedChange={(isChecked) => {
+ formMethods.setValue("hidden", isChecked);
}}
+ label={t("hide_event_type")}
/>
)}
/>
- <LocationOptions />
- <div className="mt-4 flex justify-end space-x-2">
- <Button onClick={() => setShowLocationModal(false)} type="button" color="secondary">
- {t("cancel")}
- </Button>
- <Button type="submit">{t("update")}</Button>
- </div>
- </Form>
+ </div>
+ <div className="mt-4 space-y-1.5">
+ <a
+ href={permalink}
+ target="_blank"
+ rel="noreferrer"
+ className="text-md inline-flex items-center rounded-sm px-2 py-1 text-sm font-medium text-neutral-700 hover:bg-gray-200 hover:text-gray-900">
+ <ExternalLinkIcon
+ className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2"
+ aria-hidden="true"
+ />
+ {t("preview")}
+ </a>
+ <button
+ onClick={() => {
+ navigator.clipboard.writeText(permalink);
+ showToast("Link copied!", "success");
+ }}
+ type="button"
+ className="text-md flex items-center rounded-sm px-2 py-1 text-sm font-medium text-gray-700 hover:bg-gray-200 hover:text-gray-900">
+ <LinkIcon className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
+ {t("copy_link")}
+ </button>
+ <Dialog>
+ <DialogTrigger className="text-md flex items-center rounded-sm px-2 py-1 text-sm font-medium text-neutral-700 hover:bg-gray-200 hover:text-gray-900">
+ <TrashIcon className="h-4 w-4 text-neutral-500 ltr:mr-2 rtl:ml-2" />
+ {t("delete")}
+ </DialogTrigger>
+ <ConfirmationDialogContent
+ variety="danger"
+ title={t("delete_event_type")}
+ confirmBtnText={t("confirm_delete_event_type")}
+ onConfirm={deleteEventTypeHandler}>
+ {t("delete_event_type_description")}
+ </ConfirmationDialogContent>
+ </Dialog>
+ </div>
</div>
- </DialogContent>
- </Dialog>
- <Controller
- name="customInputs"
- control={formMethods.control}
- defaultValue={eventType.customInputs.sort((a, b) => a.id - b.id) || []}
- render={() => (
- <Dialog open={selectedCustomInputModalOpen} onOpenChange={setSelectedCustomInputModalOpen}>
- <DialogContent asChild>
- <div className="inline-block transform rounded-sm bg-white px-4 pt-5 pb-4 text-left align-bottom shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6 sm:align-middle">
- <div className="mb-4 sm:flex sm:items-start">
- <div className="bg-secondary-100 mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full sm:mx-0 sm:h-10 sm:w-10">
- <PlusIcon className="text-primary-600 h-6 w-6" />
- </div>
- <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
- <h3 className="text-lg font-medium leading-6 text-gray-900" id="modal-title">
- {t("add_new_custom_input_field")}
- </h3>
- <div>
- <p className="text-sm text-gray-400">
- {t("this_input_will_shown_booking_this_event")}
- </p>
- </div>
+ </div>
+ <Dialog open={showLocationModal} onOpenChange={setShowLocationModal}>
+ <DialogContent asChild>
+ <div className="inline-block transform rounded-sm bg-white px-4 pt-5 pb-4 text-left align-bottom shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6 sm:align-middle">
+ <div className="mb-4 sm:flex sm:items-start">
+ <div className="bg-secondary-100 mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full sm:mx-0 sm:h-10 sm:w-10">
+ <LocationMarkerIcon className="text-primary-600 h-6 w-6" />
+ </div>
+ <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
+ <h3 className="text-lg font-medium leading-6 text-gray-900" id="modal-title">
+ {t("edit_location")}
+ </h3>
+ <div>
+ <p className="text-sm text-gray-400">{t("this_input_will_shown_booking_this_event")}</p>
</div>
</div>
- <CustomInputTypeForm
- selectedCustomInput={selectedCustomInput}
- onSubmit={(values) => {
- const customInput: EventTypeCustomInput = {
- id: -1,
- eventTypeId: -1,
- label: values.label,
- placeholder: values.placeholder,
- required: values.required,
- type: values.type,
+ </div>
+ <Form
+ form={locationFormMethods}
+ handleSubmit={async (values) => {
+ const newLocation = values.locationType;
+
+ let details = {};
+ if (newLocation === LocationType.InPerson) {
+ details = { address: values.locationAddress };
+ }
+
+ const existingIdx = formMethods
+ .getValues("locations")
+ .findIndex((loc) => values.locationType === loc.type);
+ if (existingIdx !== -1) {
+ const copy = formMethods.getValues("locations");
+ copy[existingIdx] = {
+ ...formMethods.getValues("locations")[existingIdx],
+ ...details,
};
-
- if (selectedCustomInput) {
- selectedCustomInput.label = customInput.label;
- selectedCustomInput.placeholder = customInput.placeholder;
- selectedCustomInput.required = customInput.required;
- selectedCustomInput.type = customInput.type;
- } else {
- setCustomInputs(customInputs.concat(customInput));
- formMethods.setValue(
- "customInputs",
- formMethods.getValues("customInputs").concat(customInput)
- );
- }
- setSelectedCustomInputModalOpen(false);
- }}
- onCancel={() => {
- setSelectedCustomInputModalOpen(false);
- }}
+ formMethods.setValue("locations", copy);
+ } else {
+ formMethods.setValue(
+ "locations",
+ formMethods.getValues("locations").concat({ type: values.locationType, ...details })
+ );
+ }
+
+ setShowLocationModal(false);
+ }}>
+ <Controller
+ name="locationType"
+ control={locationFormMethods.control}
+ render={() => (
+ <Select
+ maxMenuHeight={100}
+ name="location"
+ defaultValue={selectedLocation}
+ options={locationOptions}
+ isSearchable={false}
+ classNamePrefix="react-select"
+ className="react-select-container focus:border-primary-500 focus:ring-primary-500 my-4 block w-full min-w-0 flex-1 rounded-sm border border-gray-300 sm:text-sm"
+ onChange={(val) => {
+ if (val) {
+ locationFormMethods.setValue("locationType", val.value);
+ setSelectedLocation(val);
+ }
+ }}
+ />
+ )}
/>
- </div>
- </DialogContent>
- </Dialog>
- )}
- />
+ <LocationOptions />
+ <div className="mt-4 flex justify-end space-x-2">
+ <Button onClick={() => setShowLocationModal(false)} type="button" color="secondary">
+ {t("cancel")}
+ </Button>
+ <Button type="submit">{t("update")}</Button>
+ </div>
+ </Form>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Controller
+ name="customInputs"
+ control={formMethods.control}
+ defaultValue={eventType.customInputs.sort((a, b) => a.id - b.id) || []}
+ render={() => (
+ <Dialog open={selectedCustomInputModalOpen} onOpenChange={setSelectedCustomInputModalOpen}>
+ <DialogContent asChild>
+ <div className="inline-block transform rounded-sm bg-white px-4 pt-5 pb-4 text-left align-bottom shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6 sm:align-middle">
+ <div className="mb-4 sm:flex sm:items-start">
+ <div className="bg-secondary-100 mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full sm:mx-0 sm:h-10 sm:w-10">
+ <PlusIcon className="text-primary-600 h-6 w-6" />
+ </div>
+ <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
+ <h3 className="text-lg font-medium leading-6 text-gray-900" id="modal-title">
+ {t("add_new_custom_input_field")}
+ </h3>
+ <div>
+ <p className="text-sm text-gray-400">
+ {t("this_input_will_shown_booking_this_event")}
+ </p>
+ </div>
+ </div>
+ </div>
+ <CustomInputTypeForm
+ selectedCustomInput={selectedCustomInput}
+ onSubmit={(values) => {
+ const customInput: EventTypeCustomInput = {
+ id: -1,
+ eventTypeId: -1,
+ label: values.label,
+ placeholder: values.placeholder,
+ required: values.required,
+ type: values.type,
+ };
+
+ if (selectedCustomInput) {
+ selectedCustomInput.label = customInput.label;
+ selectedCustomInput.placeholder = customInput.placeholder;
+ selectedCustomInput.required = customInput.required;
+ selectedCustomInput.type = customInput.type;
+ } else {
+ setCustomInputs(customInputs.concat(customInput));
+ formMethods.setValue(
+ "customInputs",
+ formMethods.getValues("customInputs").concat(customInput)
+ );
+ }
+ setSelectedCustomInputModalOpen(false);
+ }}
+ onCancel={() => {
+ setSelectedCustomInputModalOpen(false);
+ }}
+ />
+ </div>
+ </DialogContent>
+ </Dialog>
+ )}
+ />
+ {isAdmin && <WebhookListContainer eventTypeId={props.eventType.id} />}
+ </ClientSuspense>
</Shell>
</div>
);
@@ -1604,6 +1621,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
accepted: true,
},
select: {
+ role: true,
user: {
select: userSelect,
},
diff --git a/apps/web/pages/integrations/index.tsx b/apps/web/pages/integrations/index.tsx
index c90deea2edb..ef7a64e8d95 100644
--- a/apps/web/pages/integrations/index.tsx
+++ b/apps/web/pages/integrations/index.tsx
@@ -1,9 +1,6 @@
-import { ChevronRightIcon, PencilAltIcon, SwitchHorizontalIcon, TrashIcon } from "@heroicons/react/outline";
import { ClipboardIcon } from "@heroicons/react/solid";
-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@radix-ui/react-collapsible";
import Image from "next/image";
import React, { useEffect, useState } from "react";
-import { Controller, useForm, useWatch } from "react-hook-form";
import { JSONObject } from "superjson/dist/types";
import { QueryCell } from "@lib/QueryCell";
@@ -11,17 +8,12 @@ import classNames from "@lib/classNames";
import { HttpError } from "@lib/core/http/error";
import { useLocale } from "@lib/hooks/useLocale";
import showToast from "@lib/notification";
-import { inferQueryOutput, trpc } from "@lib/trpc";
-import { WEBHOOK_TRIGGER_EVENTS } from "@lib/webhooks/constants";
+import { trpc } from "@lib/trpc";
import { ClientSuspense } from "@components/ClientSuspense";
-import { Dialog, DialogContent, DialogFooter, DialogTrigger } from "@components/Dialog";
import { List, ListItem, ListItemText, ListItemTitle } from "@components/List";
import Loader from "@components/Loader";
import Shell, { ShellSubHeading } from "@components/Shell";
-import { Tooltip } from "@components/Tooltip";
-import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";
-import { FieldsetLegend, Form, InputGroupBox, TextField, TextArea } from "@components/form/fields";
import { CalendarListContainer } from "@components/integrations/CalendarListContainer";
import ConnectIntegration from "@components/integrations/ConnectIntegrations";
import DisconnectIntegration from "@components/integrations/DisconnectIntegration";
@@ -29,367 +21,7 @@ import IntegrationListItem from "@components/integrations/IntegrationListItem";
import SubHeadingTitleWithConnections from "@components/integrations/SubHeadingTitleWithConnections";
import { Alert } from "@components/ui/Alert";
import Button from "@components/ui/Button";
-import Switch from "@components/ui/Switch";
-
-type TWebhook = inferQueryOutput<"viewer.webhook.list">[number];
-
-function WebhookListItem(props: { webhook: TWebhook; onEditWebhook: () => void }) {
- const { t } = useLocale();
- const utils = trpc.useContext();
- const deleteWebhook = trpc.useMutation("viewer.webhook.delete", {
- async onSuccess() {
- await utils.invalidateQueries(["viewer.webhook.list"]);
- },
- });
-
- return (
- <ListItem className="-mt-px flex w-full p-4">
- <div className="flex w-full justify-between">
- <div className="flex max-w-full flex-col truncate">
- <div className="flex space-y-1">
- <span
- className={classNames(
- "truncate text-sm",
- props.webhook.active ? "text-neutral-700" : "text-neutral-200"
- )}>
- {props.webhook.subscriberUrl}
- </span>
- </div>
- <div className="mt-2 flex">
- <span className="flex flex-col space-x-2 space-y-1 text-xs sm:flex-row sm:space-y-0 sm:rtl:space-x-reverse">
- {props.webhook.eventTriggers.map((eventTrigger, ind) => (
- <span
- key={ind}
- className={classNames(
- "w-max rounded-sm px-1 text-xs ",
- props.webhook.active ? "bg-blue-100 text-blue-700" : "bg-blue-50 text-blue-200"
- )}>
- {t(`${eventTrigger.toLowerCase()}`)}
- </span>
- ))}
- </span>
- </div>
- </div>
- <div className="flex">
- <Tooltip content={t("edit_webhook")}>
- <Button
- onClick={() => props.onEditWebhook()}
- color="minimal"
- size="icon"
- StartIcon={PencilAltIcon}
- className="ml-4 w-full self-center p-2"></Button>
- </Tooltip>
- <Dialog>
- <Tooltip content={t("delete_webhook")}>
- <DialogTrigger asChild>
- <Button
- onClick={(e) => {
- e.stopPropagation();
- }}
- color="minimal"
- size="icon"
- StartIcon={TrashIcon}
- className="ml-2 w-full self-center p-2"></Button>
- </DialogTrigger>
- </Tooltip>
- <ConfirmationDialogContent
- variety="danger"
- title={t("delete_webhook")}
- confirmBtnText={t("confirm_delete_webhook")}
- cancelBtnText={t("cancel")}
- onConfirm={() => deleteWebhook.mutate({ id: props.webhook.id })}>
- {t("delete_webhook_confirmation_message")}
- </ConfirmationDialogContent>
- </Dialog>
- </div>
- </div>
- </ListItem>
- );
-}
-
-function WebhookTestDisclosure() {
- const subscriberUrl: string = useWatch({ name: "subscriberUrl" });
- const payloadTemplate = useWatch({ name: "payloadTemplate" }) || null;
- const { t } = useLocale();
- const [open, setOpen] = useState(false);
- const mutation = trpc.useMutation("viewer.webhook.testTrigger", {
- onError(err) {
- showToast(err.message, "error");
- },
- });
-
- return (
- <Collapsible open={open} onOpenChange={() => setOpen(!open)}>
- <CollapsibleTrigger type="button" className={"flex w-full cursor-pointer"}>
- <ChevronRightIcon className={`${open ? "rotate-90 transform" : ""} h-5 w-5 text-neutral-500`} />
- <span className="text-sm font-medium text-gray-700">{t("webhook_test")}</span>
- </CollapsibleTrigger>
- <CollapsibleContent>
- <InputGroupBox className="space-y-0 border-0 px-0">
- <div className="flex justify-between bg-gray-50 p-2">
- <h3 className="self-center text-gray-700">{t("webhook_response")}</h3>
- <Button
- StartIcon={SwitchHorizontalIcon}
- type="button"
- color="minimal"
- disabled={mutation.isLoading}
- onClick={() => mutation.mutate({ url: subscriberUrl, type: "PING", payloadTemplate })}>
- {t("ping_test")}
- </Button>
- </div>
- <div className="border-8 border-gray-50 p-2 text-gray-500">
- {!mutation.data && <em>{t("no_data_yet")}</em>}
- {mutation.status === "success" && (
- <>
- <div
- className={classNames(
- "ml-auto w-max px-2 py-1 text-xs",
- mutation.data.ok ? "bg-green-50 text-green-500" : "bg-red-50 text-red-500"
- )}>
- {mutation.data.ok ? t("success") : t("failed")}
- </div>
- <pre className="overflow-x-auto">{JSON.stringify(mutation.data, null, 4)}</pre>
- </>
- )}
- </div>
- </InputGroupBox>
- </CollapsibleContent>
- </Collapsible>
- );
-}
-
-function WebhookDialogForm(props: {
- //
- defaultValues?: TWebhook;
- handleClose: () => void;
-}) {
- const { t } = useLocale();
- const utils = trpc.useContext();
- const supportedWebhookIntegrationList = ["https://discord.com/api/webhooks/"];
-
- const handleSubscriberUrlChange = (e) => {
- form.setValue("subscriberUrl", e.target.value);
- const ind = supportedWebhookIntegrationList.findIndex((integration) => {
- return e.target.value.includes(integration);
- });
- if (ind > -1) updateCustomTemplate(supportedWebhookIntegrationList[ind]);
- };
-
- const updateCustomTemplate = (webhookIntegration) => {
- setUseCustomPayloadTemplate(true);
- switch (webhookIntegration) {
- case "https://discord.com/api/webhooks/":
- form.setValue(
- "payloadTemplate",
- '{"content": "A new event has been scheduled","embeds": [{"color": 2697513,"fields": [{"name": "What","value": "{{title}} ({{type}})"},{"name": "When","value": "Start: {{startTime}} \\n End: {{endTime}} \\n Timezone: ({{organizer.timeZone}})"},{"name": "Who","value": "Organizer: {{organizer.name}} ({{organizer.email}}) \\n Booker: {{attendees.0.name}} ({{attendees.0.email}})" },{"name":"Description", "value":": {{description}}"},{"name":"Where","value":": {{location}} "}]}]}'
- );
- }
- };
-
- const {
- defaultValues = {
- id: "",
- eventTriggers: WEBHOOK_TRIGGER_EVENTS,
- subscriberUrl: "",
- active: true,
- payloadTemplate: null,
- } as Omit<TWebhook, "userId" | "createdAt">,
- } = props;
-
- const [useCustomPayloadTemplate, setUseCustomPayloadTemplate] = useState(!!defaultValues.payloadTemplate);
-
- const form = useForm({
- defaultValues,
- });
- return (
- <Form
- data-testid="WebhookDialogForm"
- form={form}
- handleSubmit={async (event) => {
- if (!useCustomPayloadTemplate && event.payloadTemplate) {
- event.payloadTemplate = null;
- }
- if (event.id) {
- await utils.client.mutation("viewer.webhook.edit", event);
- await utils.invalidateQueries(["viewer.webhook.list"]);
- showToast(t("webhook_updated_successfully"), "success");
- } else {
- await utils.client.mutation("viewer.webhook.create", event);
- await utils.invalidateQueries(["viewer.webhook.list"]);
- showToast(t("webhook_created_successfully"), "success");
- }
- props.handleClose();
- }}
- className="space-y-4">
- <input type="hidden" {...form.register("id")} />
- <fieldset className="space-y-2">
- <InputGroupBox className="border-0 bg-gray-50">
- <Controller
- control={form.control}
- name="active"
- render={({ field }) => (
- <Switch
- label={field.value ? t("webhook_enabled") : t("webhook_disabled")}
- defaultChecked={field.value}
- onCheckedChange={(isChecked) => {
- form.setValue("active", isChecked);
- }}
- />
- )}
- />
- </InputGroupBox>
- </fieldset>
- <TextField
- label={t("subscriber_url")}
- {...form.register("subscriberUrl")}
- required
- type="url"
- onChange={handleSubscriberUrlChange}
- />
-
- <fieldset className="space-y-2">
- <FieldsetLegend>{t("event_triggers")}</FieldsetLegend>
- <InputGroupBox className="border-0 bg-gray-50">
- {WEBHOOK_TRIGGER_EVENTS.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("payload_template")}</FieldsetLegend>
- <div className="space-x-3 text-sm rtl:space-x-reverse">
- <label>
- <input
- className="text-neutral-900 focus:ring-neutral-500"
- type="radio"
- name="useCustomPayloadTemplate"
- onChange={(value) => setUseCustomPayloadTemplate(!value.target.checked)}
- defaultChecked={!useCustomPayloadTemplate}
- />{" "}
- Default
- </label>
- <label>
- <input
- className="text-neutral-900 focus:ring-neutral-500"
- onChange={(value) => setUseCustomPayloadTemplate(value.target.checked)}
- name="useCustomPayloadTemplate"
- type="radio"
- defaultChecked={useCustomPayloadTemplate}
- />{" "}
- Custom
- </label>
- </div>
- {useCustomPayloadTemplate && (
- <TextArea
- {...form.register("payloadTemplate")}
- defaultValue={useCustomPayloadTemplate && (defaultValues.payloadTemplate || "")}
- rows={3}
- />
- )}
- </fieldset>
- <WebhookTestDisclosure />
- <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 WebhookListContainer() {
- const { t } = useLocale();
- const query = trpc.useQuery(["viewer.webhook.list"], { suspense: true });
-
- const [newWebhookModal, setNewWebhookModal] = useState(false);
- const [editModalOpen, setEditModalOpen] = useState(false);
- const [editing, setEditing] = useState<TWebhook | null>(null);
- return (
- <QueryCell
- query={query}
- success={({ data }) => (
- <>
- <ShellSubHeading className="mt-10" title={t("Webhooks")} subtitle={t("receive_cal_meeting_data")} />
- <List>
- <ListItem className={classNames("flex-col")}>
- <div
- className={classNames("flex w-full flex-1 items-center space-x-2 p-3 rtl:space-x-reverse")}>
- <Image width={40} height={40} src="/integrations/webhooks.svg" alt="Webhooks" />
- <div className="flex-grow truncate pl-2">
- <ListItemTitle component="h3">Webhooks</ListItemTitle>
- <ListItemText component="p">{t("automation")}</ListItemText>
- </div>
- <div>
- <Button
- color="secondary"
- onClick={() => setNewWebhookModal(true)}
- data-testid="new_webhook">
- {t("new_webhook")}
- </Button>
- </div>
- </div>
- </ListItem>
- </List>
-
- {data.length ? (
- <List>
- {data.map((item) => (
- <WebhookListItem
- key={item.id}
- webhook={item}
- onEditWebhook={() => {
- setEditing(item);
- setEditModalOpen(true);
- }}
- />
- ))}
- </List>
- ) : null}
-
- {/* 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>
- </>
- )}
- />
- );
-}
+import WebhookListContainer from "@components/webhook/WebhookListContainer";
function IframeEmbedContainer() {
const { t } = useLocale();
diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json
index de44b799f6c..1291da99e79 100644
--- a/apps/web/public/static/locales/en/common.json
+++ b/apps/web/public/static/locales/en/common.json
@@ -314,6 +314,7 @@
"create_new_webhook_to_account": "Create a new webhook to your account",
"new_webhook": "New Webhook",
"receive_cal_meeting_data": "Receive Cal meeting data at a specified URL, in real-time, when an event is scheduled or cancelled.",
+ "receive_cal_event_meeting_data": "Receive Cal meeting data at a specified URL, in real-time, when this event is scheduled or cancelled.",
"responsive_fullscreen_iframe": "Responsive full screen iframe",
"loading": "Loading...",
"standard_iframe": "Standard iframe",
diff --git a/apps/web/server/routers/viewer/webhook.tsx b/apps/web/server/routers/viewer/webhook.tsx
index 02c8605508c..579e95c5b66 100644
--- a/apps/web/server/routers/viewer/webhook.tsx
+++ b/apps/web/server/routers/viewer/webhook.tsx
@@ -10,7 +10,19 @@ import { getTranslation } from "@server/lib/i18n";
export const webhookRouter = createProtectedRouter()
.query("list", {
- async resolve({ ctx }) {
+ input: z
+ .object({
+ eventTypeId: z.number().optional(),
+ })
+ .optional(),
+ async resolve({ ctx, input }) {
+ if (input?.eventTypeId) {
+ return await ctx.prisma.webhook.findMany({
+ where: {
+ eventTypeId: input.eventTypeId,
+ },
+ });
+ }
return await ctx.prisma.webhook.findMany({
where: {
userId: ctx.user.id,
@@ -24,8 +36,17 @@ export const webhookRouter = createProtectedRouter()
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array(),
active: z.boolean(),
payloadTemplate: z.string().nullable(),
+ eventTypeId: z.number().optional(),
}),
async resolve({ ctx, input }) {
+ if (input.eventTypeId) {
+ return await ctx.prisma.webhook.create({
+ data: {
+ id: v4(),
+ ...input,
+ },
+ });
+ }
return await ctx.prisma.webhook.create({
data: {
id: v4(),
@@ -42,17 +63,26 @@ export const webhookRouter = createProtectedRouter()
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array().optional(),
active: z.boolean().optional(),
payloadTemplate: z.string().nullable(),
+ eventTypeId: z.number().optional(),
}),
async resolve({ ctx, input }) {
const { id, ...data } = input;
- const webhook = await ctx.prisma.webhook.findFirst({
- where: {
- userId: ctx.user.id,
- id,
- },
- });
+ const webhook = input.eventTypeId
+ ? await ctx.prisma.webhook.findFirst({
+ where: {
+ eventTypeId: input.eventTypeId,
+ id,
+ },
+ })
+ : await ctx.prisma.webhook.findFirst({
+ where: {
+ userId: ctx.user.id,
+ id,
+ },
+ });
if (!webhook) {
// user does not own this webhook
+ // team event doesn't own this webhook
return null;
}
return await ctx.prisma.webhook.update({
@@ -66,23 +96,36 @@ export const webhookRouter = createProtectedRouter()
.mutation("delete", {
input: z.object({
id: z.string(),
+ eventTypeId: z.number().optional(),
}),
async resolve({ ctx, input }) {
const { id } = input;
- await ctx.prisma.user.update({
- where: {
- id: ctx.user.id,
- },
- data: {
- webhooks: {
- delete: {
- id,
+ input.eventTypeId
+ ? await ctx.prisma.eventType.update({
+ where: {
+ id: input.eventTypeId,
},
- },
- },
- });
-
+ data: {
+ webhooks: {
+ delete: {
+ id,
+ },
+ },
+ },
+ })
+ : await ctx.prisma.user.update({
+ where: {
+ id: ctx.user.id,
+ },
+ data: {
+ webhooks: {
+ delete: {
+ id,
+ },
+ },
+ },
+ });
return {
id,
};
diff --git a/packages/prisma/migrations/20220217093836_add_webhook_for_event/migration.sql b/packages/prisma/migrations/20220217093836_add_webhook_for_event/migration.sql
new file mode 100644
index 00000000000..a1c68ce1244
--- /dev/null
+++ b/packages/prisma/migrations/20220217093836_add_webhook_for_event/migration.sql
@@ -0,0 +1,6 @@
+-- AlterTable
+ALTER TABLE "Webhook" ADD COLUMN "eventTypeId" INTEGER,
+ALTER COLUMN "userId" DROP NOT NULL;
+
+-- AddForeignKey
+ALTER TABLE "Webhook" ADD CONSTRAINT "Webhook_eventTypeId_fkey" FOREIGN KEY ("eventTypeId") REFERENCES "EventType"("id") ON DELETE CASCADE ON UPDATE CASCADE;
\ No newline at end of file
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index f37e28ecb1d..9f38dd52121 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -46,6 +46,7 @@ model EventType {
teamId Int?
bookings Booking[]
availability Availability[]
+ webhooks Webhook[]
destinationCalendar DestinationCalendar?
eventName String?
customInputs EventTypeCustomInput[]
@@ -345,11 +346,13 @@ enum WebhookTriggerEvents {
model Webhook {
id String @id @unique
- userId Int
+ userId Int?
+ eventTypeId Int?
subscriberUrl String
payloadTemplate String?
createdAt DateTime @default(now())
active Boolean @default(true)
eventTriggers WebhookTriggerEvents[]
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
+ eventType EventType? @relation(fields: [eventTypeId], references: [id], onDelete: Cascade)
}
diff --git a/packages/prisma/zod/eventtype.ts b/packages/prisma/zod/eventtype.ts
new file mode 100644
index 00000000000..5a62e528418
--- /dev/null
+++ b/packages/prisma/zod/eventtype.ts
@@ -0,0 +1,65 @@
+import * as z from "zod"
+import * as imports from "../zod-utils"
+import { PeriodType, SchedulingType } from "@prisma/client"
+import { CompleteUser, UserModel, CompleteTeam, TeamModel, CompleteBooking, BookingModel, CompleteAvailability, AvailabilityModel, CompleteWebhook, WebhookModel, CompleteDestinationCalendar, DestinationCalendarModel, CompleteEventTypeCustomInput, EventTypeCustomInputModel, CompleteSchedule, ScheduleModel } from "./index"
+
+// Helper schema for JSON fields
+type Literal = boolean | number | string
+type Json = Literal | { [key: string]: Json } | Json[]
+const literalSchema = z.union([z.string(), z.number(), z.boolean()])
+const jsonSchema: z.ZodSchema<Json> = z.lazy(() => z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]))
+
+export const _EventTypeModel = z.object({
+ id: z.number().int(),
+ title: z.string().nonempty(),
+ slug: imports.eventTypeSlug,
+ description: z.string().nullish(),
+ position: z.number().int(),
+ locations: imports.eventTypeLocations,
+ length: z.number().int(),
+ hidden: z.boolean(),
+ userId: z.number().int().nullish(),
+ teamId: z.number().int().nullish(),
+ eventName: z.string().nullish(),
+ timeZone: z.string().nullish(),
+ periodType: z.nativeEnum(PeriodType),
+ periodStartDate: z.date().nullish(),
+ periodEndDate: z.date().nullish(),
+ periodDays: z.number().int().nullish(),
+ periodCountCalendarDays: z.boolean().nullish(),
+ requiresConfirmation: z.boolean(),
+ disableGuests: z.boolean(),
+ minimumBookingNotice: z.number().int(),
+ schedulingType: z.nativeEnum(SchedulingType).nullish(),
+ price: z.number().int(),
+ currency: z.string(),
+ slotInterval: z.number().int().nullish(),
+ metadata: jsonSchema,
+})
+
+export interface CompleteEventType extends z.infer<typeof _EventTypeModel> {
+ users: CompleteUser[]
+ team?: CompleteTeam | null
+ bookings: CompleteBooking[]
+ availability: CompleteAvailability[]
+ webhooks: CompleteWebhook[]
+ destinationCalendar?: CompleteDestinationCalendar | null
+ customInputs: CompleteEventTypeCustomInput[]
+ Schedule: CompleteSchedule[]
+}
+
+/**
+ * EventTypeModel contains all relations on your model in addition to the scalars
+ *
+ * NOTE: Lazy required in case of potential circular dependencies within schema
+ */
+export const EventTypeModel: z.ZodSchema<CompleteEventType> = z.lazy(() => _EventTypeModel.extend({
+ users: UserModel.array(),
+ team: TeamModel.nullish(),
+ bookings: BookingModel.array(),
+ availability: AvailabilityModel.array(),
+ webhooks: WebhookModel.array(),
+ destinationCalendar: DestinationCalendarModel.nullish(),
+ customInputs: EventTypeCustomInputModel.array(),
+ Schedule: ScheduleModel.array(),
+}))
diff --git a/packages/prisma/zod/webhook.ts b/packages/prisma/zod/webhook.ts
new file mode 100644
index 00000000000..c6a86f1dffa
--- /dev/null
+++ b/packages/prisma/zod/webhook.ts
@@ -0,0 +1,30 @@
+import * as z from "zod"
+import * as imports from "../zod-utils"
+import { WebhookTriggerEvents } from "@prisma/client"
+import { CompleteUser, UserModel, CompleteEventType, EventTypeModel } from "./index"
+
+export const _WebhookModel = z.object({
+ id: z.string(),
+ userId: z.number().int().nullish(),
+ eventTypeId: z.number().int().nullish(),
+ subscriberUrl: z.string(),
+ payloadTemplate: z.string().nullish(),
+ createdAt: z.date(),
+ active: z.boolean(),
+ eventTriggers: z.nativeEnum(WebhookTriggerEvents).array(),
+})
+
+export interface CompleteWebhook extends z.infer<typeof _WebhookModel> {
+ user?: CompleteUser | null
+ eventType?: CompleteEventType | null
+}
+
+/**
+ * WebhookModel contains all relations on your model in addition to the scalars
+ *
+ * NOTE: Lazy required in case of potential circular dependencies within schema
+ */
+export const WebhookModel: z.ZodSchema<CompleteWebhook> = z.lazy(() => _WebhookModel.extend({
+ user: UserModel.nullish(),
+ eventType: EventTypeModel.nullish(),
+}))
diff --git a/turbo.json b/turbo.json
index 2327d01e407..b4167809c55 100644
--- a/turbo.json
+++ b/turbo.json
@@ -7,7 +7,9 @@
"dependsOn": ["$DATABASE_URL"],
"outputs": ["zod/**"]
},
- "@calcom/prisma#db-deploy": {},
+ "@calcom/prisma#db-deploy": {
+ "dependsOn": ["$DATABASE_URL"]
+ },
"@calcom/prisma#db-reset": {
"cache": false
},
@@ -18,7 +20,7 @@
"@calcom/web#build": {
"dependsOn": [
"^build",
- "@calcom/prisma#build",
+ "@calcom/prisma#db-deploy",
"$BASE_URL",
"$CALENDSO_ENCRYPTION_KEY",
"$CRON_API_KEY",
@@ -53,6 +55,7 @@
"$TANDEM_BASE_URL",
"$TANDEM_CLIENT_ID",
"$TANDEM_CLIENT_SECRET",
+ "WEBSITE_BASE_URL",
"$ZOOM_CLIENT_ID",
"$ZOOM_CLIENT_SECRET"
],