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,4 +1,4 @@
import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import type { CalendarEvent } from "@calcom/types/Calendar";
export const getWebhookPayloadForBooking = ({
@@ -29,9 +29,12 @@ export const getWebhookPayloadForBooking = ({
currency: booking.eventType?.currency,
length: booking.eventType?.length,
};
return {
const payload: EventPayloadType = {
...evt,
...eventTypeInfo,
bookingId: booking.id,
};
return payload;
};
@@ -13,7 +13,7 @@ import type { Workflow } from "@calcom/features/ee/workflows/lib/types";
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import { scheduleTrigger } from "@calcom/features/webhooks/lib/scheduleTrigger";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
@@ -397,16 +397,24 @@ export async function handleConfirmation(args: {
length: eventType?.length,
};
const payload: EventPayloadType = {
...evt,
...eventTypeInfo,
bookingId,
eventTypeId: eventType?.id,
status: "ACCEPTED",
smsReminderNumber: booking.smsReminderNumber || undefined,
metadata: meetingUrl ? { videoCallUrl: meetingUrl } : undefined,
};
const promises = subscribersBookingCreated.map((sub) =>
sendPayload(sub.secret, WebhookTriggerEvents.BOOKING_CREATED, new Date().toISOString(), sub, {
...evt,
...eventTypeInfo,
bookingId,
eventTypeId: eventType?.id,
status: "ACCEPTED",
smsReminderNumber: booking.smsReminderNumber || undefined,
metadata: meetingUrl ? { videoCallUrl: meetingUrl } : undefined,
}).catch((e) => {
sendPayload(
sub.secret,
WebhookTriggerEvents.BOOKING_CREATED,
new Date().toISOString(),
sub,
payload
).catch((e) => {
log.error(
`Error executing webhook for event: ${WebhookTriggerEvents.BOOKING_CREATED}, URL: ${sub.subscriberUrl}, bookingId: ${evt.bookingId}, bookingUid: ${evt.uid}`,
safeStringify(e)
@@ -452,19 +460,20 @@ export async function handleConfirmation(args: {
eventTitle: eventType?.title,
externalId: paymentExternalId,
};
payload.paymentId = bookingWithPayment?.payment?.[0].id;
payload.metadata = {
...(paid ? paymentMetadata : {}),
};
const bookingPaidSubscribers = subscriberMeetingPaid.map((sub) =>
sendPayload(sub.secret, WebhookTriggerEvents.BOOKING_PAID, new Date().toISOString(), sub, {
...evt,
...eventTypeInfo,
bookingId,
eventTypeId: eventType?.id,
status: "ACCEPTED",
smsReminderNumber: booking.smsReminderNumber || undefined,
paymentId: bookingWithPayment?.payment?.[0].id,
metadata: {
...(paid ? paymentMetadata : {}),
},
}).catch((e) => {
sendPayload(
sub.secret,
WebhookTriggerEvents.BOOKING_PAID,
new Date().toISOString(),
sub,
payload
).catch((e) => {
log.error(
`Error executing webhook for event: ${WebhookTriggerEvents.BOOKING_PAID}, URL: ${sub.subscriberUrl}, bookingId: ${evt.bookingId}, bookingUid: ${evt.uid}`,
safeStringify(e)
@@ -84,7 +84,7 @@ import type {
} from "@calcom/types/Calendar";
import type { EventResult, PartialReference } from "@calcom/types/EventManager";
import type { EventTypeInfo } from "../../webhooks/lib/sendPayload";
import type { EventPayloadType, EventTypeInfo } from "../../webhooks/lib/sendPayload";
import { getAllCredentials } from "./getAllCredentialsForUsersOnEvent/getAllCredentials";
import { refreshCredentials } from "./getAllCredentialsForUsersOnEvent/refreshCredentials";
import getBookingDataSchema from "./getBookingDataSchema";
@@ -1547,7 +1547,7 @@ async function handler(
}
: undefined;
const webhookData = {
const webhookData: EventPayloadType = {
...evt,
...eventTypeInfo,
bookingId: booking?.id,
@@ -2,7 +2,7 @@ import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { updateMeeting } from "@calcom/core/videoClient";
import { sendCancelledSeatEmails } from "@calcom/emails";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -129,13 +129,21 @@ async function cancelAttendeeSeat(
]
: [];
const payload: EventPayloadType = {
...evt,
...eventTypeInfo,
status: "CANCELLED",
smsReminderNumber: bookingToDelete.smsReminderNumber || undefined,
};
const promises = webhooks.map((webhook) =>
sendPayload(webhook.secret, WebhookTriggerEvents.BOOKING_CANCELLED, new Date().toISOString(), webhook, {
...evt,
...eventTypeInfo,
status: "CANCELLED",
smsReminderNumber: bookingToDelete.smsReminderNumber || undefined,
}).catch((e) => {
sendPayload(
webhook.secret,
WebhookTriggerEvents.BOOKING_CANCELLED,
new Date().toISOString(),
webhook,
payload
).catch((e) => {
logger.error(
`Error executing webhook for event: ${WebhookTriggerEvents.BOOKING_CANCELLED}, URL: ${webhook.subscriberUrl}, bookingId: ${evt.bookingId}, bookingUid: ${evt.uid}`,
safeStringify(e)
@@ -2,6 +2,7 @@
import dayjs from "@calcom/dayjs";
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
import type { EventPayloadType } from "@calcom/features/webhooks/lib/sendPayload";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { HttpError } from "@calcom/lib/http-error";
import prisma from "@calcom/prisma";
@@ -125,7 +126,7 @@ const handleSeats = async (newSeatedBookingObject: NewSeatedBookingObject) => {
loggerWithEventDetails.error("Error while scheduling workflow reminders", JSON.stringify({ error }));
}
const webhookData = {
const webhookData: EventPayloadType = {
...evt,
...eventTypeInfo,
uid: resultBooking?.uid || uid,
@@ -1,14 +1,14 @@
import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import type { GetSubscriberOptions } from "@calcom/features/webhooks/lib/getWebhooks";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import type { WebhookDataType } from "@calcom/features/webhooks/lib/sendPayload";
import { isEventPayload, type WebhookPayloadType } from "@calcom/features/webhooks/lib/sendPayload";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
export async function handleWebhookTrigger(args: {
subscriberOptions: GetSubscriberOptions;
eventTrigger: string;
webhookData: Omit<WebhookDataType, "createdAt" | "triggerEvent">;
webhookData: WebhookPayloadType;
}) {
try {
const subscribers = await getWebhooks(args.subscriberOptions);
@@ -16,10 +16,12 @@ export async function handleWebhookTrigger(args: {
const promises = subscribers.map((sub) =>
sendPayload(sub.secret, args.eventTrigger, new Date().toISOString(), sub, args.webhookData).catch(
(e) => {
logger.error(
`Error executing webhook for event: ${args.eventTrigger}, URL: ${sub.subscriberUrl}, bookingId: ${args.webhookData.bookingId}, bookingUid: ${args.webhookData.uid}`,
safeStringify(e)
);
if (isEventPayload(args.webhookData)) {
logger.error(
`Error executing webhook for event: ${args.eventTrigger}, URL: ${sub.subscriberUrl}, booking id: ${args.webhookData.bookingId}, booking uid: ${args.webhookData.uid}`,
safeStringify(e)
);
}
}
)
);
-1
View File
@@ -95,7 +95,6 @@ const handleMarkNoShow = async ({
await webhooks.sendPayload({
...payload,
/** We send webhook message pre-translated, on client we already handle this */
// @ts-expect-error payload is too booking specific, we need to refactor this
bookingUid,
bookingId,
});
@@ -43,6 +43,7 @@ const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP_V2: Record<string, WebhookTriggerEve
{ value: WebhookTriggerEvents.MEETING_STARTED, label: "meeting_started" },
{ value: WebhookTriggerEvents.RECORDING_READY, label: "recording_ready" },
{ value: WebhookTriggerEvents.INSTANT_MEETING, label: "instant_meeting" },
{ value: WebhookTriggerEvents.OOO_CREATED, label: "ooo_created" },
{
value: WebhookTriggerEvents.RECORDING_TRANSCRIPTION_GENERATED,
label: "recording_transcription_generated",
@@ -100,7 +101,6 @@ const WebhookForm = (props: {
const [newSecret, setNewSecret] = useState("");
const [changeSecret, setChangeSecret] = useState<boolean>(false);
const hasSecretKey = !!props?.webhook?.secret;
// const currentSecret = props?.webhook?.secret;
useEffect(() => {
if (changeSecret) {
@@ -290,7 +290,7 @@ const WebhookForm = (props: {
<Button
type="submit"
disabled={!formMethods.formState.isDirty && !changeSecret}
loading={formMethods.formState.isSubmitting || formMethods.formState.isSubmitted}>
loading={formMethods.formState.isSubmitting}>
{props?.webhook?.id ? t("save") : t("create_webhook")}
</Button>
</SectionBottomActions>
@@ -17,6 +17,7 @@ export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
WebhookTriggerEvents.INSTANT_MEETING,
WebhookTriggerEvents.RECORDING_TRANSCRIPTION_GENERATED,
WebhookTriggerEvents.BOOKING_NO_SHOW_UPDATED,
WebhookTriggerEvents.OOO_CREATED,
] as const,
"routing-forms": [WebhookTriggerEvents.FORM_SUBMITTED] as const,
};
@@ -6,15 +6,16 @@ export type GetSubscriberOptions = {
userId?: number | null;
eventTypeId?: number | null;
triggerEvent: WebhookTriggerEvents;
teamId?: number | null;
teamId?: number | number[] | null;
orgId?: number | null;
oAuthClientId?: string | null;
};
const getWebhooks = async (options: GetSubscriberOptions, prisma: PrismaClient = defaultPrisma) => {
const teamId = options.teamId;
const userId = options.userId ?? 0;
const eventTypeId = options.eventTypeId ?? 0;
const teamId = options.teamId ?? 0;
const teamIds = Array.isArray(teamId) ? teamId : [teamId ?? 0];
const orgId = options.orgId ?? 0;
const oAuthClientId = options.oAuthClientId ?? "";
@@ -33,7 +34,7 @@ const getWebhooks = async (options: GetSubscriberOptions, prisma: PrismaClient =
},
{
teamId: {
in: [teamId, orgId],
in: [...teamIds, orgId],
},
},
{ platformOAuthClientId: oAuthClientId },
@@ -1,6 +1,7 @@
import type { Prisma, Webhook, Booking } from "@prisma/client";
import { v4 } from "uuid";
import { selectOOOEntries } from "@calcom/app-store/zapier/api/subscriptions/listOOOEntries";
import { getHumanReadableLocationValue } from "@calcom/core/location";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import logger from "@calcom/lib/logger";
@@ -451,3 +452,56 @@ export async function updateTriggerForExistingBookings(
);
await Promise.all(promise);
}
export async function listOOOEntries(
appApiKey?: ApiKey,
account?: {
id: number;
name: string | null;
isTeam: boolean;
} | null
) {
const userId = appApiKey ? appApiKey.userId : account && !account.isTeam ? account.id : null;
const teamId = appApiKey ? appApiKey.teamId : account && account.isTeam ? account.id : null;
try {
const where: Prisma.OutOfOfficeEntryWhereInput = {};
if (teamId) {
where.user = {
teams: {
some: {
teamId,
},
},
};
} else if (userId) {
where.userId = userId;
}
// early return
if (!where.userId && !where.user) {
return [];
}
const oooEntries = await prisma.outOfOfficeEntry.findMany({
where: {
...where,
},
take: 3,
orderBy: {
id: "desc",
},
select: selectOOOEntries,
});
if (oooEntries.length === 0) {
return [];
}
return oooEntries;
} catch (err) {
log.error(
`Error retrieving list of ooo entries for user ${userId}. or teamId ${teamId}`,
safeStringify(err)
);
}
}
+83 -36
View File
@@ -33,7 +33,7 @@ export type WithUTCOffsetType<T> = T & {
export type BookingNoShowUpdatedPayload = {
message: string;
bookingUid: string;
bookingId: number;
bookingId?: number;
attendees: { email: string; noShow: boolean }[];
};
@@ -44,9 +44,39 @@ export type TranscriptionGeneratedPayload = {
};
};
export type WebhookDataType = CalendarEvent &
export type OOOEntryPayloadType = {
oooEntry: {
id: number;
start: string;
end: string;
createdAt: string;
updatedAt: string;
notes: string | null;
reason: {
emoji?: string;
reason?: string;
};
reasonId: number;
user: {
id: number;
name: string | null;
username: string | null;
timeZone: string;
email: string;
};
toUser: {
id: number;
name?: string | null;
username?: string | null;
timeZone?: string;
email?: string;
} | null;
uuid: string;
};
};
export type EventPayloadType = CalendarEvent &
TranscriptionGeneratedPayload &
// BookingNoShowUpdatedPayload & // This breaks all other webhooks
EventTypeInfo & {
metadata?: { [key: string]: string | number | boolean | null };
bookingId?: number;
@@ -56,8 +86,6 @@ export type WebhookDataType = CalendarEvent &
rescheduleUid?: string;
rescheduleStartTime?: string;
rescheduleEndTime?: string;
triggerEvent: string;
createdAt: string;
downloadLink?: string;
paymentId?: number;
rescheduledBy?: string;
@@ -65,28 +93,30 @@ export type WebhookDataType = CalendarEvent &
paymentData?: Payment;
};
function addUTCOffset(
data: Omit<WebhookDataType, "createdAt" | "triggerEvent">
): WithUTCOffsetType<WebhookDataType> {
if (data.organizer?.timeZone) {
(data.organizer as Person & UTCOffset).utcOffset = getUTCOffsetByTimezone(
data.organizer.timeZone,
data.startTime
);
export type WebhookPayloadType = EventPayloadType | OOOEntryPayloadType | BookingNoShowUpdatedPayload;
type WebhookDataType = WebhookPayloadType & { triggerEvent: string; createdAt: string };
function addUTCOffset(data: WebhookPayloadType): WithUTCOffsetType<WebhookPayloadType> {
if (isEventPayload(data)) {
if (data.organizer?.timeZone) {
(data.organizer as Person & UTCOffset).utcOffset = getUTCOffsetByTimezone(
data.organizer.timeZone,
data.startTime
);
}
if (data.attendees?.length) {
(data.attendees as (Person & UTCOffset)[]).forEach((attendee) => {
attendee.utcOffset = getUTCOffsetByTimezone(attendee.timeZone, data.startTime);
});
}
}
if (data?.attendees?.length) {
(data.attendees as (Person & UTCOffset)[]).forEach((attendee) => {
attendee.utcOffset = getUTCOffsetByTimezone(attendee.timeZone, data.startTime);
});
}
return data as WithUTCOffsetType<WebhookDataType>;
return data as WithUTCOffsetType<WebhookPayloadType>;
}
function getZapierPayload(
data: WithUTCOffsetType<CalendarEvent & EventTypeInfo & { status?: string; createdAt: string }>
): string {
function getZapierPayload(data: WithUTCOffsetType<EventPayloadType & { createdAt: string }>): string {
const attendees = (data.attendees as (Person & UTCOffset)[]).map((attendee) => {
return {
name: attendee.name,
@@ -150,34 +180,51 @@ export function jsonParse(jsonString: string) {
return false;
}
export function isOOOEntryPayload(data: WebhookPayloadType): data is OOOEntryPayloadType {
return "oooEntry" in data;
}
export function isNoShowPayload(data: WebhookPayloadType): data is BookingNoShowUpdatedPayload {
return "message" in data;
}
export function isEventPayload(data: WebhookPayloadType): data is EventPayloadType {
return !isNoShowPayload(data) && !isOOOEntryPayload(data);
}
const sendPayload = async (
secretKey: string | null,
triggerEvent: string,
createdAt: string,
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
data: Omit<WebhookDataType, "createdAt" | "triggerEvent">
data: WebhookPayloadType
) => {
const { appId, payloadTemplate: template } = webhook;
const contentType =
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
data.description = data.description || data.additionalNotes;
data = addUTCOffset(data);
let body;
/* Zapier id is hardcoded in the DB, we send the raw data for this case */
if (appId === "zapier") {
body = getZapierPayload({ ...data, createdAt });
} else if (template) {
body = applyTemplate(template, { ...data, triggerEvent, createdAt }, contentType);
} else {
body = JSON.stringify({
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
if (isEventPayload(data)) {
data.description = data.description || data.additionalNotes;
if (appId === "zapier") {
body = getZapierPayload({ ...data, createdAt });
}
}
if (body === undefined) {
if (template && (isOOOEntryPayload(data) || isEventPayload(data) || isNoShowPayload(data))) {
body = applyTemplate(template, { ...data, triggerEvent, createdAt }, contentType);
} else {
body = JSON.stringify({
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
}
}
return _sendPayload(secretKey, webhook, body, contentType);