Feat/zapier app (#2623)

* create basic app structure

* add zapierSubscription model to prisma.schema

* change column name triggerEvent to lower case

* add zapier functionality + enpoints + adjust prisma.schema

* add subscriptionType + refactor code

* add app store information

* create setup page to generate api key

* clean code

* add copy functionality in setup page

* clean code

* add apiKeyType and delte key when uninstalled or new key generated

* clean code

* use Promise.all

* only approve zapier api key

* clean code

* fix findValidApiKey for api keys that don't expire

* fix migrations

* clean code

* small fixes

* add i18n

* add README.md file

* add setup guide to README.md

* fix yarn.lock

* Renames zapierother to zapier

* Typo

* Updates package name

* Rename fixes

* Adds zapier to the App Store seeder

* Adds missing zapier to apiHandlers

* Adds credential relationship to App

* Rename fixes

* Allows tailwind to pick up custom app-store components

* Consolidates zapier_setup_instructions

* Webhook fixes

* Uses app relationship instead of custom type

* Refactors sendPayload to accept webhook object

Instead of individual parameters

* refactoring

* Removes unused zapier check

* Update cancel.ts

* Refactoring

* Removes example comments

* Update InstallAppButton.tsx

* Type fixes

* E2E fixes

* Deletes all user zapier webhooks on integration removal

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: zomars <[email protected]>
This commit is contained in:
authored and GitHub committed 2022-05-03 23:16:59 +00:00
1 parent ba283e3dc0
commit 02b935bcde
37 files changed
+660 -57

No files matched your search

@@ -29,7 +29,7 @@ export default function WebhookDialogForm(props: {
subscriberUrl: "",
active: true,
payloadTemplate: null,
} as Omit<TWebhook, "userId" | "createdAt" | "eventTypeId">,
} as Omit<TWebhook, "userId" | "createdAt" | "eventTypeId" | "appId">,
} = props;
const [useCustomPayloadTemplate, setUseCustomPayloadTemplate] = useState(!!defaultValues.payloadTemplate);
+20 -10
View File
@@ -1,3 +1,4 @@
import { Webhook } from "@prisma/client";
import { compile } from "handlebars";
import type { CalendarEvent } from "@calcom/types/Calendar";
@@ -24,13 +25,13 @@ function jsonParse(jsonString: string) {
const sendPayload = async (
triggerEvent: string,
createdAt: string,
subscriberUrl: string,
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
data: CalendarEvent & {
metadata?: { [key: string]: string };
rescheduleUid?: string;
},
template?: string | null
}
) => {
const { subscriberUrl, appId, payloadTemplate: template } = webhook;
if (!subscriberUrl || !data) {
throw new Error("Missing required elements to send webhook payload.");
}
@@ -38,13 +39,22 @@ const sendPayload = async (
const contentType =
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
const body = template
? applyTemplate(template, data, contentType)
: JSON.stringify({
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
data.description = data.description || data.additionalNotes;
let body;
/* Zapier id is hardcoded in the DB, we send the raw data for this case */
if (appId === "zapier") {
body = JSON.stringify(data);
} else if (template) {
body = applyTemplate(template, data, contentType);
} else {
body = JSON.stringify({
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
}
const response = await fetch(subscriberUrl, {
method: "POST",
+3 -2
View File
@@ -8,7 +8,7 @@ export type GetSubscriberOptions = {
triggerEvent: WebhookTriggerEvents;
};
const getSubscribers = async (options: GetSubscriberOptions) => {
const getWebhooks = async (options: GetSubscriberOptions) => {
const { userId, eventTypeId } = options;
const allWebhooks = await prisma.webhook.findMany({
where: {
@@ -32,10 +32,11 @@ const getSubscribers = async (options: GetSubscriberOptions) => {
select: {
subscriberUrl: true,
payloadTemplate: true,
appId: true,
},
});
return allWebhooks;
};
export default getSubscribers;
export default getWebhooks;
+5 -11
View File
@@ -753,17 +753,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
metadata: reqBody.metadata,
});
const promises = subscribers.map((sub) =>
sendPayload(
eventTrigger,
new Date().toISOString(),
sub.subscriberUrl,
{
...evt,
rescheduleUid,
metadata: reqBody.metadata,
},
sub.payloadTemplate
).catch((e) => {
sendPayload(eventTrigger, new Date().toISOString(), sub, {
...evt,
rescheduleUid,
metadata: reqBody.metadata,
}).catch((e) => {
console.error(`Error executing webhook for event: ${eventTrigger}, URL: ${sub.subscriberUrl}`, e);
})
);
+6 -8
View File
@@ -14,7 +14,7 @@ import { getSession } from "@lib/auth";
import { sendCancelledEmails } from "@lib/emails/email-manager";
import prisma from "@lib/prisma";
import sendPayload from "@lib/webhooks/sendPayload";
import getSubscribers from "@lib/webhooks/subscriptions";
import getWebhooks from "@lib/webhooks/subscriptions";
import { getTranslation } from "@server/lib/i18n";
@@ -136,13 +136,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
eventTypeId: (bookingToDelete.eventTypeId as number) || 0,
triggerEvent: eventTrigger,
};
const subscribers = await getSubscribers(subscriberOptions);
const promises = subscribers.map((sub) =>
sendPayload(eventTrigger, new Date().toISOString(), sub.subscriberUrl, evt, sub.payloadTemplate).catch(
(e) => {
console.error(`Error executing webhook for event: ${eventTrigger}, URL: ${sub.subscriberUrl}`, e);
}
)
const webhooks = await getWebhooks(subscriberOptions);
const promises = webhooks.map((webhook) =>
sendPayload(eventTrigger, new Date().toISOString(), webhook, evt).catch((e) => {
console.error(`Error executing webhook for event: ${eventTrigger}, URL: ${webhook.subscriberUrl}`, e);
})
);
await Promise.all(promises);
+34 -10
View File
@@ -1,3 +1,4 @@
import { Prisma } from "@prisma/client";
import type { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@lib/auth";
@@ -10,8 +11,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// Check that user is authenticated
const session = await getSession({ req });
const userId = session?.user?.id;
if (!session) {
if (!userId) {
res.status(401).json({ message: "You must be logged in to do this" });
return;
}
@@ -19,7 +21,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (req.method === "GET") {
const credentials = await prisma.credential.findMany({
where: {
userId: session.user?.id,
userId,
},
select: {
type: true,
@@ -31,18 +33,40 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (req.method == "DELETE") {
const id = req.body.id;
const data: Prisma.UserUpdateInput = {
credentials: {
delete: {
id,
},
},
};
const integration = await prisma.credential.findUnique({
where: {
id,
},
});
/* If the user deletes a zapier integration, we delete all his api keys as well. */
if (integration?.appId === "zapier") {
data.apiKeys = {
deleteMany: {
userId,
appId: "zapier",
},
};
/* We also delete all user's zapier wehbooks */
data.webhooks = {
deleteMany: {
userId,
appId: "zapier",
},
};
}
await prisma.user.update({
where: {
id: session?.user?.id,
},
data: {
credentials: {
delete: {
id,
},
},
id: userId,
},
data,
});
res.status(200).json({ message: "Integration deleted successfully" });
+38
View File
@@ -0,0 +1,38 @@
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import _zapierMetadata from "@calcom/app-store/zapier/_metadata";
import { ZapierSetup } from "@calcom/app-store/zapier/components";
import { trpc } from "@lib/trpc";
import Loader from "@components/Loader";
export default function SetupInformation() {
const router = useRouter();
const appName = router.query.appName;
const { status } = useSession();
if (status === "loading") {
return (
<div className="absolute z-50 flex h-screen w-full items-center bg-gray-200">
<Loader />
</div>
);
}
if (status === "unauthenticated") {
router.replace({
pathname: "/auth/login",
query: {
callbackUrl: `/apps/setup/${appName}`,
},
});
}
if (appName === _zapierMetadata.name.toLowerCase() && status === "authenticated") {
return <ZapierSetup trpc={trpc}></ZapierSetup>;
}
return null;
}
@@ -774,5 +774,12 @@
"impersonate_user_tip":"All uses of this feature is audited.",
"impersonating_user_warning":"Impersonating username \"{{user}}\".",
"impersonating_stop_instructions": "<0>Click Here to stop</0>.",
"setting_up_zapier": "Setting up your Zapier integration",
"generate_api_key": "Generate Api Key",
"your_unique_api_key": "Your unique API key",
"copy_safe_api_key": "Copy this API key and save it somewhere safe. If you lose this key you have to generate a new one.",
"zapier_setup_instructions": "<0>Log into your Zapier account and create a new Zap.</0><1>Select Cal.com as your Trigger app. Also choose a Trigger event.</1><2>Choose your account and then enter your Unique API Key.</2><3>Test your Trigger.</3><4>You're set!</4>",
"install_zapier_app": "Please first install the Zapier App in the app store.",
"go_to_app_store": "Go to App Store",
"calendar_error": "Something went wrong, try reconnecting your calendar with all necessary permissions"
}
@@ -660,5 +660,6 @@
"availability_updated_successfully": "Disponibilidad actualizada correctamente",
"requires_ownership_of_a_token": "Requiere la propiedad de un token perteneciente a la siguiente dirección:",
"example_name": "Juan Pérez",
"you_are_being_redirected": "Serás redirigido a {{ url }} en $t(second, {\"count\": {{seconds}} })."
"you_are_being_redirected": "Serás redirigido a {{ url }} en $t(second, {\"count\": {{seconds}} }).",
"zapier_setup_instructions": "<0>Inicia sesión en tu cuenta de Zapier y crea un nuevo Zap.</0><1>Selecciona Cal.com cómo tu aplicación disparadora. Tambien elige tu evento disparador.</1><2>Elige tu cuenta e ingresa tu Clave API única.</2><3>Prueba tu disparador.</3><4>¡Listo!</4>"
}
@@ -11,16 +11,39 @@ export const apiKeysRouter = createProtectedRouter()
return await ctx.prisma.apiKey.findMany({
where: {
userId: ctx.user.id,
NOT: {
appId: "zapier",
},
},
orderBy: { createdAt: "desc" },
});
},
})
.query("findKeyOfType", {
input: z.object({
appId: z.string().optional().nullable(),
}),
async resolve({ ctx, input }) {
return await ctx.prisma.apiKey.findFirst({
where: {
AND: [
{
userId: ctx.user.id,
},
{
appId: input.appId,
},
],
},
});
},
})
.mutation("create", {
input: z.object({
note: z.string().optional().nullish(),
expiresAt: z.date().optional().nullable(),
neverExpires: z.boolean().optional(),
appId: z.string().optional().nullable(),
}),
async resolve({ ctx, input }) {
const [hashedApiKey, apiKey] = generateUniqueAPIKey();
+16 -11
View File
@@ -1,3 +1,4 @@
import { Prisma } from "@prisma/client";
import { v4 } from "uuid";
import { z } from "zod";
@@ -17,17 +18,18 @@ export const webhookRouter = createProtectedRouter()
})
.optional(),
async resolve({ ctx, input }) {
if (input?.eventTypeId) {
return await ctx.prisma.webhook.findMany({
where: {
eventTypeId: input.eventTypeId,
},
});
let where: Prisma.WebhookWhereInput = {
AND: [{ appId: null /* Don't mixup zapier webhooks with normal ones */ }],
};
if (Array.isArray(where.AND)) {
if (input?.eventTypeId) {
where.AND?.push({ eventTypeId: input.eventTypeId });
} else {
where.AND?.push({ userId: ctx.user.id });
}
}
return await ctx.prisma.webhook.findMany({
where: {
userId: ctx.user.id,
},
where,
});
},
})
@@ -38,6 +40,7 @@ export const webhookRouter = createProtectedRouter()
active: z.boolean(),
payloadTemplate: z.string().nullable(),
eventTypeId: z.number().optional(),
appId: z.string().optional().nullable(),
}),
async resolve({ ctx, input }) {
if (input.eventTypeId) {
@@ -65,6 +68,7 @@ export const webhookRouter = createProtectedRouter()
active: z.boolean().optional(),
payloadTemplate: z.string().nullable(),
eventTypeId: z.number().optional(),
appId: z.string().optional().nullable(),
}),
async resolve({ ctx, input }) {
const { id, ...data } = input;
@@ -139,7 +143,7 @@ export const webhookRouter = createProtectedRouter()
payloadTemplate: z.string().optional().nullable(),
}),
async resolve({ input }) {
const { url, type, payloadTemplate } = input;
const { url, type, payloadTemplate = null } = input;
const translation = await getTranslation("en", "common");
const language = {
locale: "en",
@@ -170,7 +174,8 @@ export const webhookRouter = createProtectedRouter()
};
try {
return await sendPayload(type, new Date().toISOString(), url, data, payloadTemplate);
const webhook = { subscriberUrl: url, payloadTemplate, appId: null };
return await sendPayload(type, new Date().toISOString(), webhook, data);
} catch (_err) {
const error = getErrorFromUnknown(_err);
return {
+5 -1
View File
@@ -1,5 +1,9 @@
const base = require("@calcom/config/tailwind-preset");
module.exports = {
...base,
content: [...base.content, "../../packages/ui/**/*.{js,ts,jsx,tsx}"],
content: [
...base.content,
"../../packages/ui/**/*.{js,ts,jsx,tsx}",
"../../packages/app-store/**/components/*.{js,ts,jsx,tsx}",
],
};