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

@@ -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);