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

@@ -38,7 +38,6 @@ async function* getResponses(formId: string) {
} else {
serializedValue = escapeCsvText(value);
}
csvLineColumns.push(`"Field Label :=> Value"`);
csvLineColumns.push(`"${label} :=> ${serializedValue}"`);
}
csv.push(csvLineColumns.join(","));
@@ -48,6 +47,7 @@ async function* getResponses(formId: string) {
}
return "";
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { args } = req.query;
if (!args) {
@@ -11,7 +11,7 @@ export default function RoutingNavBar({
}) {
const tabs = [
{
name: "Fields",
name: "Form",
href: `${appUrl}/form-edit/${form?.id}`,
},
{
@@ -1,5 +1,6 @@
import { TrashIcon, PlusIcon, ArrowUpIcon, CollectionIcon, ArrowDownIcon } from "@heroicons/react/solid";
import { useRouter } from "next/router";
import { useState, useEffect } from "react";
import { useForm, UseFormReturn, useFieldArray, Controller } from "react-hook-form";
import { v4 as uuidv4 } from "uuid";
@@ -72,6 +73,22 @@ function Field({
fn: () => void;
};
}) {
const [identifier, _setIdentifier] = useState(hookForm.getValues(`${hookFieldNamespace}.identifier`));
const setUserChangedIdentifier = (val: string) => {
_setIdentifier(val);
// Also, update the form identifier so tha it can be persisted
hookForm.setValue(`${hookFieldNamespace}.identifier`, val);
};
const label = hookForm.watch(`${hookFieldNamespace}.label`);
useEffect(() => {
if (!hookForm.getValues(`${hookFieldNamespace}.identifier`)) {
_setIdentifier(label);
}
}, [label, hookFieldNamespace, hookForm]);
return (
<div
data-testid="field"
@@ -104,12 +121,30 @@ function Field({
<div className="w-full">
<input
type="text"
placeholder="This is what your users would see"
required
{...hookForm.register(`${hookFieldNamespace}.label`)}
className="block w-full rounded-sm border-gray-300 text-sm"
/>
</div>
</div>
<div className="mt-2 block items-center sm:flex">
<div className="min-w-48 mb-4 sm:mb-0">
<label htmlFor="label" className="mt-0 flex text-sm font-medium text-neutral-700">
Nickname
</label>
</div>
<div className="w-full">
<input
type="text"
required
placeholder="Identifies field in webhook payloads"
value={identifier}
onChange={(e) => setUserChangedIdentifier(e.target.value)}
className="block w-full rounded-sm border-gray-300 text-sm"
/>
</div>
</div>
<div className="mt-2 block items-center sm:flex">
<div className="min-w-48 mb-4 sm:mb-0">
<label htmlFor="label" className="mt-0 flex text-sm font-medium text-neutral-700">
@@ -64,6 +64,9 @@ test.describe("Forms", () => {
await addForm(page);
await page.click('[href="/apps/routing_forms/forms"]');
// TODO: Workaround for bug in https://github.com/calcom/cal.com/issues/3410
await page.click('[href="/apps/routing_forms/forms"]');
await page.waitForSelector('[data-testid="routing-forms-list"]');
expect(await page.locator('[data-testid="routing-forms-list"] > li').count()).toBe(1);
});
@@ -1,7 +1,10 @@
import { Prisma } from "@prisma/client";
import { Prisma, WebhookTriggerEvents } from "@prisma/client";
import { v4 as uuidv4 } from "uuid";
import { z } from "zod";
import { sendGenericWebhookPayload } from "@lib/webhooks/sendPayload";
import getWebhooks from "@lib/webhooks/subscriptions";
import { createProtectedRouter, createRouter } from "@server/createRouter";
import { TRPCError } from "@trpc/server";
@@ -28,6 +31,9 @@ const app_RoutingForms = createRouter()
where: {
id: formId,
},
include: {
user: true,
},
});
if (!form) {
throw new TRPCError({
@@ -87,6 +93,36 @@ const app_RoutingForms = createRouter()
});
}
const fieldResponsesByName: Record<string, typeof response[keyof typeof response]["value"]> = {};
for (const [fieldId, fieldResponse] of Object.entries(response)) {
// Use the label lowercased as the key to identify a field.
const key =
fields.find((f) => f.id === fieldId)?.identifier ||
(fieldResponse.label as keyof typeof fieldResponsesByName);
fieldResponsesByName[key] = fieldResponse.value;
}
const subscriberOptions = {
userId: form.user.id,
// It isn't an eventType webhook
eventTypeId: -1,
triggerEvent: WebhookTriggerEvents.FORM_SUBMITTED,
};
const webhooks = await getWebhooks(subscriberOptions);
const promises = webhooks.map((webhook) => {
sendGenericWebhookPayload(
webhook.secret,
"FORM_SUBMITTED",
new Date().toISOString(),
webhook,
fieldResponsesByName
).catch((e) => {
console.error(`Error executing routing form webhook`, webhook, e);
});
});
await Promise.all(promises);
return await prisma.app_RoutingForms_FormResponse.create({
data: input,
});
@@ -5,6 +5,7 @@ export const zodFields = z
z.object({
id: z.string(),
label: z.string(),
identifier: z.string().optional(),
type: z.string(),
selectText: z.string().optional(),
required: z.boolean().optional(),
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "WebhookTriggerEvents" ADD VALUE 'FORM_SUBMITTED';
+1
View File
@@ -392,6 +392,7 @@ enum WebhookTriggerEvents {
BOOKING_CREATED
BOOKING_RESCHEDULED
BOOKING_CANCELLED
FORM_SUBMITTED
}
model Webhook {