Webhooks for team event-types (#6120)

* add webhooks tab for team event types

* show nr of active event types

* type fixes + show team webhooks only in event type single view

* adding and deleting webhook

* fix disabling and enabling team webhooks

* add editing webhook

* code clean up

* add installed apps

* code clean up

* fix reserved subscriber url when creating event

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Omar López <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-12-20 15:34:37 -07:00
1 parent 540bf3a1cb
commit f373c9d818
7 files changed
+239 -11

No files matched your search

@@ -0,0 +1,178 @@
import { EventTypeSetupInfered, FormValues } from "pages/event-types/[type]";
import { useState } from "react";
import { WebhookForm } from "@calcom/features/webhooks/components";
import { WebhookFormSubmitData } from "@calcom/features/webhooks/components/WebhookForm";
import WebhookListItem from "@calcom/features/webhooks/components/WebhookListItem";
import { APP_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Webhook } from "@calcom/prisma/client";
import { trpc } from "@calcom/trpc/react";
import { Button, Dialog, DialogContent, EmptyScreen, Icon, showToast } from "@calcom/ui";
export const EventTeamWebhooksTab = ({
eventType,
team,
}: Pick<EventTypeSetupInfered, "eventType" | "team">) => {
const { t } = useLocale();
const utils = trpc.useContext();
const { data: webhooks } = trpc.viewer.webhook.list.useQuery({ eventTypeId: eventType.id });
const { data: installedApps, isLoading } = trpc.viewer.integrations.useQuery({
variant: "other",
onlyInstalled: true,
});
const [createModalOpen, setCreateModalOpen] = useState(false);
const [editModalOpen, setEditModalOpen] = useState(false);
const [webhookToEdit, setWebhookToEdit] = useState<Webhook>();
const subscriberUrlReserved = (subscriberUrl: string, id?: string): boolean => {
return !!webhooks?.find(
(webhook) => webhook.subscriberUrl === subscriberUrl && (!id || webhook.id !== id)
);
};
const editWebhookMutation = trpc.viewer.webhook.edit.useMutation({
async onSuccess() {
setEditModalOpen(false);
await utils.viewer.webhook.list.invalidate();
showToast(t("webhook_updated_successfully"), "success");
},
onError(error) {
showToast(`${error.message}`, "error");
},
});
const createWebhookMutation = trpc.viewer.webhook.create.useMutation({
async onSuccess() {
showToast(t("webhook_created_successfully"), "success");
await utils.viewer.webhook.list.invalidate();
setCreateModalOpen(false);
},
onError(error) {
showToast(`${error.message}`, "error");
},
});
const onCreateWebhook = async (values: WebhookFormSubmitData) => {
if (subscriberUrlReserved(values.subscriberUrl, values.id)) {
showToast(t("webhook_subscriber_url_reserved"), "error");
return;
}
if (!values.payloadTemplate) {
values.payloadTemplate = null;
}
createWebhookMutation.mutate({
subscriberUrl: values.subscriberUrl,
eventTriggers: values.eventTriggers,
active: values.active,
payloadTemplate: values.payloadTemplate,
secret: values.secret,
eventTypeId: eventType.id,
});
};
const NewWebhookButton = () => {
const { t } = useLocale();
return (
<Button
color="secondary"
data-testid="new_webhook"
StartIcon={Icon.FiPlus}
onClick={() => setCreateModalOpen(true)}>
{t("new_webhook")}
</Button>
);
};
return (
<div>
{team && webhooks && !isLoading && (
<>
<div>
<div>
<>
{webhooks.length ? (
<>
<div className="mt-4 mb-8 rounded-md border">
{webhooks.map((webhook, index) => {
return (
<WebhookListItem
key={webhook.id}
webhook={webhook}
lastItem={webhooks.length === index + 1}
onEditWebhook={() => {
setEditModalOpen(true);
setWebhookToEdit(webhook);
}}
/>
);
})}
</div>
<NewWebhookButton />
</>
) : (
<EmptyScreen
Icon={Icon.FiLink}
headline={t("create_your_first_webhook")}
description={t("create_your_first_team_webhook_description", { appName: APP_NAME })}
buttonRaw={<NewWebhookButton />}
/>
)}
</>
</div>
</div>
{/* New webhook dialog */}
<Dialog open={createModalOpen} onOpenChange={(isOpen) => !isOpen && setCreateModalOpen(false)}>
<DialogContent title={t("create_webhook")} description={t("create_webhook_team_event_type")}>
<WebhookForm
onSubmit={onCreateWebhook}
onCancel={() => setCreateModalOpen(false)}
apps={installedApps?.items.map((app) => app.slug)}
/>
</DialogContent>
</Dialog>
{/* Edit webhook dialog */}
<Dialog open={editModalOpen} onOpenChange={(isOpen) => !isOpen && setEditModalOpen(false)}>
<DialogContent title={t("edit_webhook")}>
<WebhookForm
webhook={webhookToEdit}
apps={installedApps?.items.map((app) => app.slug)}
onCancel={() => setEditModalOpen(false)}
onSubmit={(values: WebhookFormSubmitData) => {
if (subscriberUrlReserved(values.subscriberUrl, webhookToEdit?.id || "")) {
showToast(t("webhook_subscriber_url_reserved"), "error");
return;
}
if (values.changeSecret) {
values.secret = values.newSecret.length ? values.newSecret : null;
}
if (!values.payloadTemplate) {
values.payloadTemplate = null;
}
editWebhookMutation.mutate({
id: webhookToEdit?.id || "",
subscriberUrl: values.subscriberUrl,
eventTriggers: values.eventTriggers,
active: values.active,
payloadTemplate: values.payloadTemplate,
secret: values.secret,
eventTypeId: webhookToEdit?.eventTypeId || undefined,
});
}}
/>
</DialogContent>
</Dialog>
</>
)}
</div>
);
};
@@ -149,13 +149,20 @@ function EventTypeSingleLayout({
enabledWorkflowsNumber,
});
// If there is a team put this navigation item within the tabs
if (team)
if (team) {
navigation.splice(2, 0, {
name: "scheduling_type",
href: `/event-types/${eventType.id}?tabName=team`,
icon: Icon.FiUsers,
info: eventType.schedulingType === "COLLECTIVE" ? "collective" : "round_robin",
});
navigation.push({
name: "webhooks",
href: `/event-types/${eventType.id}?tabName=webhooks`,
icon: Icon.FiLink,
info: `${eventType.webhooks.filter((webhook) => webhook.active).length} ${t("active")}`,
});
}
return navigation;
}, [t, eventType, installedAppsNumber, enabledAppsNumber, enabledWorkflowsNumber, team]);
+25 -2
View File
@@ -36,6 +36,7 @@ import { EventLimitsTab } from "@components/eventtype/EventLimitsTab";
import { EventRecurringTab } from "@components/eventtype/EventRecurringTab";
import { EventSetupTab } from "@components/eventtype/EventSetupTab";
import { EventTeamTab } from "@components/eventtype/EventTeamTab";
import { EventTeamWebhooksTab } from "@components/eventtype/EventTeamWebhooksTab";
import { EventTypeSingleLayout } from "@components/eventtype/EventTypeSingleLayout";
import EventWorkflowsTab from "@components/eventtype/EventWorkfowsTab";
@@ -93,7 +94,17 @@ export type CustomInputParsed = typeof customInputSchema._output;
const querySchema = z.object({
tabName: z
.enum(["setup", "availability", "apps", "limits", "recurring", "team", "advanced", "workflows"])
.enum([
"setup",
"availability",
"apps",
"limits",
"recurring",
"team",
"advanced",
"workflows",
"webhooks",
])
.optional()
.default("setup"),
});
@@ -237,6 +248,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
workflows={eventType.workflows.map((workflowOnEventType) => workflowOnEventType.workflow)}
/>
),
webhooks: <EventTeamWebhooksTab eventType={eventType} team={team} />,
} as const;
return (
@@ -248,7 +260,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
team={team}
isUpdateMutationLoading={updateMutation.isLoading}
formMethods={formMethods}
disableBorder={tabName === "apps" || tabName === "workflows"}
disableBorder={tabName === "apps" || tabName === "workflows" || tabName === "webhooks"}
currentUserMembership={props.currentUserMembership}>
<Form
form={formMethods}
@@ -436,6 +448,17 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
destinationCalendar: true,
seatsPerTimeSlot: true,
seatsShowAttendees: true,
webhooks: {
select: {
id: true,
subscriberUrl: true,
payloadTemplate: true,
active: true,
eventTriggers: true,
secret: true,
eventTypeId: true,
},
},
workflows: {
include: {
workflow: {
@@ -1467,5 +1467,7 @@
"no_availability_in_month": "No availability in {{month}}",
"view_next_month": "View next month",
"send_code" : "Send code",
"number_verified": "Number Verified"
"number_verified": "Number Verified",
"create_your_first_team_webhook_description": "Create your first webhook for this team event type",
"create_webhook_team_event_type": "Create a webhook for this team event type"
}
@@ -42,6 +42,7 @@ const WebhookForm = (props: {
webhook?: WebhookFormData;
apps?: (keyof typeof WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP_V2)[];
onSubmit: (event: WebhookFormSubmitData) => void;
onCancel?: () => void;
}) => {
const { apps = [] } = props;
const { t } = useLocale();
@@ -252,7 +253,11 @@ const WebhookForm = (props: {
</div>
<div className="mt-12 flex place-content-end space-x-4">
<Button type="button" color="minimal" href={`${WEBAPP_URL}/settings/developer/webhooks`}>
<Button
type="button"
color="minimal"
onClick={props.onCancel}
{...(!props.onCancel ? { href: `${WEBAPP_URL}/settings/developer/webhooks` } : {})}>
{t("cancel")}
</Button>
<Button type="submit" loading={formMethods.formState.isSubmitting}>
@@ -1,12 +1,22 @@
import { WebhookTriggerEvents } from "@prisma/client";
import classNames from "@calcom/lib/classNames";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { RouterOutputs, trpc } from "@calcom/trpc/react";
import { Badge, Button, Icon, showToast, Switch, Tooltip } from "@calcom/ui";
export type TWebhook = RouterOutputs["viewer"]["webhook"]["list"][number];
type WebhookProps = {
id: string;
subscriberUrl: string;
payloadTemplate: string | null;
active: boolean;
eventTriggers: WebhookTriggerEvents[];
secret: string | null;
eventTypeId: number | null;
};
export default function WebhookListItem(props: {
webhook: TWebhook;
webhook: WebhookProps;
onEditWebhook: () => void;
lastItem: boolean;
}) {
@@ -50,6 +60,7 @@ export default function WebhookListItem(props: {
id: webhook.id,
active: !webhook.active,
payloadTemplate: webhook.payloadTemplate,
eventTypeId: webhook.eventTypeId || undefined,
})
}
/>
@@ -62,7 +73,7 @@ export default function WebhookListItem(props: {
size="icon"
onClick={() => {
// TODO: Confimation dialog before deleting
deleteWebhook.mutate({ id: webhook.id });
deleteWebhook.mutate({ id: webhook.id, eventTypeId: webhook.eventTypeId || undefined });
}}
/>
</div>
@@ -34,12 +34,14 @@ const NewWebhookView = () => {
},
});
const subscriberUrlReserved = (subscriberUrl: string, id: string): boolean => {
return !!webhooks?.find((webhook) => webhook.subscriberUrl === subscriberUrl && webhook.id !== id);
const subscriberUrlReserved = (subscriberUrl: string, id?: string): boolean => {
return !!webhooks?.find(
(webhook) => webhook.subscriberUrl === subscriberUrl && (!id || webhook.id !== id)
);
};
const onCreateWebhook = async (values: WebhookFormSubmitData) => {
if (values.id && subscriberUrlReserved(values.subscriberUrl, values.id)) {
if (subscriberUrlReserved(values.subscriberUrl, values.id)) {
showToast(t("webhook_subscriber_url_reserved"), "error");
return;
}