feat: automatic no show (#16727)

Co-authored-by: Carina Wollendorfer <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: zomars <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-10-10 10:57:04 -07:00
1 parent ef88effd9f
commit 395381ddcc
43 files changed
+1103 -69

No files matched your search

+9 -1
View File
@@ -3,7 +3,7 @@ import { NextResponse } from "next/server";
import tasker from "..";
export async function GET(request: NextRequest) {
async function handler(request: NextRequest) {
const authHeader = request.headers.get("authorization");
if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
return new Response("Unauthorized", { status: 401 });
@@ -11,3 +11,11 @@ export async function GET(request: NextRequest) {
await tasker.processQueue();
return NextResponse.json({ success: true });
}
export async function GET(request: NextRequest) {
return await handler(request);
}
export async function POST(request: NextRequest) {
return await handler(request);
}
+5 -4
View File
@@ -1,5 +1,5 @@
import { Task } from "./repository";
import { type Tasker, type TaskTypes } from "./tasker";
import { type TaskerCreate, type Tasker } from "./tasker";
import tasksMap from "./tasks";
/**
@@ -9,9 +9,10 @@ import tasksMap from "./tasks";
* Then, you can use the TaskerFactory to select the new Tasker.
*/
export class InternalTasker implements Tasker {
async create(type: TaskTypes, payload: string): Promise<string> {
return Task.create(type, payload);
}
create: TaskerCreate = async (type, payload, options = {}): Promise<string> => {
const payloadString = typeof payload === "string" ? payload : JSON.stringify(payload);
return Task.create(type, payloadString, options);
};
async processQueue(): Promise<void> {
const tasks = await Task.getNextBatch();
const tasksPromises = tasks.map(async (task) => {
+20 -2
View File
@@ -1,9 +1,27 @@
import type { z } from "zod";
export type TaskerTypes = "internal" | "redis";
export type TaskTypes = "sendEmail" | "sendWebhook" | "sendSms";
type TaskPayloads = {
sendEmail: string;
sendWebhook: string;
sendSms: string;
triggerHostNoShowWebhook: z.infer<
typeof import("./tasks/triggerNoShow/schema").ZSendNoShowWebhookPayloadSchema
>;
triggerGuestNoShowWebhook: z.infer<
typeof import("./tasks/triggerNoShow/schema").ZSendNoShowWebhookPayloadSchema
>;
};
export type TaskTypes = keyof TaskPayloads;
export type TaskHandler = (payload: string) => Promise<void>;
export type TaskerCreate = <TaskKey extends keyof TaskPayloads>(
type: TaskKey,
payload: TaskPayloads[TaskKey],
options?: { scheduledAt?: Date; maxAttempts?: number }
) => Promise<string>;
export interface Tasker {
/** Create a new task with the given type and payload. */
create(type: TaskTypes, payload: string): Promise<string>;
create: TaskerCreate;
processQueue(): Promise<void>;
cleanup(): Promise<void>;
}
+4
View File
@@ -8,6 +8,10 @@ import type { TaskHandler, TaskTypes } from "../tasker";
const tasks: Record<TaskTypes, () => Promise<TaskHandler>> = {
sendEmail: () => import("./sendEmail").then((module) => module.sendEmail),
sendWebhook: () => import("./sendWebook").then((module) => module.sendWebhook),
triggerHostNoShowWebhook: () =>
import("./triggerNoShow/triggerHostNoShow").then((module) => module.triggerHostNoShow),
triggerGuestNoShowWebhook: () =>
import("./triggerNoShow/triggerGuestNoShow").then((module) => module.triggerGuestNoShow),
sendSms: () => Promise.resolve(() => Promise.reject(new Error("Not implemented"))),
};
@@ -0,0 +1,153 @@
import dayjs from "@calcom/dayjs";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import type { TimeUnit } from "@calcom/prisma/enums";
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { getBooking } from "./getBooking";
import { getMeetingSessionsFromRoomName } from "./getMeetingSessionsFromRoomName";
import type { TWebhook, TTriggerNoShowPayloadSchema } from "./schema";
import { ZSendNoShowWebhookPayloadSchema } from "./schema";
export type Host = {
id: number;
email: string;
};
export type Booking = Awaited<ReturnType<typeof getBooking>>;
type Webhook = TWebhook;
export type Participants = TTriggerNoShowPayloadSchema["data"][number]["participants"];
export function getHosts(booking: Booking): Host[] {
const hostMap = new Map<number, Host>();
const addHost = (id: number, email: string) => {
if (!hostMap.has(id)) {
hostMap.set(id, { id, email });
}
};
booking?.eventType?.hosts?.forEach((host) => addHost(host.userId, host.user.email));
booking?.eventType?.users?.forEach((user) => addHost(user.id, user.email));
// Add booking.user if not already included
if (booking?.user?.id && booking?.user?.email) {
addHost(booking.user.id, booking.user.email);
}
// Filter hosts to only include those who are also attendees
const attendeeEmails = new Set(booking.attendees?.map((attendee) => attendee.email));
const filteredHosts = Array.from(hostMap.values()).filter(
(host) => attendeeEmails.has(host.email) || host.id === booking.user?.id
);
return filteredHosts;
}
export function sendWebhookPayload(
webhook: Webhook,
triggerEvent: WebhookTriggerEvents,
booking: Booking,
maxStartTime: number,
hostEmail?: string
): Promise<any> {
const maxStartTimeHumanReadable = dayjs.unix(maxStartTime).format("YYYY-MM-DD HH:mm:ss Z");
return sendGenericWebhookPayload({
secretKey: webhook.secret,
triggerEvent,
createdAt: new Date().toISOString(),
webhook,
data: {
bookingId: booking.id,
bookingUid: booking.uid,
startTime: booking.startTime,
endTime: booking.endTime,
...(triggerEvent === WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW ? { email: hostEmail } : {}),
eventType: {
...booking.eventType,
id: booking.eventTypeId,
},
message:
triggerEvent === WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW
? `Guest didn't join the call or didn't join before ${maxStartTimeHumanReadable}`
: `Host with email ${hostEmail} didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
}).catch((e) => {
console.error(
`Error executing webhook for event: ${triggerEvent}, URL: ${webhook.subscriberUrl}`,
webhook,
e
);
});
}
export function calculateMaxStartTime(startTime: Date, time: number, timeUnit: TimeUnit): number {
return dayjs(startTime)
.add(time, timeUnit.toLowerCase() as dayjs.ManipulateType)
.unix();
}
export function checkIfUserJoinedTheCall(userId: number, allParticipants: Participants): boolean {
return allParticipants.some(
(participant) => participant.user_id && parseInt(participant.user_id) === userId
);
}
export const log = logger.getSubLogger({ prefix: ["triggerNoShowTask"] });
export const prepareNoShowTrigger = async (
payload: string
): Promise<{
booking: Booking;
webhook: TWebhook;
hostsThatDidntJoinTheCall: Host[];
numberOfHostsThatJoined: number;
didGuestJoinTheCall: boolean;
} | void> => {
const { bookingId, webhook } = ZSendNoShowWebhookPayloadSchema.parse(JSON.parse(payload));
const booking = await getBooking(bookingId);
if (booking.status !== BookingStatus.ACCEPTED) {
log.debug(
"Booking is not accepted",
safeStringify({
bookingId,
webhook: { id: webhook.id },
})
);
return;
}
const dailyVideoReference = booking.references.find((reference) => reference.type === "daily_video");
if (!dailyVideoReference) {
log.error(
"Daily video reference not found",
safeStringify({
bookingId,
webhook: { id: webhook.id },
})
);
throw new Error(`Daily video reference not found in triggerHostNoShow with bookingId ${bookingId}`);
}
const meetingDetails = await getMeetingSessionsFromRoomName(dailyVideoReference.uid);
const hosts = getHosts(booking);
const allParticipants = meetingDetails.data.flatMap((meeting) => meeting.participants);
const hostsThatDidntJoinTheCall = hosts.filter(
(host) => !checkIfUserJoinedTheCall(host.id, allParticipants)
);
const numberOfHostsThatJoined = hosts.length - hostsThatDidntJoinTheCall.length;
const didGuestJoinTheCall = meetingDetails.data.some(
(meeting) => meeting.max_participants < numberOfHostsThatJoined
);
return { hostsThatDidntJoinTheCall, booking, numberOfHostsThatJoined, webhook, didGuestJoinTheCall };
};
@@ -0,0 +1,71 @@
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
const log = logger.getSubLogger({ prefix: ["trigger-no-show-handler"] });
export const getBooking = async (bookingId: number) => {
const booking = await prisma.booking.findUniqueOrThrow({
where: {
id: bookingId,
},
select: {
...bookingMinimalSelect,
uid: true,
location: true,
status: true,
isRecorded: true,
eventTypeId: true,
references: true,
eventType: {
select: {
id: true,
teamId: true,
parentId: true,
hosts: {
select: {
userId: true,
user: {
select: {
email: true,
},
},
},
},
users: {
select: {
id: true,
email: true,
},
},
},
},
user: {
select: {
id: true,
timeZone: true,
email: true,
name: true,
locale: true,
destinationCalendar: true,
},
},
},
});
if (!booking) {
log.error(
"Couldn't find Booking Id:",
safeStringify({
bookingId,
})
);
throw new HttpError({
message: `Booking of id ${bookingId} does not exist or does not contain daily video as location`,
statusCode: 404,
});
}
return booking;
};
@@ -0,0 +1,7 @@
import { fetcher } from "@calcom/lib/dailyApiFetcher";
import { triggerNoShowPayloadSchema } from "./schema";
export const getMeetingSessionsFromRoomName = async (roomName: string) => {
return fetcher(`/meetings?room=${roomName}`).then(triggerNoShowPayloadSchema.parse);
};
@@ -0,0 +1,57 @@
import { z } from "zod";
import { TIME_UNIT } from "@calcom/features/ee/workflows/lib/constants";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
const commonSchema = z.object({
triggerEvent: z.enum([
WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
]),
bookingId: z.number(),
});
export const ZWebhook = z.object({
id: z.string(),
subscriberUrl: z.string().url(),
appId: z.string().nullable(),
secret: z.string().nullable(),
time: z.number(),
timeUnit: z.enum(TIME_UNIT),
eventTriggers: z.array(z.string()),
payloadTemplate: z.string().nullable(),
});
export type TWebhook = z.infer<typeof ZWebhook>;
export const triggerNoShowPayloadSchema = z.object({
total_count: z.number(),
data: z.array(
z
.object({
id: z.string(),
room: z.string(),
start_time: z.number(),
duration: z.number(),
max_participants: z.number(),
participants: z.array(
z.object({
user_id: z.string().nullable(),
participant_id: z.string(),
user_name: z.string(),
join_time: z.number(),
duration: z.number(),
})
),
})
.passthrough()
),
});
export type TTriggerNoShowPayloadSchema = z.infer<typeof triggerNoShowPayloadSchema>;
export const ZSendNoShowWebhookPayloadSchema = commonSchema.extend({
webhook: ZWebhook,
});
export type TSendNoShowWebhookPayloadSchema = z.infer<typeof ZSendNoShowWebhookPayloadSchema>;
@@ -0,0 +1,21 @@
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { calculateMaxStartTime, sendWebhookPayload, prepareNoShowTrigger } from "./common";
export async function triggerGuestNoShow(payload: string): Promise<void> {
const result = await prepareNoShowTrigger(payload);
if (!result) return;
const { webhook, booking, didGuestJoinTheCall } = result;
const maxStartTime = calculateMaxStartTime(booking.startTime, webhook.time, webhook.timeUnit);
if (!didGuestJoinTheCall) {
await sendWebhookPayload(
webhook,
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
booking,
maxStartTime
);
}
}
@@ -0,0 +1,324 @@
import {
createBookingScenario,
getDate,
getGoogleCalendarCredential,
TestData,
getOrganizer,
getScenarioData,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { expectWebhookToHaveBeenCalledWith } from "@calcom/web/test/utils/bookingScenario/expects";
import { describe, vi, test } from "vitest";
import { appStoreMetadata } from "@calcom/app-store/apps.metadata.generated";
import dayjs from "@calcom/dayjs";
import { TimeUnit } from "@calcom/prisma/enums";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import { calculateMaxStartTime } from "./common";
import { getMeetingSessionsFromRoomName } from "./getMeetingSessionsFromRoomName";
import type { TSendNoShowWebhookPayloadSchema } from "./schema";
import { triggerHostNoShow } from "./triggerHostNoShow";
vi.mock(
"@calcom/features/tasker/tasks/triggerNoShow/getMeetingSessionsFromRoomName",
async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
getMeetingSessionsFromRoomName: vi.fn(),
};
}
);
const timeout = process.env.CI ? 5000 : 20000;
const EMPTY_MEETING_SESSIONS = {
total_count: 0,
data: [],
};
describe("Trigger Host No Show:", () => {
test(
`Should trigger host no show webhook when no one joined the call`,
async () => {
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
});
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const uidOfBooking = "n5Wv3eHgconAED2j4gcVhP";
const iCalUID = `${uidOfBooking}@Cal.com`;
const subscriberUrl = "http://my-webhook.example.com";
const bookingStartTime = `${plus1DateString}T05:00:00.000Z`;
await createBookingScenario(
getScenarioData({
webhooks: [
{
id: "22",
userId: organizer.id,
eventTriggers: [WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW],
subscriberUrl,
active: true,
eventTypeId: 1,
appId: null,
time: 5,
timeUnit: TimeUnit.MINUTE,
},
],
eventTypes: [
{
id: 1,
slotInterval: 15,
length: 15,
users: [
{
id: 101,
},
],
},
],
bookings: [
{
id: 222,
uid: uidOfBooking,
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
startTime: bookingStartTime,
endTime: `${plus1DateString}T05:15:00.000Z`,
user: { id: organizer.id },
metadata: {
videoCallUrl: "https://existing-daily-video-call-url.example.com",
},
references: [
{
type: appStoreMetadata.dailyvideo.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASS",
meetingUrl: "http://mock-dailyvideo.example.com",
credentialId: null,
},
{
type: appStoreMetadata.googlecalendar.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
externalCalendarId: "MOCK_EXTERNAL_CALENDAR_ID",
credentialId: undefined,
},
],
iCalUID,
},
],
organizer,
apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],
})
);
vi.mocked(getMeetingSessionsFromRoomName).mockResolvedValue(EMPTY_MEETING_SESSIONS);
const payload = JSON.stringify({
triggerEvent: WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
bookingId: 222,
webhook: {
id: "22",
eventTriggers: [WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW],
subscriberUrl,
active: true,
eventTypeId: 1,
appId: null,
time: 5,
timeUnit: TimeUnit.MINUTE,
payloadTemplate: null,
secret: null,
},
} satisfies TSendNoShowWebhookPayloadSchema);
await triggerHostNoShow(payload);
const maxStartTime = calculateMaxStartTime(bookingStartTime, 5, TimeUnit.MINUTE);
const maxStartTimeHumanReadable = dayjs.unix(maxStartTime).format("YYYY-MM-DD HH:mm:ss Z");
await expectWebhookToHaveBeenCalledWith(subscriberUrl, {
triggerEvent: WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
payload: {
bookingId: 222,
bookingUid: uidOfBooking,
email: "[email protected]",
startTime: `${plus1DateString}T05:00:00.000Z`,
endTime: `${plus1DateString}T05:15:00.000Z`,
eventType: {
id: 1,
teamId: null,
parentId: null,
hosts: [],
users: [{ id: organizer.id, email: organizer.email }],
},
message: `Host with email ${organizer.email} didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
},
timeout
);
test(
`Should trigger host no show webhook when host didn't joined the call`,
async () => {
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
});
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const uidOfBooking = "n5Wv3eHgconAED2j4gcVhP";
const iCalUID = `${uidOfBooking}@Cal.com`;
const subscriberUrl = "http://my-webhook.example.com";
const bookingStartTime = `${plus1DateString}T05:00:00.000Z`;
await createBookingScenario(
getScenarioData({
webhooks: [
{
id: "22",
userId: organizer.id,
eventTriggers: [WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW],
subscriberUrl,
active: true,
eventTypeId: 1,
appId: null,
time: 5,
timeUnit: TimeUnit.MINUTE,
},
],
eventTypes: [
{
id: 1,
slotInterval: 15,
length: 15,
users: [
{
id: 101,
},
],
},
],
bookings: [
{
id: 222,
uid: uidOfBooking,
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
startTime: bookingStartTime,
endTime: `${plus1DateString}T05:15:00.000Z`,
user: { id: organizer.id },
metadata: {
videoCallUrl: "https://existing-daily-video-call-url.example.com",
},
references: [
{
type: appStoreMetadata.dailyvideo.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASS",
meetingUrl: "http://mock-dailyvideo.example.com",
credentialId: null,
},
{
type: appStoreMetadata.googlecalendar.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
externalCalendarId: "MOCK_EXTERNAL_CALENDAR_ID",
credentialId: undefined,
},
],
iCalUID,
},
],
organizer,
apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],
})
);
const MOCKED_MEETING_SESSIONS = {
total_count: 1,
data: [
{
id: "MOCK_ID",
room: "MOCK_ROOM",
start_time: "MOCK_START_TIME",
duration: 15,
max_participants: 1,
// User with id 101 is not in the participants list
participants: [
{
user_id: null,
participant_id: "MOCK_PARTICIPANT_ID",
user_name: "MOCK_USER_NAME",
join_time: 0,
duration: 15,
},
],
},
],
};
vi.mocked(getMeetingSessionsFromRoomName).mockResolvedValue(MOCKED_MEETING_SESSIONS);
const payload = JSON.stringify({
triggerEvent: WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
bookingId: 222,
webhook: {
id: "22",
eventTriggers: [WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW],
subscriberUrl,
active: true,
eventTypeId: 1,
appId: null,
time: 5,
timeUnit: TimeUnit.MINUTE,
payloadTemplate: null,
secret: null,
},
} satisfies TSendNoShowWebhookPayloadSchema);
await triggerHostNoShow(payload);
const maxStartTime = calculateMaxStartTime(bookingStartTime as unknown as Date, 5, TimeUnit.MINUTE);
const maxStartTimeHumanReadable = dayjs.unix(maxStartTime).format("YYYY-MM-DD HH:mm:ss Z");
await expectWebhookToHaveBeenCalledWith(subscriberUrl, {
triggerEvent: WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
payload: {
bookingId: 222,
bookingUid: uidOfBooking,
email: "[email protected]",
startTime: `${plus1DateString}T05:00:00.000Z`,
endTime: `${plus1DateString}T05:15:00.000Z`,
eventType: {
id: 1,
teamId: null,
parentId: null,
hosts: [],
users: [{ id: organizer.id, email: organizer.email }],
},
message: `Host with email ${organizer.email} didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
},
timeout
);
});
@@ -0,0 +1,57 @@
import { prisma } from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import type { Booking, Host } from "./common";
import { calculateMaxStartTime, sendWebhookPayload, prepareNoShowTrigger, log } from "./common";
const markHostsAsNoShowInBooking = async (booking: Booking, hostsThatDidntJoinTheCall: Host[]) => {
try {
await Promise.allSettled(
hostsThatDidntJoinTheCall.map((host) => {
if (booking?.user?.id === host.id) {
return prisma.booking.update({
where: {
uid: booking.uid,
},
data: {
noShowHost: true,
},
});
}
// If there are more than one host then it is stored in attendees table
else if (booking.attendees?.some((attendee) => attendee.email === host.email)) {
return prisma.attendee.update({
where: { id: host.id },
data: { noShow: true },
});
}
return Promise.resolve();
})
);
} catch (error) {
log.error("Error marking hosts as no show in booking", error);
}
};
export async function triggerHostNoShow(payload: string): Promise<void> {
const result = await prepareNoShowTrigger(payload);
if (!result) return;
const { booking, webhook, hostsThatDidntJoinTheCall } = result;
const maxStartTime = calculateMaxStartTime(booking.startTime, webhook.time, webhook.timeUnit);
const hostsNoShowPromises = hostsThatDidntJoinTheCall.map((host) => {
return sendWebhookPayload(
webhook,
WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
booking,
maxStartTime,
host.email
);
});
await Promise.all(hostsNoShowPromises);
await markHostsAsNoShowInBooking(booking, hostsThatDidntJoinTheCall);
}