feat: OOO webhook and zapier (#15434)

* zapier and webhook

* instructions for zapier

* Fix types

* fix types

* revert adding zap template

* Update packages/app-store/zapier/README.md

Co-authored-by: Carina Wollendorfer <[email protected]>

* Update packages/app-store/zapier/README.md

Co-authored-by: Carina Wollendorfer <[email protected]>

* Update packages/app-store/zapier/README.md

Co-authored-by: Carina Wollendorfer <[email protected]>

* Update packages/features/webhooks/lib/scheduleTrigger.ts

Co-authored-by: Carina Wollendorfer <[email protected]>

* wip

* Fixes from comments, no more sendPayloadNoBooking

* fix subscriberOptions teamIds param type

* types

* Update packages/features/webhooks/lib/sendPayload.ts

* Re add zapierPayload to don't break old zaps

* instead of metadata use oooEntry inside webhookPayload

* undo comment message

* Types

* reset changes on yarn.lock

* review changes

* fix types

* fix types

* tentative fix for types in webhook

* type improvements

* fix description + clean up

* revert yarn.lock changes

* allow custom template for ooo entry

* type fixes

* type fix

* fix donwloadLinks in payload

* simplify some types

* allow array or number for teamId

* same payload for test trigger

* code clean up

* fix no show e2e test

* translate text for webhook payload and fix conditional

* add test for ooo_created webhooks

* reset files

* merge fix

* fix test data test id

* remove unused variable

* only trigger for accepted memberships

* remove unused variable

---------

Co-authored-by: Carina Wollendorfer <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: Omar López <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-09-06 15:48:05 -04:00
1 parent 105e7d3e28
commit f5c16f0d6b
27 files changed
+606 -126

No files matched your search

@@ -1,7 +1,13 @@
import type { Prisma } from "@prisma/client";
import { v4 as uuidv4 } from "uuid";
import { selectOOOEntries } from "@calcom/app-store/zapier/api/subscriptions/listOOOEntries";
import dayjs from "@calcom/dayjs";
import { sendBookingRedirectNotification } from "@calcom/emails";
import type { GetSubscriberOptions } from "@calcom/features/webhooks/lib/getWebhooks";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import type { OOOEntryPayloadType } from "@calcom/features/webhooks/lib/sendPayload";
import sendPayload from "@calcom/features/webhooks/lib/sendPayload";
import { getTranslation } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -9,6 +15,7 @@ import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import { TRPCError } from "@trpc/server";
import type { TOutOfOfficeDelete, TOutOfOfficeInputSchema } from "./outOfOffice.schema";
import { WebhookTriggerEvents } from ".prisma/client";
type TBookingRedirect = {
ctx: {
@@ -44,7 +51,7 @@ export const outOfOfficeCreateOrUpdate = async ({ ctx, input }: TBookingRedirect
throw new TRPCError({ code: "BAD_REQUEST", message: "start_date_must_be_in_the_future" });
}
let toUserId;
let toUserId: number | null = null;
if (input.toTeamUserId) {
const user = await prisma.user.findUnique({
@@ -130,7 +137,7 @@ export const outOfOfficeCreateOrUpdate = async ({ ctx, input }: TBookingRedirect
toUserId: true,
},
where: {
userId: toUserId,
...(toUserId && { userId: toUserId }),
toUserId: ctx.user.id,
// Check for time overlap or collision
OR: [
@@ -200,7 +207,43 @@ export const outOfOfficeCreateOrUpdate = async ({ ctx, input }: TBookingRedirect
toUserId: toUserId ? toUserId : null,
},
});
let resultRedirect: Prisma.OutOfOfficeEntryGetPayload<{ select: typeof selectOOOEntries }> | null = null;
if (createdOrUpdatedOutOfOffice) {
const findRedirect = await prisma.outOfOfficeEntry.findFirst({
where: {
uuid: createdOrUpdatedOutOfOffice.uuid,
},
select: selectOOOEntries,
});
if (findRedirect) {
resultRedirect = findRedirect;
}
}
if (!resultRedirect) {
return;
}
const toUser = toUserId
? await prisma.user.findFirst({
where: {
id: toUserId,
},
select: {
name: true,
username: true,
timeZone: true,
email: true,
},
})
: null;
const reason = await prisma.outOfOfficeReason.findFirst({
where: {
id: input.reasonId,
},
select: {
reason: true,
emoji: true,
},
});
if (toUserId) {
// await send email to notify user
const userToNotify = await prisma.user.findFirst({
@@ -275,6 +318,76 @@ export const outOfOfficeCreateOrUpdate = async ({ ctx, input }: TBookingRedirect
}
}
const memberships = await prisma.membership.findMany({
where: {
userId: ctx.user.id,
accepted: true,
},
});
const teamIds = memberships.map((membership) => membership.teamId);
// Send webhook to notify other services
const subscriberOptions: GetSubscriberOptions = {
userId: ctx.user.id,
teamId: teamIds,
orgId: ctx.user.organizationId,
triggerEvent: WebhookTriggerEvents.OOO_CREATED,
};
const subscribers = await getWebhooks(subscriberOptions);
const payload: OOOEntryPayloadType = {
oooEntry: {
id: createdOrUpdatedOutOfOffice.id,
start: dayjs(createdOrUpdatedOutOfOffice.start)
.tz(ctx.user.timeZone, true)
.format("YYYY-MM-DDTHH:mm:ssZ"),
end: dayjs(createdOrUpdatedOutOfOffice.end).tz(ctx.user.timeZone, true).format("YYYY-MM-DDTHH:mm:ssZ"),
createdAt: createdOrUpdatedOutOfOffice.createdAt.toISOString(),
updatedAt: createdOrUpdatedOutOfOffice.updatedAt.toISOString(),
notes: createdOrUpdatedOutOfOffice.notes,
reason: {
emoji: reason?.emoji,
reason: reason?.reason,
},
reasonId: input.reasonId,
user: {
id: ctx.user.id,
name: ctx.user.name,
username: ctx.user.username,
email: ctx.user.email,
timeZone: ctx.user.timeZone,
},
toUser: toUserId
? {
id: toUserId,
name: toUser?.name,
username: toUser?.username,
email: toUser?.email,
timeZone: toUser?.timeZone,
}
: null,
uuid: createdOrUpdatedOutOfOffice.uuid,
},
};
await Promise.all(
subscribers.map(async (subscriber) => {
sendPayload(
subscriber.secret,
WebhookTriggerEvents.OOO_CREATED,
dayjs().toISOString(),
{
appId: subscriber.appId,
subscriberUrl: subscriber.subscriberUrl,
payloadTemplate: subscriber.payloadTemplate,
},
payload
);
})
);
return {};
};
@@ -8,7 +8,7 @@ import { sendDeclinedEmails } from "@calcom/emails";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation";
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
@@ -399,7 +399,7 @@ export const confirmHandler = async ({ ctx, input }: ConfirmOptions) => {
currency: booking.eventType?.currency,
length: booking.eventType?.length,
};
const webhookData = {
const webhookData: EventPayloadType = {
...evt,
...eventTypeInfo,
bookingId,
@@ -296,10 +296,11 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
userId,
eventTypeId: bookingToReschedule.eventTypeId as number,
triggerEvent: eventTrigger,
teamId,
teamId: teamId ? [teamId] : null,
orgId,
};
const webhooks = await getWebhooks(subscriberOptions);
const promises = webhooks.map((webhook) =>
sendPayload(webhook.secret, eventTrigger, new Date().toISOString(), webhook, {
...evt,
@@ -1,4 +1,5 @@
import type { Webhook } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import { v4 } from "uuid";
import { updateTriggerForExistingBookings } from "@calcom/features/webhooks/lib/scheduleTrigger";
@@ -17,33 +18,29 @@ type CreateOptions = {
};
export const createHandler = async ({ ctx, input }: CreateOptions) => {
const { user } = ctx;
const webhookData: Prisma.WebhookCreateInput = {
id: v4(),
...input,
};
if (input.platform && user.role !== "ADMIN") {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
// Add userId if platform, eventTypeId, and teamId are not provided
if (!input.platform && !input.eventTypeId && !input.teamId) {
webhookData.user = { connect: { id: user.id } };
}
let newWebhook: Webhook;
if (input.platform) {
const { user } = ctx;
if (user?.role !== "ADMIN") {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
try {
newWebhook = await prisma.webhook.create({
data: {
id: v4(),
...input,
},
});
} else if (input.eventTypeId || input.teamId) {
newWebhook = await prisma.webhook.create({
data: {
id: v4(),
...input,
},
});
} else {
newWebhook = await prisma.webhook.create({
data: {
id: v4(),
userId: ctx.user.id,
...input,
},
data: webhookData,
});
} catch (error) {
// Avoid printing raw prisma error on frontend
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to create webhook" });
}
await updateTriggerForExistingBookings(newWebhook, [], newWebhook.eventTriggers);
@@ -1,3 +1,4 @@
import type { EventPayloadType } from "@calcom/features/webhooks/lib/sendPayload";
import sendPayload from "@calcom/features/webhooks/lib/sendPayload";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { getTranslation } from "@calcom/lib/server/i18n";
@@ -17,7 +18,7 @@ export const testTriggerHandler = async ({ ctx: _ctx, input }: TestTriggerOption
translate: translation,
};
const data = {
const data: EventPayloadType = {
type: "Test",
title: "Test trigger event",
description: "",