Feature: Routing Forms Webhook for Form Responses (#3444)

Co-authored-by: Omar López <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2022-07-20 18:30:57 +00:00
1 parent b47c75304e
commit 5b7cd476a7
15 files changed
+164 -22

No files matched your search

@@ -3,14 +3,13 @@ import { Controller, useForm } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import showToast from "@calcom/lib/notification";
import { Tooltip } from "@calcom/ui";
import Button from "@calcom/ui/Button";
import { DialogFooter } from "@calcom/ui/Dialog";
import Switch from "@calcom/ui/Switch";
import { FieldsetLegend, Form, InputGroupBox, TextArea, TextField } from "@calcom/ui/form/fields";
import { trpc } from "@lib/trpc";
import { WEBHOOK_TRIGGER_EVENTS } from "@lib/webhooks/constants";
import { WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP } from "@lib/webhooks/constants";
import customTemplate, { hasTemplateIntegration } from "@lib/webhooks/integrationTemplate";
import { TWebhook } from "@components/webhook/WebhookListItem";
@@ -19,14 +18,20 @@ import WebhookTestDisclosure from "@components/webhook/WebhookTestDisclosure";
export default function WebhookDialogForm(props: {
eventTypeId?: number;
defaultValues?: TWebhook;
app?: string;
handleClose: () => void;
}) {
const { t } = useLocale();
const utils = trpc.useContext();
const appId = props.app;
const triggers = !appId
? WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP["core"]
: WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP[appId as keyof typeof WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP];
const {
defaultValues = {
id: "",
eventTriggers: WEBHOOK_TRIGGER_EVENTS,
eventTriggers: triggers,
subscriberUrl: "",
active: true,
payloadTemplate: null,
@@ -60,8 +65,8 @@ export default function WebhookDialogForm(props: {
form={form}
handleSubmit={async (event) => {
const e = changeSecret
? { ...event, eventTypeId: props.eventTypeId }
: { ...event, secret: currentSecret, eventTypeId: props.eventTypeId };
? { ...event, eventTypeId: props.eventTypeId, appId }
: { ...event, secret: currentSecret, eventTypeId: props.eventTypeId, appId };
if (!useCustomPayloadTemplate && event.payloadTemplate) {
event.payloadTemplate = null;
}
@@ -115,7 +120,7 @@ export default function WebhookDialogForm(props: {
<fieldset className="space-y-2">
<FieldsetLegend>{t("event_triggers")}</FieldsetLegend>
<InputGroupBox className="border-0 bg-gray-50">
{WEBHOOK_TRIGGER_EVENTS.map((key) => (
{triggers.map((key) => (
<Controller
key={key}
control={form.control}
@@ -17,12 +17,16 @@ export type WebhookListContainerType = {
title: string;
subtitle: string;
eventTypeId?: number;
appId?: string;
};
export default function WebhookListContainer(props: WebhookListContainerType) {
const query = trpc.useQuery(["viewer.webhook.list", { eventTypeId: props.eventTypeId }], {
suspense: true,
});
const query = trpc.useQuery(
["viewer.webhook.list", { eventTypeId: props.eventTypeId, appId: props.appId }],
{
suspense: true,
}
);
const [newWebhookModal, setNewWebhookModal] = useState(false);
const [editModalOpen, setEditModalOpen] = useState(false);
const [editing, setEditing] = useState<TWebhook | null>(null);
@@ -66,6 +70,7 @@ export default function WebhookListContainer(props: WebhookListContainerType) {
<Dialog open={newWebhookModal} onOpenChange={(isOpen) => !isOpen && setNewWebhookModal(false)}>
<DialogContent>
<WebhookDialogForm
app={props.appId}
eventTypeId={props.eventTypeId}
handleClose={() => setNewWebhookModal(false)}
/>
@@ -76,6 +81,7 @@ export default function WebhookListContainer(props: WebhookListContainerType) {
<DialogContent>
{editing && (
<WebhookDialogForm
app={props.appId}
key={editing.id}
eventTypeId={props.eventTypeId || undefined}
handleClose={() => setEditModalOpen(false)}
+13 -4
View File
@@ -1,8 +1,17 @@
import { WebhookTriggerEvents } from "@prisma/client";
// this is exported as we can't use `WebhookTriggerEvents` in the frontend straight-off
export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
core: [
WebhookTriggerEvents.BOOKING_CANCELLED,
WebhookTriggerEvents.BOOKING_CREATED,
WebhookTriggerEvents.BOOKING_RESCHEDULED,
] as ["BOOKING_CANCELLED", "BOOKING_CREATED", "BOOKING_RESCHEDULED"],
routing_forms: [WebhookTriggerEvents.FORM_SUBMITTED] as ["FORM_SUBMITTED"],
};
export const WEBHOOK_TRIGGER_EVENTS = [
WebhookTriggerEvents.BOOKING_CANCELLED,
WebhookTriggerEvents.BOOKING_CREATED,
WebhookTriggerEvents.BOOKING_RESCHEDULED,
] as ["BOOKING_CANCELLED", "BOOKING_CREATED", "BOOKING_RESCHEDULED"];
...WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP.core,
...WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP.routing_forms,
] as ["BOOKING_CANCELLED", "BOOKING_CREATED", "BOOKING_RESCHEDULED", "FORM_SUBMITTED"];
+28 -4
View File
@@ -34,10 +34,7 @@ const sendPayload = async (
bookingId?: number;
}
) => {
const { subscriberUrl, appId, payloadTemplate: template } = webhook;
if (!subscriberUrl || !data) {
throw new Error("Missing required elements to send webhook payload.");
}
const { appId, payloadTemplate: template } = webhook;
const contentType =
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
@@ -59,6 +56,33 @@ const sendPayload = async (
});
}
return _sendPayload(secretKey, triggerEvent, createdAt, webhook, body, contentType);
};
export const sendGenericWebhookPayload = async (
secretKey: string | null,
triggerEvent: string,
createdAt: string,
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
data: Record<string, unknown>
) => {
const body = JSON.stringify(data);
return _sendPayload(secretKey, triggerEvent, createdAt, webhook, body, "application/json");
};
const _sendPayload = async (
secretKey: string | null,
triggerEvent: string,
createdAt: string,
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
body: string,
contentType: "application/json" | "application/x-www-form-urlencoded"
) => {
const { subscriberUrl } = webhook;
if (!subscriberUrl || !body) {
throw new Error("Missing required elements to send webhook payload.");
}
const secretSignature = secretKey
? createHmac("sha256", secretKey).update(`${body}`).digest("hex")
: "no-secret-provided";
+16 -1
View File
@@ -1,15 +1,30 @@
import { useLocale } from "@calcom/lib/hooks/useLocale";
import ApiKeyListContainer from "@ee/components/apiKeys/ApiKeyListContainer";
import { trpc } from "@lib/trpc";
import SettingsShell from "@components/SettingsShell";
import WebhookListContainer from "@components/webhook/WebhookListContainer";
export default function Settings() {
const { t } = useLocale();
const { data: routingForms } = trpc.useQuery([
"viewer.appById",
{
appId: "routing_forms",
},
]);
return (
<SettingsShell heading={t("developer")} subtitle={t("manage_developer_settings")}>
<WebhookListContainer title={t("webhooks")} subtitle={t("receive_cal_meeting_data")} />
<WebhookListContainer title="Event Webhooks" subtitle={t("receive_cal_meeting_data")} />
{routingForms && (
<WebhookListContainer
appId="routing_forms"
title="Routing Webhooks"
subtitle="Receive Routing Form responses at a specified URL, in real-time, when a Routing Form is submitted"
/>
)}
<ApiKeyListContainer />
</SettingsShell>
);
@@ -344,6 +344,7 @@
"booking_cancelled": "Booking Cancelled",
"booking_rescheduled": "Booking Rescheduled",
"booking_created": "Booking Created",
"form_submitted": "Form Submitted",
"event_triggers": "Event Triggers",
"subscriber_url": "Subscriber Url",
"create_new_webhook": "Create a new webhook",
+5 -1
View File
@@ -71,11 +71,13 @@ export const webhookRouter = createProtectedRouter()
input: z
.object({
eventTypeId: z.number().optional(),
appId: z.string().optional(),
})
.optional(),
async resolve({ ctx, input }) {
const where: Prisma.WebhookWhereInput = {
AND: [{ appId: null /* Don't mixup zapier webhooks with normal ones */ }],
/* Don't mixup zapier webhooks with normal ones */
AND: [{ appId: !input?.appId ? null : input.appId }],
};
if (Array.isArray(where.AND)) {
if (input?.eventTypeId) {
@@ -84,6 +86,7 @@ export const webhookRouter = createProtectedRouter()
where.AND?.push({ userId: ctx.user.id });
}
}
return await ctx.prisma.webhook.findMany({
where,
});
@@ -108,6 +111,7 @@ export const webhookRouter = createProtectedRouter()
},
});
}
return await ctx.prisma.webhook.create({
data: {
id: v4(),