2022-08-15 20:18:41 +00:00
|
|
|
import { WebhookTriggerEvents } from "@prisma/client";
|
2022-05-03 23:16:59 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2022-08-15 20:18:41 +00:00
|
|
|
import z from "zod";
|
2022-05-03 23:16:59 +00:00
|
|
|
|
2022-07-28 19:58:26 +00:00
|
|
|
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
|
2022-08-15 20:18:41 +00:00
|
|
|
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
2022-05-03 23:16:59 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
|
|
|
|
2022-08-15 20:18:41 +00:00
|
|
|
const querySchema = z.object({
|
|
|
|
apiKey: z.string(),
|
|
|
|
id: z.string(),
|
|
|
|
});
|
|
|
|
|
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
|
|
const { apiKey, id } = querySchema.parse(req.query);
|
2022-05-03 23:16:59 +00:00
|
|
|
|
|
|
|
if (!apiKey) {
|
|
|
|
return res.status(401).json({ message: "No API key provided" });
|
|
|
|
}
|
|
|
|
|
|
|
|
const validKey = await findValidApiKey(apiKey, "zapier");
|
|
|
|
|
|
|
|
if (!validKey) {
|
|
|
|
return res.status(401).json({ message: "API key not valid" });
|
|
|
|
}
|
|
|
|
|
2022-08-15 20:18:41 +00:00
|
|
|
const webhook = await prisma.webhook.findFirst({
|
|
|
|
where: {
|
|
|
|
id,
|
|
|
|
},
|
|
|
|
});
|
2022-05-03 23:16:59 +00:00
|
|
|
|
2022-08-15 20:18:41 +00:00
|
|
|
if (webhook?.eventTriggers.includes(WebhookTriggerEvents.MEETING_ENDED)) {
|
|
|
|
const bookingsWithScheduledJobs = await prisma.booking.findMany({
|
2022-05-03 23:16:59 +00:00
|
|
|
where: {
|
2022-08-15 20:18:41 +00:00
|
|
|
userId: validKey.userId,
|
|
|
|
scheduledJobs: {
|
|
|
|
isEmpty: false,
|
|
|
|
},
|
2022-05-03 23:16:59 +00:00
|
|
|
},
|
|
|
|
});
|
2022-08-15 20:18:41 +00:00
|
|
|
for (const booking of bookingsWithScheduledJobs) {
|
|
|
|
const updatedScheduledJobs = booking.scheduledJobs.filter(
|
|
|
|
(scheduledJob) => scheduledJob !== `zapier_${webhook.id}`
|
|
|
|
);
|
|
|
|
await prisma.booking.update({
|
|
|
|
where: {
|
|
|
|
id: booking.id,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
scheduledJobs: updatedScheduledJobs,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
2022-05-03 23:16:59 +00:00
|
|
|
}
|
2022-08-15 20:18:41 +00:00
|
|
|
|
|
|
|
await prisma.webhook.delete({
|
|
|
|
where: {
|
|
|
|
id,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
res.status(204).json({ message: "Subscription is deleted." });
|
2022-05-03 23:16:59 +00:00
|
|
|
}
|
2022-08-15 20:18:41 +00:00
|
|
|
|
|
|
|
export default defaultHandler({
|
|
|
|
DELETE: Promise.resolve({ default: defaultResponder(handler) }),
|
|
|
|
});
|