feat: booking no show webhook (#15502)

* WIP

Signed-off-by: zomars <[email protected]>

* WIP

Signed-off-by: zomars <[email protected]>

* WIP

Signed-off-by: zomars <[email protected]>

* Type fixes

* Update webhook.e2e.ts

* Update noShow.handler.ts

* Log failed results

* Updates tests

* Show generic error on frontend.

* test: add basic webhook service test

* fix: webhook end to end test

* fix: type error

* fix: test

---------

Signed-off-by: zomars <[email protected]>
Co-authored-by: sean-brydon <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-06-27 20:12:09 +00:00
1 parent 6207afdf03
commit 3948b8d203
14 files changed
+371 -156

No files matched your search

@@ -38,6 +38,7 @@ const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP_V2: Record<string, WebhookTriggerEve
{ value: WebhookTriggerEvents.BOOKING_PAYMENT_INITIATED, label: "booking_payment_initiated" },
{ value: WebhookTriggerEvents.BOOKING_RESCHEDULED, label: "booking_rescheduled" },
{ value: WebhookTriggerEvents.BOOKING_PAID, label: "booking_paid" },
{ value: WebhookTriggerEvents.BOOKING_NO_SHOW_UPDATED, label: "booking_no_show_updated" },
{ value: WebhookTriggerEvents.MEETING_ENDED, label: "meeting_ended" },
{ value: WebhookTriggerEvents.MEETING_STARTED, label: "meeting_started" },
{ value: WebhookTriggerEvents.RECORDING_READY, label: "recording_ready" },
@@ -0,0 +1,40 @@
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import getWebhooks from "./getWebhooks";
import sendOrSchedulePayload from "./sendOrSchedulePayload";
const log = logger.getSubLogger({ prefix: ["[WebhookService] "] });
/** This is a WIP. With minimal methods until the API matures and stabilizes */
export class WebhookService {
private options = {} as Parameters<typeof getWebhooks>[0];
private webhooks: Awaited<ReturnType<typeof getWebhooks>> = [];
constructor(options: Parameters<typeof getWebhooks>[0]) {
return (async (): Promise<WebhookService> => {
this.options = options;
this.webhooks = await getWebhooks(options);
return this;
})() as unknown as WebhookService;
}
async getWebhooks() {
return this.webhooks;
}
async sendPayload(payload: Parameters<typeof sendOrSchedulePayload>[4]) {
const promises = this.webhooks.map((sub) =>
sendOrSchedulePayload(
sub.secret,
this.options.triggerEvent,
new Date().toISOString(),
sub,
payload
).catch((e) => {
log.error(
`Error executing webhook for event: ${this.options.triggerEvent}, URL: ${sub.subscriberUrl}`,
safeStringify(e)
);
})
);
await Promise.allSettled(promises);
}
}
@@ -15,6 +15,7 @@ export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
WebhookTriggerEvents.BOOKING_REJECTED,
WebhookTriggerEvents.RECORDING_READY,
WebhookTriggerEvents.INSTANT_MEETING,
WebhookTriggerEvents.BOOKING_NO_SHOW_UPDATED,
] as const,
"routing-forms": [WebhookTriggerEvents.FORM_SUBMITTED] as const,
};
@@ -29,7 +29,14 @@ export type WithUTCOffsetType<T> = T & {
attendees?: (Person & UTCOffset)[];
};
export type BookingNoShowUpdatedPayload = {
message: string;
bookingUid: string;
attendees: { email: string; noShow: boolean }[];
};
export type WebhookDataType = CalendarEvent &
// BookingNoShowUpdatedPayload & // This breaks all other webhooks
EventTypeInfo & {
metadata?: { [key: string]: string | number | boolean | null };
bookingId?: number;
@@ -0,0 +1,141 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { WebhookService } from "../WebhookService";
import getWebhooks from "../getWebhooks";
vi.mock("../getWebhooks");
vi.mock("../sendOrSchedulePayload");
vi.mock("@calcom/lib/logger", async () => {
const actual = await vi.importActual<typeof import("@calcom/lib/logger")>("@calcom/lib/logger");
return {
...actual,
getSubLogger: vi.fn(() => ({
error: vi.fn(),
})),
};
});
vi.mock("@calcom/lib/safeStringify", () => ({
safeStringify: JSON.stringify,
}));
describe("WebhookService", () => {
const mockOptions = {
id: "mockOptionsId",
subscriberUrl: "subUrl",
payloadTemplate: "PayloadTemplate",
appId: "AppId",
secret: "WhSecret",
triggerEvent: WebhookTriggerEvents.BOOKING_CREATED,
};
beforeEach(() => {
vi.resetAllMocks();
});
it("should initialize with options and webhooks", async () => {
const mockWebhooks = [
{
id: "webhookId",
subscriberUrl: "url",
secret: "secret",
appId: "appId",
payloadTemplate: "payloadTemplate",
},
];
vi.mocked(getWebhooks).mockResolvedValue(mockWebhooks);
// Has to be called with await due to the iffi being async
const service = await new WebhookService(mockOptions);
expect(service).toBeInstanceOf(WebhookService);
expect(await service.getWebhooks()).toEqual(mockWebhooks);
expect(getWebhooks).toHaveBeenCalledWith(mockOptions);
});
// it("should send payload to all webhooks", async () => {
// const mockWebhooks = [
// {
// id: "webhookId",
// subscriberUrl: "url",
// secret: "secret",
// appId: "appId",
// payloadTemplate: "payloadTemplate",
// },
// {
// id: "webhookId2",
// subscriberUrl: "url",
// secret: "secret2",
// appId: "appId2",
// payloadTemplate: "payloadTemplate",
// },
// ];
// vi.mocked(getWebhooks).mockResolvedValue(mockWebhooks);
// const service = await new WebhookService(mockOptions);
//
// const payload = {
// secretKey: "secret",
// triggerEvent: "triggerEvent",
// createdAt: "now",
// webhook: {
// subscriberUrl: "url",
// appId: "appId",
// payloadTemplate: "payloadTemplate",
// },
// data: "test",
// };
//
// await service.sendPayload(payload as any);
//
// expect(sendOrSchedulePayload).toHaveBeenCalledTimes(mockWebhooks.length);
//
// mockWebhooks.forEach((webhook) => {
// expect(sendOrSchedulePayload).toHaveBeenCalledWith(
// webhook.secret,
// mockOptions.triggerEvent,
// expect.any(String),
// webhook,
// payload
// );
// });
// });
//
// it("should log error when sending payload fails", async () => {
// const mockWebhooks = [
// {
// id: "webhookId",
// subscriberUrl: "url",
// secret: "secret",
// appId: "appId",
// payloadTemplate: "payloadTemplate",
// },
// ];
// vi.mocked(getWebhooks).mockResolvedValue(mockWebhooks);
//
// const logError = vi.fn();
//
// (sendOrSchedulePayload as any).mockImplementation(() => {
// throw new Error("Failure");
// });
//
// const service = new WebhookService(mockOptions);
//
// const payload = {
// secretKey: "secret", triggerEvent: "triggerEvent", createdAt: "now", webhook: {
// subscriberUrl: "url",
// appId: "appId",
// payloadTemplate: "payloadTemplate"
// },
// data: "test"
// };
//
// await service.sendPayload(payload as any);
//
// expect(logError).toHaveBeenCalledWith(
// `Error executing webhook for event: ${mockOptions.triggerEvent}, URL: ${mockWebhooks[0].subscriberUrl}`,
// JSON.stringify(new Error("Failure"))
// );
// });
});
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "WebhookTriggerEvents" ADD VALUE 'BOOKING_NO_SHOW_UPDATED';
+1
View File
@@ -708,6 +708,7 @@ enum WebhookTriggerEvents {
BOOKING_REQUESTED
BOOKING_CANCELLED
BOOKING_REJECTED
BOOKING_NO_SHOW_UPDATED
FORM_SUBMITTED
MEETING_ENDED
MEETING_STARTED
@@ -1,5 +1,9 @@
import { WebhookService } from "@calcom/features/webhooks/lib/WebhookService";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { prisma } from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/client";
import type { TNoShowInputSchema } from "./noShow.schema";
@@ -7,6 +11,24 @@ type NoShowOptions = {
input: TNoShowInputSchema;
};
const getResultPayload = async (attendees: { email: string; noShow: boolean }[]) => {
if (attendees.length === 1) {
const [attendee] = attendees;
return {
message: attendee.noShow ? "x_marked_as_no_show" : "x_unmarked_as_no_show",
attendees: [attendee],
};
}
return { message: "no_show_updated", attendees: attendees };
};
const logFailedResults = (results: PromiseSettledResult<any>[]) => {
const failed = results.filter((x) => x.status === "rejected") as PromiseRejectedResult[];
if (failed.length < 1) return;
const failedMessage = failed.map((r) => r.reason);
console.error("Failed to update no-show status", failedMessage.join(","));
};
export const noShowHandler = async ({ input }: NoShowOptions) => {
const { bookingUid, attendees } = input;
@@ -31,33 +53,73 @@ export const noShowHandler = async ({ input }: NoShowOptions) => {
email: true,
},
});
const allAttendeesMap = allAttendees.reduce((acc, attendee) => {
acc[attendee.email] = attendee;
return acc;
}, {} as Record<string, { id: number; email: string }>);
const updatePromises = attendees.map((attendee) => {
const attendeeToUpdate = allAttendees.find((a) => a.email === attendee.email);
if (attendeeToUpdate) {
return prisma.attendee.update({
where: { id: attendeeToUpdate.id },
data: { noShow: attendee.noShow },
});
}
const attendeeToUpdate = allAttendeesMap[attendee.email];
if (!attendeeToUpdate) return;
return prisma.attendee.update({
where: { id: attendeeToUpdate.id },
data: { noShow: attendee.noShow },
});
});
await Promise.all(updatePromises);
} else {
await prisma.booking.update({
where: {
uid: bookingUid,
},
data: {
noShowHost: true,
const results = await Promise.allSettled(updatePromises);
logFailedResults(results);
const _attendees = results
.filter((x) => x.status === "fulfilled")
.map((x) => (x as PromiseFulfilledResult<{ noShow: boolean; email: string }>).value)
.map((x) => ({ email: x.email, noShow: x.noShow }));
const payload = await getResultPayload(_attendees);
const booking = await prisma.booking.findUnique({
where: { uid: bookingUid },
select: {
eventType: {
select: {
id: true,
teamId: true,
userId: true,
},
},
},
});
const orgId = await getOrgIdFromMemberOrTeamId({
memberId: booking?.eventType?.userId,
teamId: booking?.eventType?.teamId,
});
const webhooks = await new WebhookService({
teamId: booking?.eventType?.teamId,
userId: booking?.eventType?.userId,
eventTypeId: booking?.eventType?.id,
orgId,
triggerEvent: WebhookTriggerEvents.BOOKING_NO_SHOW_UPDATED,
});
const t = await getTranslation("en", "common");
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
message: t(payload.message, { x: payload.attendees[0]?.email || "User" }),
bookingUid,
});
return payload;
}
await prisma.booking.update({
where: {
uid: bookingUid,
},
data: {
noShowHost: true,
},
});
return { message: "No-show status updated", noShowHost: true };
} catch (error) {
if (error instanceof Error) {
logger.error(error.message);
}
return { message: "Failed to update no-show status" };
}
};