Skip to content

Scheduling infrastructure for absolutely everyone.

refactor: Canceling Seats (#13136)

Joe Au-Yeungd1810d9f1413
diff --git a/apps/web/test/utils/bookingScenario/bookingScenario.ts b/apps/web/test/utils/bookingScenario/bookingScenario.ts
index 33ef4e6f2fb..a185994dcd6 100644
--- a/apps/web/test/utils/bookingScenario/bookingScenario.ts
+++ b/apps/web/test/utils/bookingScenario/bookingScenario.ts
@@ -127,6 +127,7 @@ export type InputEventType = {
schedule?: InputUser["schedules"][number];
bookingLimits?: IntervalLimit;
durationLimits?: IntervalLimit;
+ owner?: number;
} & Partial<Omit<Prisma.EventTypeCreateInput, "users" | "schedule" | "bookingLimits" | "durationLimits">>;
type AttendeeBookingSeatInput = Pick<Prisma.BookingSeatCreateInput, "referenceUid" | "data">;
@@ -279,6 +280,7 @@ async function addEventTypes(eventTypes: InputEventType[], usersStore: InputUser
},
}
: eventType.schedule,
+ owner: eventType.owner ? { connect: { id: eventType.owner } } : undefined,
};
});
log.silly("TestData: Creating EventType", JSON.stringify(eventTypesWithUsers));
diff --git a/apps/web/test/utils/bookingScenario/getMockRequestDataForCancelBooking.ts b/apps/web/test/utils/bookingScenario/getMockRequestDataForCancelBooking.ts
new file mode 100644
index 00000000000..fe7424a8f48
--- /dev/null
+++ b/apps/web/test/utils/bookingScenario/getMockRequestDataForCancelBooking.ts
@@ -0,0 +1,7 @@
+import type z from "zod";
+
+import type { schemaBookingCancelParams } from "@calcom/prisma/zod-utils";
+
+export function getMockRequestDataForCancelBooking(data: z.infer<typeof schemaBookingCancelParams>) {
+ return data;
+}
diff --git a/packages/features/bookings/lib/handleCancelBooking.ts b/packages/features/bookings/lib/handleCancelBooking.ts
index 6d39d5ba438..9cdd8b90643 100644
--- a/packages/features/bookings/lib/handleCancelBooking.ts
+++ b/packages/features/bookings/lib/handleCancelBooking.ts
@@ -5,9 +5,9 @@ import appStore from "@calcom/app-store";
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { FAKE_DAILY_CREDENTIAL } from "@calcom/app-store/dailyvideo/lib/VideoApiAdapter";
import { DailyLocationType } from "@calcom/app-store/locations";
-import { deleteMeeting, updateMeeting } from "@calcom/core/videoClient";
+import { deleteMeeting } from "@calcom/core/videoClient";
import dayjs from "@calcom/dayjs";
-import { sendCancelledEmails, sendCancelledSeatEmails } from "@calcom/emails";
+import { sendCancelledEmails } from "@calcom/emails";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { deleteScheduledEmailReminder } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";
import { sendCancelledReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
@@ -25,12 +25,15 @@ import { handleRefundError } from "@calcom/lib/payment/handleRefundError";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
-import { BookingStatus, MembershipRole, WebhookTriggerEvents, WorkflowMethods } from "@calcom/prisma/enums";
+import type { WebhookTriggerEvents } from "@calcom/prisma/enums";
+import { BookingStatus, MembershipRole, WorkflowMethods } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { schemaBookingCancelParams } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { IAbstractPaymentService, PaymentApp } from "@calcom/types/PaymentService";
+import cancelAttendeeSeat from "./handleSeats/cancel/cancelAttendeeSeat";
+
async function getBookingToDelete(id: number | undefined, uid: string | undefined) {
return await prisma.booking.findUnique({
where: {
@@ -122,7 +125,7 @@ async function getBookingToDelete(id: number | undefined, uid: string | undefine
});
}
-type CustomRequest = NextApiRequest & {
+export type CustomRequest = NextApiRequest & {
userId?: number;
bookingToDelete?: Awaited<ReturnType<typeof getBookingToDelete>>;
};
@@ -274,30 +277,9 @@ async function handler(req: CustomRequest) {
const dataForWebhooks = { evt, webhooks, eventTypeInfo };
// If it's just an attendee of a booking then just remove them from that booking
- const result = await handleSeatedEventCancellation(req, dataForWebhooks);
+ const result = await cancelAttendeeSeat(req, dataForWebhooks);
if (result) return { success: true };
- // If it's just an attendee of a booking then just remove them from that booking
- if (seatReferenceUid && bookingToDelete.attendees.length > 1) {
- const seatReference = bookingToDelete.seatsReferences.find(
- (reference) => reference.referenceUid === seatReferenceUid
- );
-
- const attendee = bookingToDelete.attendees.find((attendee) => attendee.id === seatReference?.attendeeId);
-
- if (!seatReference || !attendee)
- throw new HttpError({ statusCode: 400, message: "User not a part of this booking" });
-
- await prisma.attendee.delete({
- where: {
- id: seatReference.attendeeId,
- },
- });
-
- req.statusCode = 200;
- return { message: "No longer attending event" };
- }
-
const promises = webhooks.map((webhook) =>
sendPayload(webhook.secret, eventTrigger, new Date().toISOString(), webhook, {
...evt,
@@ -696,147 +678,4 @@ async function handler(req: CustomRequest) {
return { message: "Booking successfully cancelled." };
}
-async function handleSeatedEventCancellation(
- req: CustomRequest,
- dataForWebhooks: {
- webhooks: {
- id: string;
- subscriberUrl: string;
- payloadTemplate: string | null;
- appId: string | null;
- secret: string | null;
- }[];
- evt: CalendarEvent;
- eventTypeInfo: EventTypeInfo;
- }
-) {
- const { seatReferenceUid } = schemaBookingCancelParams.parse(req.body);
- const { webhooks, evt, eventTypeInfo } = dataForWebhooks;
- if (!seatReferenceUid) return;
- const bookingToDelete = req.bookingToDelete;
- if (!bookingToDelete?.attendees.length || bookingToDelete.attendees.length < 2) return;
-
- if (!bookingToDelete.userId) {
- throw new HttpError({ statusCode: 400, message: "User not found" });
- }
-
- const seatReference = bookingToDelete.seatsReferences.find(
- (reference) => reference.referenceUid === seatReferenceUid
- );
-
- if (!seatReference) throw new HttpError({ statusCode: 400, message: "User not a part of this booking" });
-
- await Promise.all([
- prisma.bookingSeat.delete({
- where: {
- referenceUid: seatReferenceUid,
- },
- }),
- prisma.attendee.delete({
- where: {
- id: seatReference.attendeeId,
- },
- }),
- ]);
- req.statusCode = 200;
-
- const attendee = bookingToDelete?.attendees.find((attendee) => attendee.id === seatReference.attendeeId);
-
- if (attendee) {
- /* If there are references then we should update them as well */
-
- const integrationsToUpdate = [];
-
- for (const reference of bookingToDelete.references) {
- if (reference.credentialId) {
- const credential = await prisma.credential.findUnique({
- where: {
- id: reference.credentialId,
- },
- select: credentialForCalendarServiceSelect,
- });
-
- if (credential) {
- const updatedEvt = {
- ...evt,
- attendees: evt.attendees.filter((evtAttendee) => attendee.email !== evtAttendee.email),
- };
- if (reference.type.includes("_video")) {
- integrationsToUpdate.push(updateMeeting(credential, updatedEvt, reference));
- }
- if (reference.type.includes("_calendar")) {
- const calendar = await getCalendar(credential);
- if (calendar) {
- integrationsToUpdate.push(
- calendar?.updateEvent(reference.uid, updatedEvt, reference.externalCalendarId)
- );
- }
- }
- }
- }
- }
-
- try {
- await Promise.all(integrationsToUpdate);
- } catch (error) {
- // Shouldn't stop code execution if integrations fail
- // as integrations was already updated
- }
-
- const tAttendees = await getTranslation(attendee.locale ?? "en", "common");
-
- await sendCancelledSeatEmails(evt, {
- ...attendee,
- language: { translate: tAttendees, locale: attendee.locale ?? "en" },
- });
- }
-
- evt.attendees = attendee
- ? [
- {
- ...attendee,
- language: {
- translate: await getTranslation(attendee.locale ?? "en", "common"),
- locale: attendee.locale ?? "en",
- },
- },
- ]
- : [];
-
- 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) => {
- console.error(
- `Error executing webhook for event: ${WebhookTriggerEvents.BOOKING_CANCELLED}, URL: ${webhook.subscriberUrl}`,
- e
- );
- })
- );
- await Promise.all(promises);
-
- const workflowRemindersForAttendee = bookingToDelete?.workflowReminders.filter(
- (reminder) => reminder.seatReferenceId === seatReferenceUid
- );
-
- if (workflowRemindersForAttendee && workflowRemindersForAttendee.length !== 0) {
- const deletionPromises = workflowRemindersForAttendee.map((reminder) => {
- if (reminder.method === WorkflowMethods.EMAIL) {
- return deleteScheduledEmailReminder(reminder.id, reminder.referenceId);
- } else if (reminder.method === WorkflowMethods.SMS) {
- return deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
- } else if (reminder.method === WorkflowMethods.WHATSAPP) {
- return deleteScheduledWhatsappReminder(reminder.id, reminder.referenceId);
- }
- });
-
- await Promise.allSettled(deletionPromises);
- }
-
- return { success: true };
-}
-
export default handler;
diff --git a/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts b/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts
new file mode 100644
index 00000000000..667c5bbe4a8
--- /dev/null
+++ b/packages/features/bookings/lib/handleSeats/cancel/cancelAttendeeSeat.ts
@@ -0,0 +1,162 @@
+import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
+import { updateMeeting } from "@calcom/core/videoClient";
+import { sendCancelledSeatEmails } from "@calcom/emails";
+import { deleteScheduledEmailReminder } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";
+import { deleteScheduledSMSReminder } from "@calcom/features/ee/workflows/lib/reminders/smsReminderManager";
+import { deleteScheduledWhatsappReminder } from "@calcom/features/ee/workflows/lib/reminders/whatsappReminderManager";
+import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
+import sendPayload from "@calcom/features/webhooks/lib/sendPayload";
+import { HttpError } from "@calcom/lib/http-error";
+import { getTranslation } from "@calcom/lib/server/i18n";
+import prisma from "@calcom/prisma";
+import { WebhookTriggerEvents, WorkflowMethods } from "@calcom/prisma/enums";
+import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
+import { schemaBookingCancelParams } from "@calcom/prisma/zod-utils";
+import type { CalendarEvent } from "@calcom/types/Calendar";
+
+import type { CustomRequest } from "../../handleCancelBooking";
+
+async function cancelAttendeeSeat(
+ req: CustomRequest,
+ dataForWebhooks: {
+ webhooks: {
+ id: string;
+ subscriberUrl: string;
+ payloadTemplate: string | null;
+ appId: string | null;
+ secret: string | null;
+ }[];
+ evt: CalendarEvent;
+ eventTypeInfo: EventTypeInfo;
+ }
+) {
+ const { seatReferenceUid } = schemaBookingCancelParams.parse(req.body);
+ const { webhooks, evt, eventTypeInfo } = dataForWebhooks;
+ if (!seatReferenceUid) return;
+ const bookingToDelete = req.bookingToDelete;
+ if (!bookingToDelete?.attendees.length || bookingToDelete.attendees.length < 2) return;
+
+ if (!bookingToDelete.userId) {
+ throw new HttpError({ statusCode: 400, message: "User not found" });
+ }
+
+ const seatReference = bookingToDelete.seatsReferences.find(
+ (reference) => reference.referenceUid === seatReferenceUid
+ );
+
+ if (!seatReference) throw new HttpError({ statusCode: 400, message: "User not a part of this booking" });
+
+ await Promise.all([
+ prisma.bookingSeat.delete({
+ where: {
+ referenceUid: seatReferenceUid,
+ },
+ }),
+ prisma.attendee.delete({
+ where: {
+ id: seatReference.attendeeId,
+ },
+ }),
+ ]);
+ req.statusCode = 200;
+
+ const attendee = bookingToDelete?.attendees.find((attendee) => attendee.id === seatReference.attendeeId);
+
+ if (attendee) {
+ /* If there are references then we should update them as well */
+
+ const integrationsToUpdate = [];
+
+ for (const reference of bookingToDelete.references) {
+ if (reference.credentialId) {
+ const credential = await prisma.credential.findUnique({
+ where: {
+ id: reference.credentialId,
+ },
+ select: credentialForCalendarServiceSelect,
+ });
+
+ if (credential) {
+ const updatedEvt = {
+ ...evt,
+ attendees: evt.attendees.filter((evtAttendee) => attendee.email !== evtAttendee.email),
+ };
+ if (reference.type.includes("_video")) {
+ integrationsToUpdate.push(updateMeeting(credential, updatedEvt, reference));
+ }
+ if (reference.type.includes("_calendar")) {
+ const calendar = await getCalendar(credential);
+ if (calendar) {
+ integrationsToUpdate.push(
+ calendar?.updateEvent(reference.uid, updatedEvt, reference.externalCalendarId)
+ );
+ }
+ }
+ }
+ }
+ }
+
+ try {
+ await Promise.all(integrationsToUpdate);
+ } catch (error) {
+ // Shouldn't stop code execution if integrations fail
+ // as integrations was already updated
+ }
+
+ const tAttendees = await getTranslation(attendee.locale ?? "en", "common");
+
+ await sendCancelledSeatEmails(evt, {
+ ...attendee,
+ language: { translate: tAttendees, locale: attendee.locale ?? "en" },
+ });
+ }
+
+ evt.attendees = attendee
+ ? [
+ {
+ ...attendee,
+ language: {
+ translate: await getTranslation(attendee.locale ?? "en", "common"),
+ locale: attendee.locale ?? "en",
+ },
+ },
+ ]
+ : [];
+
+ 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) => {
+ console.error(
+ `Error executing webhook for event: ${WebhookTriggerEvents.BOOKING_CANCELLED}, URL: ${webhook.subscriberUrl}`,
+ e
+ );
+ })
+ );
+ await Promise.all(promises);
+
+ const workflowRemindersForAttendee = bookingToDelete?.workflowReminders.filter(
+ (reminder) => reminder.seatReferenceId === seatReferenceUid
+ );
+
+ if (workflowRemindersForAttendee && workflowRemindersForAttendee.length !== 0) {
+ const deletionPromises = workflowRemindersForAttendee.map((reminder) => {
+ if (reminder.method === WorkflowMethods.EMAIL) {
+ return deleteScheduledEmailReminder(reminder.id, reminder.referenceId);
+ } else if (reminder.method === WorkflowMethods.SMS) {
+ return deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
+ } else if (reminder.method === WorkflowMethods.WHATSAPP) {
+ return deleteScheduledWhatsappReminder(reminder.id, reminder.referenceId);
+ }
+ });
+
+ await Promise.allSettled(deletionPromises);
+ }
+
+ return { success: true };
+}
+
+export default cancelAttendeeSeat;
diff --git a/packages/features/bookings/lib/handleSeats/test/handleSeats.test.ts b/packages/features/bookings/lib/handleSeats/test/handleSeats.test.ts
index 8bcf4519867..51f8b29d524 100644
--- a/packages/features/bookings/lib/handleSeats/test/handleSeats.test.ts
+++ b/packages/features/bookings/lib/handleSeats/test/handleSeats.test.ts
@@ -18,6 +18,7 @@ import {
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { createMockNextJsRequest } from "@calcom/web/test/utils/bookingScenario/createMockNextJsRequest";
import { getMockRequestDataForBooking } from "@calcom/web/test/utils/bookingScenario/getMockRequestDataForBooking";
+import { getMockRequestDataForCancelBooking } from "@calcom/web/test/utils/bookingScenario/getMockRequestDataForCancelBooking";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import * as handleSeatsModule from "../handleSeats";
@@ -1241,6 +1242,299 @@ describe("handleSeats", () => {
expect(attendeeSeat?.bookingSeat?.bookingId).toEqual(createdBooking.id);
});
});
+
+ describe("Canceling a booking", async () => {
+ test("When canceling a booking, only remove that single attendee", async () => {
+ const handleCancelBooking = (await import("@calcom/features/bookings/lib/handleCancelBooking"))
+ .default;
+
+ const organizer = getOrganizer({
+ name: "Organizer",
+ email: "[email protected]",
+ id: 101,
+ schedules: [TestData.schedules.IstWorkHours],
+ });
+
+ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
+ const bookingStartTime = `${plus1DateString}T04:00:00.00Z`;
+ const bookingEndTime = `${plus1DateString}T15:00:00.00Z`;
+ const bookingUid = "abc123";
+ const bookingId = 1;
+
+ const attendeeIdToBeCancelled = 2;
+ const bookingSeatToBeCancelledUid = "booking-seat-2";
+
+ await createBookingScenario(
+ getScenarioData({
+ eventTypes: [
+ {
+ id: bookingId,
+ slug: "seated-event",
+ slotInterval: 45,
+ length: 45,
+ users: [
+ {
+ id: 101,
+ },
+ ],
+ seatsPerTimeSlot: 4,
+ seatsShowAttendees: false,
+ owner: organizer.id,
+ },
+ ],
+ bookings: [
+ {
+ id: 1,
+ uid: bookingUid,
+ eventTypeId: 1,
+ userId: organizer.id,
+ status: BookingStatus.ACCEPTED,
+ startTime: bookingStartTime,
+ endTime: bookingEndTime,
+ 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,
+ },
+ ],
+ attendees: [
+ getMockBookingAttendee({
+ id: 1,
+ name: "Seat 1",
+ email: "[email protected]",
+ locale: "en",
+ timeZone: "America/Toronto",
+ bookingSeat: {
+ referenceUid: "booking-seat-1",
+ data: {},
+ },
+ }),
+ getMockBookingAttendee({
+ id: 2,
+ name: "Seat 2",
+ email: "[email protected]",
+ locale: "en",
+ timeZone: "America/Toronto",
+ bookingSeat: {
+ referenceUid: "booking-seat-2",
+ data: {},
+ },
+ }),
+ ],
+ },
+ ],
+ organizer,
+ })
+ );
+
+ mockSuccessfulVideoMeetingCreation({
+ metadataLookupKey: "dailyvideo",
+ videoMeetingData: {
+ id: "MOCK_ID",
+ password: "MOCK_PASS",
+ url: `http://mock-dailyvideo.example.com/meeting-1`,
+ },
+ });
+
+ const mockCancelBookingData = getMockRequestDataForCancelBooking({
+ id: bookingId,
+ uid: bookingUid,
+ seatReferenceUid: bookingSeatToBeCancelledUid,
+ });
+
+ const { req } = createMockNextJsRequest({
+ method: "POST",
+ body: mockCancelBookingData,
+ });
+
+ req.userId = organizer.id;
+
+ await handleCancelBooking(req);
+
+ // Ensure that the booking has been cancelled
+ const cancelledBooking = await prismaMock.booking.findFirst({
+ where: {
+ id: bookingId,
+ },
+ select: {
+ status: true,
+ },
+ });
+
+ // Check that the booking is still accepted
+ expect(cancelledBooking?.status).toEqual(BookingStatus.ACCEPTED);
+
+ // Check that the booking does not contain the cancelled attendee
+ const attendees = await prismaMock.attendee.findMany({
+ where: {
+ bookingId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ expect(attendees).not.toContain({ id: attendeeIdToBeCancelled });
+
+ const bookingSeats = await prismaMock.bookingSeat.findMany({
+ where: {
+ bookingId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ expect(bookingSeats).not.toContain({ referenceUid: bookingSeatToBeCancelledUid });
+ });
+
+ test("When last attendee cancels a booking, delete event", async () => {
+ const handleCancelBooking = (await import("@calcom/features/bookings/lib/handleCancelBooking"))
+ .default;
+
+ const organizer = getOrganizer({
+ name: "Organizer",
+ email: "[email protected]",
+ id: 101,
+ schedules: [TestData.schedules.IstWorkHours],
+ });
+
+ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
+ const bookingStartTime = `${plus1DateString}T04:00:00.00Z`;
+ const bookingEndTime = `${plus1DateString}T15:00:00.00Z`;
+ const bookingUid = "abc123";
+ const bookingId = 1;
+
+ const attendeeIdToBeCancelled = 1;
+ const bookingSeatToBeCancelledUid = "booking-seat-1";
+
+ await createBookingScenario(
+ getScenarioData({
+ eventTypes: [
+ {
+ id: bookingId,
+ slug: "seated-event",
+ slotInterval: 45,
+ length: 45,
+ users: [
+ {
+ id: 101,
+ },
+ ],
+ seatsPerTimeSlot: 4,
+ seatsShowAttendees: false,
+ owner: organizer.id,
+ },
+ ],
+ bookings: [
+ {
+ id: 1,
+ uid: bookingUid,
+ eventTypeId: 1,
+ userId: organizer.id,
+ status: BookingStatus.ACCEPTED,
+ startTime: bookingStartTime,
+ endTime: bookingEndTime,
+ 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,
+ },
+ ],
+ attendees: [
+ getMockBookingAttendee({
+ id: 1,
+ name: "Seat 1",
+ email: "[email protected]",
+ locale: "en",
+ timeZone: "America/Toronto",
+ bookingSeat: {
+ referenceUid: "booking-seat-1",
+ data: {},
+ },
+ }),
+ ],
+ },
+ ],
+ organizer,
+ })
+ );
+
+ mockSuccessfulVideoMeetingCreation({
+ metadataLookupKey: "dailyvideo",
+ videoMeetingData: {
+ id: "MOCK_ID",
+ password: "MOCK_PASS",
+ url: `http://mock-dailyvideo.example.com/meeting-1`,
+ },
+ });
+
+ const mockCancelBookingData = getMockRequestDataForCancelBooking({
+ id: bookingId,
+ uid: bookingUid,
+ seatReferenceUid: bookingSeatToBeCancelledUid,
+ });
+
+ const { req } = createMockNextJsRequest({
+ method: "POST",
+ body: mockCancelBookingData,
+ });
+
+ req.userId = organizer.id;
+
+ await handleCancelBooking(req);
+
+ // Ensure that the booking has been cancelled
+ const cancelledBooking = await prismaMock.booking.findFirst({
+ where: {
+ id: bookingId,
+ },
+ select: {
+ status: true,
+ },
+ });
+
+ // Check that the booking is still accepted
+ expect(cancelledBooking?.status).toEqual(BookingStatus.CANCELLED);
+
+ // Check that the booking does not contain the cancelled attendee
+ const attendees = await prismaMock.attendee.findMany({
+ where: {
+ bookingId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ expect(attendees).not.toContain({ id: attendeeIdToBeCancelled });
+
+ const bookingSeats = await prismaMock.bookingSeat.findMany({
+ where: {
+ bookingId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ expect(bookingSeats).not.toContain({ referenceUid: bookingSeatToBeCancelledUid });
+ });
+ });
});
describe("As an owner", () => {
@@ -1430,8 +1724,8 @@ describe("handleSeats", () => {
const secondBookingUid = "def456";
const secondBookingId = 2;
const { dateString: plus2DateString } = getDate({ dateIncrement: 2 });
- const secondBookingStartTime = `${plus2DateString}T04:00:00.000Z`;
- const secondBookingEndTime = `${plus2DateString}T05:15:00.000Z`;
+ const secondBookingStartTime = `${plus2DateString}T04:00:00Z`;
+ const secondBookingEndTime = `${plus2DateString}T05:15:00Z`;
await createBookingScenario(
getScenarioData({
@@ -1795,5 +2089,142 @@ describe("handleSeats", () => {
await expect(() => handleNewBooking(req)).rejects.toThrowError(ErrorCode.NotEnoughAvailableSeats);
});
});
+
+ describe("Cancelling a booking", () => {
+ test("When owner cancels booking, cancel booking for all attendees", async () => {
+ const handleCancelBooking = (await import("@calcom/features/bookings/lib/handleCancelBooking"))
+ .default;
+
+ const booker = getBooker({
+ email: "[email protected]",
+ name: "Booker",
+ });
+
+ const organizer = getOrganizer({
+ name: "Organizer",
+ email: "[email protected]",
+ id: 101,
+ schedules: [TestData.schedules.IstWorkHours],
+ });
+
+ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
+ const firstBookingStartTime = `${plus1DateString}T04:00:00.00Z`;
+ const firstBookingEndTime = `${plus1DateString}T15:00:00.00Z`;
+ const firstBookingUid = "abc123";
+ const firstBookingId = 1;
+
+ await createBookingScenario(
+ getScenarioData({
+ eventTypes: [
+ {
+ id: firstBookingId,
+ slug: "seated-event",
+ slotInterval: 45,
+ length: 45,
+ users: [
+ {
+ id: 101,
+ },
+ ],
+ seatsPerTimeSlot: 4,
+ seatsShowAttendees: false,
+ owner: organizer.id,
+ },
+ ],
+ bookings: [
+ {
+ id: 1,
+ uid: firstBookingUid,
+ eventTypeId: 1,
+ userId: organizer.id,
+ status: BookingStatus.ACCEPTED,
+ startTime: firstBookingStartTime,
+ endTime: firstBookingEndTime,
+ 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,
+ },
+ ],
+ attendees: [
+ getMockBookingAttendee({
+ id: 1,
+ name: "Seat 1",
+ email: "[email protected]",
+ locale: "en",
+ timeZone: "America/Toronto",
+ bookingSeat: {
+ referenceUid: "booking-seat-1",
+ data: {},
+ },
+ }),
+ getMockBookingAttendee({
+ id: 2,
+ name: "Seat 2",
+ email: "[email protected]",
+ locale: "en",
+ timeZone: "America/Toronto",
+ bookingSeat: {
+ referenceUid: "booking-seat-2",
+ data: {},
+ },
+ }),
+ ],
+ },
+ ],
+ organizer,
+ })
+ );
+
+ mockSuccessfulVideoMeetingCreation({
+ metadataLookupKey: "dailyvideo",
+ videoMeetingData: {
+ id: "MOCK_ID",
+ password: "MOCK_PASS",
+ url: `http://mock-dailyvideo.example.com/meeting-1`,
+ },
+ });
+
+ const mockBookingData = getMockRequestDataForBooking({
+ data: {
+ eventTypeId: 1,
+ responses: {
+ email: booker.email,
+ name: booker.name,
+ location: { optionValue: "", value: BookingLocations.CalVideo },
+ },
+ rescheduleUid: firstBookingUid,
+ },
+ });
+
+ const { req } = createMockNextJsRequest({
+ method: "POST",
+ body: mockBookingData,
+ });
+
+ req.userId = organizer.id;
+
+ await handleCancelBooking(req);
+
+ // Ensure that the booking has been cancelled
+ const cancelledBooking = await prismaMock.booking.findFirst({
+ where: {
+ id: firstBookingId,
+ },
+ select: {
+ status: true,
+ },
+ });
+
+ expect(cancelledBooking?.status).toEqual(BookingStatus.CANCELLED);
+ });
+ });
});
});