From 9fa73aca863b779747b84c4a0cc92cb532326d3e Mon Sep 17 00:00:00 2001 From: Lauris Skraucis Date: Fri, 22 Nov 2024 17:19:56 +0100 Subject: [PATCH] fix: v2 booking confirmation emails not sent (#17764) * fix: round robin recurring don't send email if noEmail * fix: noEmail: false for non platform requests * fix: booking e2e tests * refactor: move bookings e2e tests in folder and uniform name * test: emails * test: team emails * reschedule and cancel emails with api key * test: round robin reassign emails * test: confirm and decline emails * test: confirm and decline emails * fix tests * test: recurring booking emails * remove unused imports and spies * fix test * remove log * chore: bump libraries * try to fix ci tests --- apps/api/v2/package.json | 2 +- .../api-key-bookings.controller.e2e-spec.ts | 160 --- .../e2e/api-key-bookings.e2e-spec.ts | 291 ++++++ .../{ => e2e}/confirm-bookings.e2e-spec.ts | 23 +- .../e2e/emails/confirm-emails.e2e-spec.ts | 474 +++++++++ .../e2e/emails/team-emails.e2e-spec.ts | 979 ++++++++++++++++++ .../e2e/emails/user-emails.e2e-spec.ts | 482 +++++++++ .../{ => e2e}/reassign-bookings.e2e-spec.ts | 27 +- .../{ => e2e}/recurring-bookings.e2e-spec.ts | 15 + .../{ => e2e}/seated-bookings.e2e-spec.ts | 19 +- .../team-bookings.e2e-spec.ts} | 24 +- .../user-bookings.e2e-spec.ts} | 5 + .../variable-length-bookings.e2e-spec.ts} | 8 +- .../2024-08-13/services/bookings.service.ts | 18 + .../2024-08-13/services/input.service.ts | 133 +-- .../oauth-clients/oauth-client.repository.ts | 24 + .../templates/attendee-cancelled-email.ts | 2 +- .../templates/attendee-declined-email.ts | 2 +- .../templates/attendee-request-email.ts | 13 +- .../templates/attendee-rescheduled-email.ts | 14 +- .../templates/attendee-scheduled-email.ts | 2 +- .../templates/organizer-cancelled-email.ts | 2 +- .../templates/organizer-reassigned-email.ts | 2 +- .../templates/organizer-request-email.ts | 17 +- .../templates/organizer-rescheduled-email.ts | 13 +- .../templates/organizer-scheduled-email.ts | 2 +- .../bookings/lib/handleConfirmation.ts | 19 +- .../bookings/lib/handleNewRecurringBooking.ts | 2 +- .../roundRobinManualReassignment.ts | 40 +- .../ee/round-robin/roundRobinReassignment.ts | 58 +- packages/platform/libraries/index.ts | 12 + packages/prisma/zod-utils.ts | 1 + .../viewer/bookings/confirm.handler.ts | 7 +- yarn.lock | 10 +- 34 files changed, 2544 insertions(+), 358 deletions(-) delete mode 100644 apps/api/v2/src/ee/bookings/2024-08-13/controllers/api-key-bookings.controller.e2e-spec.ts create mode 100644 apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/api-key-bookings.e2e-spec.ts rename apps/api/v2/src/ee/bookings/2024-08-13/controllers/{ => e2e}/confirm-bookings.e2e-spec.ts (92%) create mode 100644 apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/confirm-emails.e2e-spec.ts create mode 100644 apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/team-emails.e2e-spec.ts create mode 100644 apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/user-emails.e2e-spec.ts rename apps/api/v2/src/ee/bookings/2024-08-13/controllers/{ => e2e}/reassign-bookings.e2e-spec.ts (94%) rename apps/api/v2/src/ee/bookings/2024-08-13/controllers/{ => e2e}/recurring-bookings.e2e-spec.ts (98%) rename apps/api/v2/src/ee/bookings/2024-08-13/controllers/{ => e2e}/seated-bookings.e2e-spec.ts (99%) rename apps/api/v2/src/ee/bookings/2024-08-13/controllers/{team-bookings.controller.e2e-spec.ts => e2e/team-bookings.e2e-spec.ts} (97%) rename apps/api/v2/src/ee/bookings/2024-08-13/controllers/{user-bookings.controller.e2e-spec.ts => e2e/user-bookings.e2e-spec.ts} (99%) rename apps/api/v2/src/ee/bookings/2024-08-13/controllers/{variable-length-bookings.controller.e2e-spec.ts => e2e/variable-length-bookings.e2e-spec.ts} (96%) diff --git a/apps/api/v2/package.json b/apps/api/v2/package.json index 182160e4cc..335d09ee1f 100644 --- a/apps/api/v2/package.json +++ b/apps/api/v2/package.json @@ -29,7 +29,7 @@ "@axiomhq/winston": "^1.2.0", "@calcom/platform-constants": "*", "@calcom/platform-enums": "*", - "@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.62", + "@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.63", "@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2", "@calcom/platform-types": "*", "@calcom/platform-utils": "*", diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/api-key-bookings.controller.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/api-key-bookings.controller.e2e-spec.ts deleted file mode 100644 index f28af04e4e..0000000000 --- a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/api-key-bookings.controller.e2e-spec.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { bootstrap } from "@/app"; -import { AppModule } from "@/app.module"; -import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output"; -import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; -import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; -import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service"; -import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard"; -import { PrismaModule } from "@/modules/prisma/prisma.module"; -import { UsersModule } from "@/modules/users/users.module"; -import { INestApplication } from "@nestjs/common"; -import { NestExpressApplication } from "@nestjs/platform-express"; -import { Test } from "@nestjs/testing"; -import { User } from "@prisma/client"; -import * as request from "supertest"; -import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture"; -import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture"; -import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture"; -import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture"; -import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture"; -import { withApiAuth } from "test/utils/withApiAuth"; - -import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; -import { CreateBookingInput_2024_08_13, BookingOutput_2024_08_13 } from "@calcom/platform-types"; -import { Team } from "@calcom/prisma/client"; - -describe("Bookings Endpoints 2024-08-13", () => { - describe("With api key", () => { - let app: INestApplication; - let organization: Team; - - let userRepositoryFixture: UserRepositoryFixture; - let bookingsRepositoryFixture: BookingsRepositoryFixture; - let schedulesService: SchedulesService_2024_04_15; - let eventTypesRepositoryFixture: EventTypesRepositoryFixture; - let teamRepositoryFixture: TeamRepositoryFixture; - let apiKeysRepositoryFixture: ApiKeysRepositoryFixture; - let apiKeyString: string; - - const userEmail = "bookings-controller-e2e@api.com"; - let user: User; - - let eventTypeId: number; - - beforeAll(async () => { - const moduleRef = await withApiAuth( - userEmail, - Test.createTestingModule({ - imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15], - }) - ) - .overrideGuard(PermissionsGuard) - .useValue({ - canActivate: () => true, - }) - .compile(); - - userRepositoryFixture = new UserRepositoryFixture(moduleRef); - bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef); - eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef); - teamRepositoryFixture = new TeamRepositoryFixture(moduleRef); - schedulesService = moduleRef.get(SchedulesService_2024_04_15); - apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef); - - organization = await teamRepositoryFixture.create({ name: "organization bookings" }); - - user = await userRepositoryFixture.create({ - email: userEmail, - }); - - const { keyString } = await apiKeysRepositoryFixture.createApiKey(user.id, null); - apiKeyString = keyString; - - const userSchedule: CreateScheduleInput_2024_04_15 = { - name: "working time", - timeZone: "Europe/Rome", - isDefault: true, - }; - await schedulesService.createUserSchedule(user.id, userSchedule); - const event = await eventTypesRepositoryFixture.create( - { title: "peer coding", slug: "peer-coding", length: 60 }, - user.id - ); - eventTypeId = event.id; - - app = moduleRef.createNestApplication(); - bootstrap(app as NestExpressApplication); - - await app.init(); - }); - - it("should be defined", () => { - expect(userRepositoryFixture).toBeDefined(); - expect(user).toBeDefined(); - }); - - describe("create bookings", () => { - it("should create a booking with api key", async () => { - const body: CreateBookingInput_2024_08_13 = { - start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(), - eventTypeId, - attendee: { - name: "Mr Key", - email: "mr_key@gmail.com", - timeZone: "Europe/Rome", - language: "it", - }, - meetingUrl: "https://meet.google.com/abc-def-ghi", - }; - - return request(app.getHttpServer()) - .post("/v2/bookings") - .send(body) - .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) - .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) - .expect(201) - .then(async (response) => { - const responseBody: CreateBookingOutput_2024_08_13 = response.body; - expect(responseBody.status).toEqual(SUCCESS_STATUS); - expect(responseBody.data).toBeDefined(); - expect(responseDataIsBooking(responseBody.data)).toBe(true); - - if (responseDataIsBooking(responseBody.data)) { - const data: BookingOutput_2024_08_13 = responseBody.data; - expect(data.id).toBeDefined(); - expect(data.uid).toBeDefined(); - expect(data.hosts[0].id).toEqual(user.id); - expect(data.status).toEqual("accepted"); - expect(data.start).toEqual(body.start); - expect(data.end).toEqual(new Date(Date.UTC(2030, 0, 8, 14, 0, 0)).toISOString()); - expect(data.duration).toEqual(60); - expect(data.eventTypeId).toEqual(eventTypeId); - expect(data.attendees[0]).toEqual({ - name: body.attendee.name, - timeZone: body.attendee.timeZone, - language: body.attendee.language, - absent: false, - }); - expect(data.meetingUrl).toEqual(body.meetingUrl); - expect(data.absentHost).toEqual(false); - } else { - throw new Error( - "Invalid response data - expected booking but received array of possibily recurring bookings" - ); - } - }); - }); - }); - - function responseDataIsBooking(data: any): data is BookingOutput_2024_08_13 { - return !Array.isArray(data) && typeof data === "object" && data && "id" in data; - } - - afterAll(async () => { - await teamRepositoryFixture.delete(organization.id); - await userRepositoryFixture.deleteByEmail(user.email); - await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email); - await app.close(); - }); - }); -}); diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/api-key-bookings.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/api-key-bookings.e2e-spec.ts new file mode 100644 index 0000000000..47d2de1abc --- /dev/null +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/api-key-bookings.e2e-spec.ts @@ -0,0 +1,291 @@ +import { bootstrap } from "@/app"; +import { AppModule } from "@/app.module"; +import { CancelBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/cancel-booking.output"; +import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output"; +import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output"; +import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; +import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; +import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service"; +import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard"; +import { PrismaModule } from "@/modules/prisma/prisma.module"; +import { UsersModule } from "@/modules/users/users.module"; +import { INestApplication } from "@nestjs/common"; +import { NestExpressApplication } from "@nestjs/platform-express"; +import { Test } from "@nestjs/testing"; +import { User } from "@prisma/client"; +import * as request from "supertest"; +import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture"; +import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture"; +import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture"; +import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture"; +import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture"; +import { withApiAuth } from "test/utils/withApiAuth"; + +import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; +import { + AttendeeScheduledEmail, + OrganizerScheduledEmail, + AttendeeRescheduledEmail, + OrganizerRescheduledEmail, + AttendeeCancelledEmail, + OrganizerCancelledEmail, +} from "@calcom/platform-libraries"; +import { + CreateBookingInput_2024_08_13, + BookingOutput_2024_08_13, + RescheduleBookingInput_2024_08_13, + CancelBookingInput_2024_08_13, +} from "@calcom/platform-types"; +import { Team } from "@calcom/prisma/client"; + +jest.spyOn(AttendeeScheduledEmail.prototype as any, "getHtml").mockImplementation(async function () { + return "Mocked Email Content"; +}); + +jest.spyOn(OrganizerScheduledEmail.prototype as any, "getHtml").mockImplementation(async function () { + return "Mocked Email Content"; +}); + +jest + .spyOn(AttendeeRescheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerRescheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeCancelledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerCancelledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); + +describe("Bookings Endpoints 2024-08-13", () => { + describe("With api key", () => { + let app: INestApplication; + let organization: Team; + + let userRepositoryFixture: UserRepositoryFixture; + let bookingsRepositoryFixture: BookingsRepositoryFixture; + let schedulesService: SchedulesService_2024_04_15; + let eventTypesRepositoryFixture: EventTypesRepositoryFixture; + let teamRepositoryFixture: TeamRepositoryFixture; + let apiKeysRepositoryFixture: ApiKeysRepositoryFixture; + let apiKeyString: string; + + const userEmail = "bookings-controller-e2e@api.com"; + let user: User; + + let eventTypeId: number; + + let createdBooking: BookingOutput_2024_08_13; + let rescheduledBooking: BookingOutput_2024_08_13; + + beforeAll(async () => { + const moduleRef = await withApiAuth( + userEmail, + Test.createTestingModule({ + imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15], + }) + ) + .overrideGuard(PermissionsGuard) + .useValue({ + canActivate: () => true, + }) + .compile(); + + userRepositoryFixture = new UserRepositoryFixture(moduleRef); + bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef); + eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef); + teamRepositoryFixture = new TeamRepositoryFixture(moduleRef); + schedulesService = moduleRef.get(SchedulesService_2024_04_15); + apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef); + + organization = await teamRepositoryFixture.create({ name: "organization bookings" }); + + user = await userRepositoryFixture.create({ + email: userEmail, + }); + + const { keyString } = await apiKeysRepositoryFixture.createApiKey(user.id, null); + apiKeyString = keyString; + + const userSchedule: CreateScheduleInput_2024_04_15 = { + name: "working time", + timeZone: "Europe/Rome", + isDefault: true, + }; + await schedulesService.createUserSchedule(user.id, userSchedule); + const event = await eventTypesRepositoryFixture.create( + { title: "peer coding", slug: "peer-coding", length: 60 }, + user.id + ); + eventTypeId = event.id; + + app = moduleRef.createNestApplication(); + bootstrap(app as NestExpressApplication); + + await app.init(); + }); + + it("should be defined", () => { + expect(userRepositoryFixture).toBeDefined(); + expect(user).toBeDefined(); + }); + + it("should create a booking with api key", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(), + eventTypeId, + attendee: { + name: "Mr Key", + email: "mr_key@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + meetingUrl: "https://meet.google.com/abc-def-ghi", + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(responseDataIsBooking(responseBody.data)).toBe(true); + + if (responseDataIsBooking(responseBody.data)) { + const data: BookingOutput_2024_08_13 = responseBody.data; + expect(data.id).toBeDefined(); + expect(data.uid).toBeDefined(); + expect(data.hosts[0].id).toEqual(user.id); + expect(data.status).toEqual("accepted"); + expect(data.start).toEqual(body.start); + expect(data.end).toEqual(new Date(Date.UTC(2030, 0, 8, 14, 0, 0)).toISOString()); + expect(data.duration).toEqual(60); + expect(data.eventTypeId).toEqual(eventTypeId); + expect(data.attendees[0]).toEqual({ + name: body.attendee.name, + timeZone: body.attendee.timeZone, + language: body.attendee.language, + absent: false, + }); + expect(data.meetingUrl).toEqual(body.meetingUrl); + expect(data.absentHost).toEqual(false); + expect(AttendeeScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + createdBooking = data; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should reschedule a booking with api key", async () => { + const body: RescheduleBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2035, 0, 8, 14, 0, 0)).toISOString(), + reschedulingReason: "Flying to mars that day", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${createdBooking.uid}/reschedule`) + .send(body) + .set({ Authorization: `Bearer cal_test_${apiKeyString}` }) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: RescheduleBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(responseDataIsBooking(responseBody.data)).toBe(true); + + if (responseDataIsBooking(responseBody.data)) { + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const data: BookingOutput_2024_08_13 = responseBody.data; + expect(data.reschedulingReason).toEqual(body.reschedulingReason); + expect(data.start).toEqual(body.start); + expect(data.end).toEqual(new Date(Date.UTC(2035, 0, 8, 15, 0, 0)).toISOString()); + expect(data.rescheduledFromUid).toEqual(createdBooking.uid); + expect(data.id).toBeDefined(); + expect(data.uid).toBeDefined(); + expect(data.hosts[0].id).toEqual(user.id); + expect(data.status).toEqual(createdBooking.status); + expect(data.duration).toEqual(createdBooking.duration); + expect(data.eventTypeId).toEqual(createdBooking.eventTypeId); + expect(data.attendees[0]).toEqual(createdBooking.attendees[0]); + expect(data.location).toEqual(createdBooking.location); + expect(data.absentHost).toEqual(createdBooking.absentHost); + expect(data.metadata).toEqual(createdBooking.metadata); + expect(AttendeeRescheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerRescheduledEmail.prototype.getHtml).toHaveBeenCalled(); + rescheduledBooking = data; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should cancel booking", async () => { + const body: CancelBookingInput_2024_08_13 = { + cancellationReason: "Going on a vacation", + }; + + const booking = await bookingsRepositoryFixture.getByUid(rescheduledBooking.uid); + expect(booking).toBeDefined(); + expect(booking?.status).toEqual("ACCEPTED"); + + return request(app.getHttpServer()) + .post(`/v2/bookings/${rescheduledBooking.uid}/cancel`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const data: BookingOutput_2024_08_13 = responseBody.data; + expect(data.id).toBeDefined(); + expect(data.uid).toBeDefined(); + expect(data.hosts[0].id).toEqual(user.id); + expect(data.status).toEqual("cancelled"); + expect(data.cancellationReason).toEqual(body.cancellationReason); + expect(data.start).toEqual(rescheduledBooking.start); + expect(data.end).toEqual(rescheduledBooking.end); + expect(data.duration).toEqual(rescheduledBooking.duration); + expect(data.eventTypeId).toEqual(rescheduledBooking.eventTypeId); + expect(data.attendees[0]).toEqual(rescheduledBooking.attendees[0]); + expect(data.location).toEqual(rescheduledBooking.location); + expect(data.absentHost).toEqual(rescheduledBooking.absentHost); + + const cancelledBooking = await bookingsRepositoryFixture.getByUid(rescheduledBooking.uid); + expect(cancelledBooking).toBeDefined(); + expect(cancelledBooking?.status).toEqual("CANCELLED"); + expect(AttendeeCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + }); + }); + + function responseDataIsBooking(data: any): data is BookingOutput_2024_08_13 { + return !Array.isArray(data) && typeof data === "object" && data && "id" in data; + } + + afterAll(async () => { + await teamRepositoryFixture.delete(organization.id); + await userRepositoryFixture.deleteByEmail(user.email); + await bookingsRepositoryFixture.deleteAllBookings(user.id, user.email); + await app.close(); + }); + }); +}); diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/confirm-bookings.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/confirm-bookings.e2e-spec.ts similarity index 92% rename from apps/api/v2/src/ee/bookings/2024-08-13/controllers/confirm-bookings.e2e-spec.ts rename to apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/confirm-bookings.e2e-spec.ts index f9863161e8..84c2ae15cb 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/confirm-bookings.e2e-spec.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/confirm-bookings.e2e-spec.ts @@ -1,6 +1,5 @@ import { bootstrap } from "@/app"; import { AppModule } from "@/app.module"; -import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output"; import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service"; @@ -20,26 +19,9 @@ import { UserRepositoryFixture } from "test/fixtures/repository/users.repository import { withApiAuth } from "test/utils/withApiAuth"; import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; -import { - AttendeeScheduledEmail, - OrganizerScheduledEmail, - AttendeeDeclinedEmail, -} from "@calcom/platform-libraries"; import { BookingOutput_2024_08_13, GetBookingOutput_2024_08_13 } from "@calcom/platform-types"; import { Booking, PlatformOAuthClient, Team } from "@calcom/prisma/client"; -jest.spyOn(AttendeeScheduledEmail.prototype as any, "getHtml").mockImplementation(async function () { - return "Mocked Email Content"; -}); - -jest.spyOn(OrganizerScheduledEmail.prototype as any, "getHtml").mockImplementation(async function () { - return "Mocked Email Content"; -}); - -jest.spyOn(AttendeeDeclinedEmail.prototype as any, "getHtml").mockImplementation(async function () { - return "Mocked Email Content"; -}); - describe("Bookings Endpoints 2024-08-13", () => { describe("Bookings confirmation", () => { let app: INestApplication; @@ -87,6 +69,11 @@ describe("Bookings Endpoints 2024-08-13", () => { user = await userRepositoryFixture.create({ email: userEmail, + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/confirm-emails.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/confirm-emails.e2e-spec.ts new file mode 100644 index 0000000000..9ef524f1a5 --- /dev/null +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/confirm-emails.e2e-spec.ts @@ -0,0 +1,474 @@ +import { bootstrap } from "@/app"; +import { AppModule } from "@/app.module"; +import { CancelBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/cancel-booking.output"; +import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output"; +import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output"; +import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; +import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; +import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service"; +import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard"; +import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard"; +import { PrismaModule } from "@/modules/prisma/prisma.module"; +import { UsersModule } from "@/modules/users/users.module"; +import { INestApplication } from "@nestjs/common"; +import { NestExpressApplication } from "@nestjs/platform-express"; +import { Test } from "@nestjs/testing"; +import { User } from "@prisma/client"; +import * as request from "supertest"; +import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture"; +import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture"; +import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture"; +import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture"; +import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture"; +import { withApiAuth } from "test/utils/withApiAuth"; + +import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; +import { + OrganizerScheduledEmail, + AttendeeScheduledEmail, + OrganizerRescheduledEmail, + AttendeeRescheduledEmail, + OrganizerCancelledEmail, + AttendeeCancelledEmail, + AttendeeRequestEmail, + OrganizerRequestEmail, + AttendeeDeclinedEmail, +} from "@calcom/platform-libraries"; +import { + CreateBookingInput_2024_08_13, + BookingOutput_2024_08_13, + RescheduleBookingInput_2024_08_13, + GetBookingOutput_2024_08_13, +} from "@calcom/platform-types"; +import { CancelBookingInput_2024_08_13 } from "@calcom/platform-types"; +import { Team } from "@calcom/prisma/client"; + +jest + .spyOn(AttendeeScheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerScheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeRescheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerRescheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeCancelledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerCancelledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeRequestEmail.prototype, "getHtmlRequestEmail") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerRequestEmail.prototype, "getHtmlRequestEmail") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeDeclinedEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); + +type EmailSetup = { + user: User; + eventTypeId: number; + createdBookingUid: string; + rescheduledBookingUid: string; +}; + +describe("Bookings Endpoints 2024-08-13 confirm emails", () => { + let app: INestApplication; + let organization: Team; + + let userRepositoryFixture: UserRepositoryFixture; + let bookingsRepositoryFixture: BookingsRepositoryFixture; + let schedulesService: SchedulesService_2024_04_15; + let eventTypesRepositoryFixture: EventTypesRepositoryFixture; + let oauthClientRepositoryFixture: OAuthClientRepositoryFixture; + let teamRepositoryFixture: TeamRepositoryFixture; + + let emailsEnabledSetup: EmailSetup; + let emailsDisabledSetup: EmailSetup; + + const authEmail = `admin-${Math.floor(Math.random() * 1000)}@example.com`; + + beforeAll(async () => { + const moduleRef = await withApiAuth( + authEmail, + Test.createTestingModule({ + imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15], + }) + ) + .overrideGuard(PermissionsGuard) + .useValue({ + canActivate: () => true, + }) + .compile(); + + userRepositoryFixture = new UserRepositoryFixture(moduleRef); + bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef); + eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef); + oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef); + teamRepositoryFixture = new TeamRepositoryFixture(moduleRef); + schedulesService = moduleRef.get(SchedulesService_2024_04_15); + + organization = await teamRepositoryFixture.create({ name: "organization bookings" }); + + await setupEnabledEmails(); + await setupDisabledEmails(); + + await userRepositoryFixture.create({ + email: authEmail, + organization: { + connect: { + id: organization.id, + }, + }, + role: "ADMIN", + }); + + app = moduleRef.createNestApplication(); + bootstrap(app as NestExpressApplication); + + await app.init(); + }); + + async function setupEnabledEmails() { + const oAuthClientEmailsEnabled = await createOAuthClient(organization.id, true); + + const user = await userRepositoryFixture.create({ + email: `alice-${Math.floor(Math.random() * 1000)}@gmail.com`, + platformOAuthClients: { + connect: { + id: oAuthClientEmailsEnabled.id, + }, + }, + }); + + const userSchedule: CreateScheduleInput_2024_04_15 = { + name: "working time", + timeZone: "Europe/Rome", + isDefault: true, + }; + await schedulesService.createUserSchedule(user.id, userSchedule); + + const event = await eventTypesRepositoryFixture.create( + { title: "peer coding", slug: "peer-coding", length: 60, requiresConfirmation: true }, + user.id + ); + + emailsEnabledSetup = { + user, + eventTypeId: event.id, + createdBookingUid: "", + rescheduledBookingUid: "", + }; + } + + async function setupDisabledEmails() { + const oAuthClientEmailsDisabled = await createOAuthClient(organization.id, false); + + const user = await userRepositoryFixture.create({ + email: `bob-${Math.floor(Math.random() * 1000)}@gmail.com`, + platformOAuthClients: { + connect: { + id: oAuthClientEmailsDisabled.id, + }, + }, + }); + const userSchedule: CreateScheduleInput_2024_04_15 = { + name: "working time", + timeZone: "Europe/Rome", + isDefault: true, + }; + await schedulesService.createUserSchedule(user.id, userSchedule); + const event = await eventTypesRepositoryFixture.create( + { title: "peer coding", slug: "peer-coding", length: 60, requiresConfirmation: true }, + user.id + ); + + emailsDisabledSetup = { + user, + eventTypeId: event.id, + createdBookingUid: "", + rescheduledBookingUid: "", + }; + } + + async function createOAuthClient(organizationId: number, emailsEnabled: boolean) { + const data = { + logo: "logo-url", + name: "name", + redirectUris: ["http://localhost:5555"], + permissions: 32, + areEmailsEnabled: emailsEnabled, + }; + const secret = "secret"; + + const client = await oauthClientRepositoryFixture.create(organizationId, data, secret); + return client; + } + + describe("OAuth client managed user bookings - emails disabled", () => { + beforeEach(async () => { + jest.clearAllMocks(); + }); + + it("should not send an email when creating a booking that requires confirmation", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(), + eventTypeId: emailsDisabledSetup.eventTypeId, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(responseBody.data.status).toEqual("pending"); + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(AttendeeRequestEmail.prototype.getHtmlRequestEmail).not.toHaveBeenCalled(); + expect(OrganizerRequestEmail.prototype.getHtmlRequestEmail).not.toHaveBeenCalled(); + emailsDisabledSetup.createdBookingUid = responseBody.data.uid; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should not send an email when confirming a booking", async () => { + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.createdBookingUid}/confirm`) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: GetBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + emailsDisabledSetup.rescheduledBookingUid = responseBody.data.uid; + }); + }); + + it("should not send an email when creating a booking that requires confirmation", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 10, 0, 0)).toISOString(), + eventTypeId: emailsDisabledSetup.eventTypeId, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(responseBody.data.status).toEqual("pending"); + expect(AttendeeRequestEmail.prototype.getHtmlRequestEmail).not.toHaveBeenCalled(); + expect(OrganizerRequestEmail.prototype.getHtmlRequestEmail).not.toHaveBeenCalled(); + emailsDisabledSetup.createdBookingUid = responseBody.data.uid; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should not send an email when declining a booking", async () => { + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.createdBookingUid}/decline`) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: GetBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeDeclinedEmail.prototype.getHtml).not.toHaveBeenCalled(); + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + emailsDisabledSetup.rescheduledBookingUid = responseBody.data.uid; + }); + }); + }); + + describe("OAuth client managed user bookings - emails enabled", () => { + beforeEach(async () => { + jest.clearAllMocks(); + }); + + it("should send an email when creating a booking that requires confirmation", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(), + eventTypeId: emailsEnabledSetup.eventTypeId, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(responseBody.data.status).toEqual("pending"); + expect(AttendeeRequestEmail.prototype.getHtmlRequestEmail).toHaveBeenCalled(); + expect(OrganizerRequestEmail.prototype.getHtmlRequestEmail).toHaveBeenCalled(); + emailsEnabledSetup.createdBookingUid = responseBody.data.uid; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should send an email when confirming a booking", async () => { + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.createdBookingUid}/confirm`) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: GetBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + emailsEnabledSetup.rescheduledBookingUid = responseBody.data.uid; + }); + }); + + it("should send an email when creating a booking that requires confirmation", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 10, 0, 0)).toISOString(), + eventTypeId: emailsEnabledSetup.eventTypeId, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(responseBody.data.status).toEqual("pending"); + expect(AttendeeRequestEmail.prototype.getHtmlRequestEmail).toHaveBeenCalled(); + expect(OrganizerRequestEmail.prototype.getHtmlRequestEmail).toHaveBeenCalled(); + emailsEnabledSetup.createdBookingUid = responseBody.data.uid; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should send an email when declining a booking", async () => { + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.createdBookingUid}/decline`) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: GetBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeDeclinedEmail.prototype.getHtml).toHaveBeenCalled(); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + emailsEnabledSetup.rescheduledBookingUid = responseBody.data.uid; + }); + }); + }); + + afterAll(async () => { + await teamRepositoryFixture.delete(organization.id); + await userRepositoryFixture.deleteByEmail(emailsEnabledSetup.user.email); + await userRepositoryFixture.deleteByEmail(emailsDisabledSetup.user.email); + await userRepositoryFixture.deleteByEmail(authEmail); + await bookingsRepositoryFixture.deleteAllBookings( + emailsEnabledSetup.user.id, + emailsEnabledSetup.user.email + ); + await bookingsRepositoryFixture.deleteAllBookings( + emailsDisabledSetup.user.id, + emailsDisabledSetup.user.email + ); + await app.close(); + }); + + function responseDataIsBooking(data: any): data is BookingOutput_2024_08_13 { + return !Array.isArray(data) && typeof data === "object" && data && "id" in data; + } +}); diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/team-emails.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/team-emails.e2e-spec.ts new file mode 100644 index 0000000000..bdf2782b9a --- /dev/null +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/team-emails.e2e-spec.ts @@ -0,0 +1,979 @@ +import { bootstrap } from "@/app"; +import { AppModule } from "@/app.module"; +import { CancelBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/cancel-booking.output"; +import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output"; +import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output"; +import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; +import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; +import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service"; +import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard"; +import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard"; +import { PrismaModule } from "@/modules/prisma/prisma.module"; +import { UsersModule } from "@/modules/users/users.module"; +import { createParamDecorator, INestApplication } from "@nestjs/common"; +import { NestExpressApplication } from "@nestjs/platform-express"; +import { Test } from "@nestjs/testing"; +import { User } from "@prisma/client"; +import * as request from "supertest"; +import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture"; +import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture"; +import { HostsRepositoryFixture } from "test/fixtures/repository/hosts.repository.fixture"; +import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture"; +import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture"; +import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture"; +import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture"; +import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture"; +import { withApiAuth } from "test/utils/withApiAuth"; + +import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; +import { + OrganizerScheduledEmail, + AttendeeScheduledEmail, + OrganizerRescheduledEmail, + AttendeeRescheduledEmail, + OrganizerCancelledEmail, + AttendeeCancelledEmail, + OrganizerReassignedEmail, +} from "@calcom/platform-libraries"; +import { + CreateBookingInput_2024_08_13, + BookingOutput_2024_08_13, + RescheduleBookingInput_2024_08_13, +} from "@calcom/platform-types"; +import { CancelBookingInput_2024_08_13 } from "@calcom/platform-types"; +import { Team } from "@calcom/prisma/client"; + +jest + .spyOn(AttendeeScheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerScheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeRescheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerRescheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeCancelledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerCancelledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); + +jest + .spyOn(OrganizerReassignedEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); + +type EmailSetup = { + team: Team; + member1: User; + member2: User; + collectiveEventType: { + id: number; + createdBookingUid: string; + rescheduledBookingUid: string; + }; + roundRobinEventType: { + id: number; + createdBookingUid: string; + rescheduledBookingUid: string; + currentHostId: number; + }; +}; + +describe("Bookings Endpoints 2024-08-13 team emails", () => { + let app: INestApplication; + let organization: Team; + + let userRepositoryFixture: UserRepositoryFixture; + let bookingsRepositoryFixture: BookingsRepositoryFixture; + let schedulesService: SchedulesService_2024_04_15; + let eventTypesRepositoryFixture: EventTypesRepositoryFixture; + let oauthClientRepositoryFixture: OAuthClientRepositoryFixture; + let teamRepositoryFixture: TeamRepositoryFixture; + let profileRepositoryFixture: ProfileRepositoryFixture; + let membershipsRepositoryFixture: MembershipRepositoryFixture; + let hostsRepositoryFixture: HostsRepositoryFixture; + + let emailsEnabledSetup: EmailSetup; + let emailsDisabledSetup: EmailSetup; + + const authEmail = "admin@example.com"; + + beforeAll(async () => { + const moduleRef = await withApiAuth( + authEmail, + Test.createTestingModule({ + imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15], + }) + ) + .overrideGuard(PermissionsGuard) + .useValue({ + canActivate: () => true, + }) + .compile(); + + userRepositoryFixture = new UserRepositoryFixture(moduleRef); + bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef); + eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef); + oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef); + teamRepositoryFixture = new TeamRepositoryFixture(moduleRef); + profileRepositoryFixture = new ProfileRepositoryFixture(moduleRef); + membershipsRepositoryFixture = new MembershipRepositoryFixture(moduleRef); + hostsRepositoryFixture = new HostsRepositoryFixture(moduleRef); + schedulesService = moduleRef.get(SchedulesService_2024_04_15); + + organization = await teamRepositoryFixture.create({ name: "organization bookings" }); + + await setupEnabledEmails(); + await setupDisabledEmails(); + + await userRepositoryFixture.create({ + email: authEmail, + organization: { + connect: { + id: organization.id, + }, + }, + }); + + app = moduleRef.createNestApplication(); + bootstrap(app as NestExpressApplication); + + await app.init(); + }); + + async function setupEnabledEmails() { + const oAuthClientEmailsEnabled = await createOAuthClient(organization.id, true); + + const team = await teamRepositoryFixture.create({ + name: "team 1", + isOrganization: false, + parent: { connect: { id: organization.id } }, + createdByOAuthClient: { + connect: { + id: oAuthClientEmailsEnabled.id, + }, + }, + }); + + const member1 = await userRepositoryFixture.create({ + email: "alice@gmail.com", + platformOAuthClients: { + connect: { + id: oAuthClientEmailsEnabled.id, + }, + }, + }); + + const member2 = await userRepositoryFixture.create({ + email: "bob@gmail.com", + platformOAuthClients: { + connect: { + id: oAuthClientEmailsEnabled.id, + }, + }, + }); + + const userSchedule: CreateScheduleInput_2024_04_15 = { + name: "working time", + timeZone: "Europe/Rome", + isDefault: true, + }; + await schedulesService.createUserSchedule(member1.id, userSchedule); + await schedulesService.createUserSchedule(member2.id, userSchedule); + + await profileRepositoryFixture.create({ + uid: `usr-${member1.id}`, + username: member1.email, + organization: { + connect: { + id: organization.id, + }, + }, + user: { + connect: { + id: member1.id, + }, + }, + }); + + await profileRepositoryFixture.create({ + uid: `usr-${member2.id}`, + username: member2.email, + organization: { + connect: { + id: organization.id, + }, + }, + user: { + connect: { + id: member2.id, + }, + }, + }); + + await membershipsRepositoryFixture.create({ + role: "MEMBER", + user: { connect: { id: member1.id } }, + team: { connect: { id: team.id } }, + accepted: true, + }); + + await membershipsRepositoryFixture.create({ + role: "MEMBER", + user: { connect: { id: member2.id } }, + team: { connect: { id: team.id } }, + accepted: true, + }); + + const collectiveEvent = await eventTypesRepositoryFixture.createTeamEventType({ + schedulingType: "COLLECTIVE", + team: { + connect: { id: team.id }, + }, + title: "Collective Event Type", + slug: "collective-event-type", + length: 60, + assignAllTeamMembers: true, + bookingFields: [], + locations: [], + }); + + await hostsRepositoryFixture.create({ + isFixed: true, + user: { + connect: { + id: member1.id, + }, + }, + eventType: { + connect: { + id: collectiveEvent.id, + }, + }, + }); + + await hostsRepositoryFixture.create({ + isFixed: true, + user: { + connect: { + id: member2.id, + }, + }, + eventType: { + connect: { + id: collectiveEvent.id, + }, + }, + }); + + const roundRobinEvent = await eventTypesRepositoryFixture.createTeamEventType({ + schedulingType: "ROUND_ROBIN", + team: { + connect: { id: team.id }, + }, + title: "Round Robin Event Type", + slug: "round-robin-event-type", + length: 60, + assignAllTeamMembers: false, + bookingFields: [], + locations: [], + }); + + await hostsRepositoryFixture.create({ + isFixed: false, + user: { + connect: { + id: member1.id, + }, + }, + eventType: { + connect: { + id: roundRobinEvent.id, + }, + }, + }); + + await hostsRepositoryFixture.create({ + isFixed: false, + user: { + connect: { + id: member2.id, + }, + }, + eventType: { + connect: { + id: roundRobinEvent.id, + }, + }, + }); + + emailsEnabledSetup = { + team, + member1: member1, + member2: member2, + collectiveEventType: { + id: collectiveEvent.id, + createdBookingUid: "", + rescheduledBookingUid: "", + }, + roundRobinEventType: { + id: roundRobinEvent.id, + createdBookingUid: "", + rescheduledBookingUid: "", + currentHostId: 0, + }, + }; + } + + async function setupDisabledEmails() { + const oAuthClientEmailsDisabled = await createOAuthClient(organization.id, false); + + const team = await teamRepositoryFixture.create({ + name: "team 2", + isOrganization: false, + parent: { connect: { id: organization.id } }, + createdByOAuthClient: { + connect: { + id: oAuthClientEmailsDisabled.id, + }, + }, + }); + + const member1 = await userRepositoryFixture.create({ + email: "charlie@gmail.com", + platformOAuthClients: { + connect: { + id: oAuthClientEmailsDisabled.id, + }, + }, + }); + + const member2 = await userRepositoryFixture.create({ + email: "dean@gmail.com", + platformOAuthClients: { + connect: { + id: oAuthClientEmailsDisabled.id, + }, + }, + }); + + const userSchedule: CreateScheduleInput_2024_04_15 = { + name: "working time", + timeZone: "Europe/Rome", + isDefault: true, + }; + await schedulesService.createUserSchedule(member1.id, userSchedule); + await schedulesService.createUserSchedule(member2.id, userSchedule); + + await profileRepositoryFixture.create({ + uid: `usr-${member1.id}`, + username: member1.email, + organization: { + connect: { + id: organization.id, + }, + }, + user: { + connect: { + id: member1.id, + }, + }, + }); + + await profileRepositoryFixture.create({ + uid: `usr-${member2.id}`, + username: member2.email, + organization: { + connect: { + id: organization.id, + }, + }, + user: { + connect: { + id: member2.id, + }, + }, + }); + + await membershipsRepositoryFixture.create({ + role: "MEMBER", + user: { connect: { id: member1.id } }, + team: { connect: { id: team.id } }, + accepted: true, + }); + + await membershipsRepositoryFixture.create({ + role: "MEMBER", + user: { connect: { id: member2.id } }, + team: { connect: { id: team.id } }, + accepted: true, + }); + + const collectiveEvent = await eventTypesRepositoryFixture.createTeamEventType({ + schedulingType: "COLLECTIVE", + team: { + connect: { id: team.id }, + }, + title: "Collective Event Type", + slug: "collective-event-type", + length: 60, + assignAllTeamMembers: true, + bookingFields: [], + locations: [], + }); + + await hostsRepositoryFixture.create({ + isFixed: true, + user: { + connect: { + id: member1.id, + }, + }, + eventType: { + connect: { + id: collectiveEvent.id, + }, + }, + }); + + await hostsRepositoryFixture.create({ + isFixed: true, + user: { + connect: { + id: member2.id, + }, + }, + eventType: { + connect: { + id: collectiveEvent.id, + }, + }, + }); + + const roundRobinEvent = await eventTypesRepositoryFixture.createTeamEventType({ + schedulingType: "ROUND_ROBIN", + team: { + connect: { id: team.id }, + }, + title: "Round Robin Event Type", + slug: "round-robin-event-type", + length: 60, + assignAllTeamMembers: false, + bookingFields: [], + locations: [], + }); + + await hostsRepositoryFixture.create({ + isFixed: false, + user: { + connect: { + id: member1.id, + }, + }, + eventType: { + connect: { + id: roundRobinEvent.id, + }, + }, + }); + + await hostsRepositoryFixture.create({ + isFixed: false, + user: { + connect: { + id: member2.id, + }, + }, + eventType: { + connect: { + id: roundRobinEvent.id, + }, + }, + }); + + emailsDisabledSetup = { + team, + member1: member1, + member2: member2, + collectiveEventType: { + id: collectiveEvent.id, + createdBookingUid: "", + rescheduledBookingUid: "", + }, + roundRobinEventType: { + id: roundRobinEvent.id, + createdBookingUid: "", + rescheduledBookingUid: "", + currentHostId: 0, + }, + }; + } + + async function createOAuthClient(organizationId: number, emailsEnabled: boolean) { + const data = { + logo: "logo-url", + name: "name", + redirectUris: ["http://localhost:5555"], + permissions: 32, + areEmailsEnabled: emailsEnabled, + }; + const secret = "secret"; + + const client = await oauthClientRepositoryFixture.create(organizationId, data, secret); + return client; + } + + beforeEach(async () => { + jest.clearAllMocks(); + }); + + describe("OAuth client team bookings - emails disabled", () => { + describe("book", () => { + it("should not send an email when booking collective event", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 9, 0, 0)).toISOString(), + eventTypeId: emailsDisabledSetup.collectiveEventType.id, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + emailsDisabledSetup.collectiveEventType.createdBookingUid = responseBody.data.uid; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should not send an email when booking round robin event", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 10, 0, 0)).toISOString(), + eventTypeId: emailsDisabledSetup.roundRobinEventType.id, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + emailsDisabledSetup.roundRobinEventType.createdBookingUid = responseBody.data.uid; + emailsDisabledSetup.roundRobinEventType.currentHostId = responseBody.data.hosts[0].id; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + }); + + describe("reschedule", () => { + it("should not send an email when rescheduling collective booking", async () => { + const body: RescheduleBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2035, 0, 8, 11, 0, 0)).toISOString(), + reschedulingReason: "Flying to mars that day", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.collectiveEventType.createdBookingUid}/reschedule`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: RescheduleBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(AttendeeRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + emailsDisabledSetup.collectiveEventType.rescheduledBookingUid = responseBody.data.uid; + }); + }); + + it("should not send an email when rescheduling round robin booking", async () => { + const body: RescheduleBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2035, 0, 8, 12, 0, 0)).toISOString(), + reschedulingReason: "Flying to mars that day", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.roundRobinEventType.createdBookingUid}/reschedule`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: RescheduleBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(AttendeeRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + emailsDisabledSetup.roundRobinEventType.rescheduledBookingUid = responseBody.data.uid; + emailsDisabledSetup.roundRobinEventType.currentHostId = responseBody.data.hosts[0].id; + }); + }); + }); + + describe("reassign", () => { + it("should not send an email when manually reassigning round robin booking", async () => { + const reassignToId = + emailsDisabledSetup.roundRobinEventType.currentHostId === emailsDisabledSetup.member1.id + ? emailsDisabledSetup.member2.id + : emailsDisabledSetup.member1.id; + + return request(app.getHttpServer()) + .post( + `/v2/bookings/${emailsDisabledSetup.roundRobinEventType.rescheduledBookingUid}/reassign/${reassignToId}` + ) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + emailsDisabledSetup.roundRobinEventType.currentHostId = reassignToId; + }); + }); + + it("should not send an email when automatically reassigning round robin booking", async () => { + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.roundRobinEventType.rescheduledBookingUid}/reassign`) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerReassignedEmail.prototype.getHtml).not.toHaveBeenCalled(); + }); + }); + }); + + describe("cancel", () => { + it("should not send an email when cancelling a collective booking", async () => { + const body: CancelBookingInput_2024_08_13 = { + cancellationReason: "Going on a vacation", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.collectiveEventType.rescheduledBookingUid}/cancel`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + }); + }); + }); + + it("should not send an email when cancelling a round robin booking", async () => { + const body: CancelBookingInput_2024_08_13 = { + cancellationReason: "Going on a vacation", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.roundRobinEventType.rescheduledBookingUid}/cancel`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + }); + }); + }); + + describe("OAuth client team bookings - emails enabled", () => { + beforeEach(async () => { + jest.clearAllMocks(); + }); + + describe("book", () => { + it("should send an email when booking collective event", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 9, 0, 0)).toISOString(), + eventTypeId: emailsEnabledSetup.collectiveEventType.id, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(AttendeeScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + emailsEnabledSetup.collectiveEventType.createdBookingUid = responseBody.data.uid; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should send an email when booking round robin event", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 10, 0, 0)).toISOString(), + eventTypeId: emailsEnabledSetup.roundRobinEventType.id, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(AttendeeScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + emailsEnabledSetup.roundRobinEventType.createdBookingUid = responseBody.data.uid; + emailsEnabledSetup.roundRobinEventType.currentHostId = responseBody.data.hosts[0].id; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + }); + + describe("reschedule", () => { + it("should send an email when rescheduling collective booking", async () => { + const body: RescheduleBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2035, 0, 8, 11, 0, 0)).toISOString(), + reschedulingReason: "Flying to mars that day", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.collectiveEventType.createdBookingUid}/reschedule`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: RescheduleBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(AttendeeRescheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerRescheduledEmail.prototype.getHtml).toHaveBeenCalled(); + emailsEnabledSetup.collectiveEventType.rescheduledBookingUid = responseBody.data.uid; + }); + }); + + it("should send an email when rescheduling round robin booking", async () => { + const body: RescheduleBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2035, 0, 8, 12, 0, 0)).toISOString(), + reschedulingReason: "Flying to mars that day", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.roundRobinEventType.createdBookingUid}/reschedule`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: RescheduleBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(AttendeeRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + + expect(OrganizerRescheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + emailsEnabledSetup.roundRobinEventType.rescheduledBookingUid = responseBody.data.uid; + emailsEnabledSetup.roundRobinEventType.currentHostId = responseBody.data.hosts[0].id; + }); + }); + }); + + describe("reassign", () => { + it("should send an email when manually reassigning round robin booking", async () => { + const reassignToId = + emailsEnabledSetup.roundRobinEventType.currentHostId === emailsEnabledSetup.member1.id + ? emailsEnabledSetup.member2.id + : emailsEnabledSetup.member1.id; + + return request(app.getHttpServer()) + .post( + `/v2/bookings/${emailsEnabledSetup.roundRobinEventType.rescheduledBookingUid}/reassign/${reassignToId}` + ) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + emailsDisabledSetup.roundRobinEventType.currentHostId = reassignToId; + }); + }); + + it("should send an email when automatically reassigning round robin booking", async () => { + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.roundRobinEventType.rescheduledBookingUid}/reassign`) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerReassignedEmail.prototype.getHtml).toHaveBeenCalled(); + }); + }); + }); + + describe("cancel", () => { + it("should send an email when cancelling a collective booking", async () => { + const body: CancelBookingInput_2024_08_13 = { + cancellationReason: "Going on a vacation", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.collectiveEventType.rescheduledBookingUid}/cancel`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + }); + }); + + it("should send an email when cancelling round robin booking", async () => { + const body: CancelBookingInput_2024_08_13 = { + cancellationReason: "Going on a vacation", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.roundRobinEventType.rescheduledBookingUid}/cancel`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + }); + }); + }); + }); + afterAll(async () => { + await teamRepositoryFixture.delete(organization.id); + await userRepositoryFixture.deleteByEmail(emailsEnabledSetup.member1.email); + await userRepositoryFixture.deleteByEmail(emailsDisabledSetup.member1.email); + await bookingsRepositoryFixture.deleteAllBookings( + emailsEnabledSetup.member1.id, + emailsEnabledSetup.member1.email + ); + await bookingsRepositoryFixture.deleteAllBookings( + emailsDisabledSetup.member1.id, + emailsDisabledSetup.member1.email + ); + await app.close(); + }); + + function responseDataIsBooking(data: any): data is BookingOutput_2024_08_13 { + return !Array.isArray(data) && typeof data === "object" && data && "id" in data; + } +}); diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/user-emails.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/user-emails.e2e-spec.ts new file mode 100644 index 0000000000..7d115bdf31 --- /dev/null +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/emails/user-emails.e2e-spec.ts @@ -0,0 +1,482 @@ +import { bootstrap } from "@/app"; +import { AppModule } from "@/app.module"; +import { CancelBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/cancel-booking.output"; +import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output"; +import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output"; +import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; +import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; +import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service"; +import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard"; +import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard"; +import { PrismaModule } from "@/modules/prisma/prisma.module"; +import { UsersModule } from "@/modules/users/users.module"; +import { INestApplication } from "@nestjs/common"; +import { NestExpressApplication } from "@nestjs/platform-express"; +import { Test } from "@nestjs/testing"; +import { User } from "@prisma/client"; +import * as request from "supertest"; +import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture"; +import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture"; +import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture"; +import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture"; +import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture"; + +import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; +import { + OrganizerScheduledEmail, + AttendeeScheduledEmail, + OrganizerRescheduledEmail, + AttendeeRescheduledEmail, + OrganizerCancelledEmail, + AttendeeCancelledEmail, +} from "@calcom/platform-libraries"; +import { + CreateBookingInput_2024_08_13, + BookingOutput_2024_08_13, + RescheduleBookingInput_2024_08_13, + RecurringBookingOutput_2024_08_13, +} from "@calcom/platform-types"; +import { CancelBookingInput_2024_08_13 } from "@calcom/platform-types"; +import { Team } from "@calcom/prisma/client"; + +jest + .spyOn(AttendeeScheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerScheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeRescheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerRescheduledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(AttendeeCancelledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); +jest + .spyOn(OrganizerCancelledEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

")); + +type EmailSetup = { + user: User; + eventTypeId: number; + recurringEventTypeId: number; + createdBookingUid: string; + rescheduledBookingUid: string; +}; + +describe("Bookings Endpoints 2024-08-13 user emails", () => { + let app: INestApplication; + let organization: Team; + + let userRepositoryFixture: UserRepositoryFixture; + let bookingsRepositoryFixture: BookingsRepositoryFixture; + let schedulesService: SchedulesService_2024_04_15; + let eventTypesRepositoryFixture: EventTypesRepositoryFixture; + let oauthClientRepositoryFixture: OAuthClientRepositoryFixture; + let teamRepositoryFixture: TeamRepositoryFixture; + + let emailsEnabledSetup: EmailSetup; + let emailsDisabledSetup: EmailSetup; + + beforeAll(async () => { + const moduleRef = await Test.createTestingModule({ + imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15], + }) + .overrideGuard(PermissionsGuard) + .useValue({ + canActivate: () => true, + }) + .overrideGuard(ApiAuthGuard) + .useValue({ + canActivate: () => true, + }) + .compile(); + + userRepositoryFixture = new UserRepositoryFixture(moduleRef); + bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef); + eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef); + oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef); + teamRepositoryFixture = new TeamRepositoryFixture(moduleRef); + schedulesService = moduleRef.get(SchedulesService_2024_04_15); + + organization = await teamRepositoryFixture.create({ name: "organization bookings" }); + + await setupEnabledEmails(); + await setupDisabledEmails(); + + app = moduleRef.createNestApplication(); + bootstrap(app as NestExpressApplication); + + await app.init(); + }); + + async function setupEnabledEmails() { + const oAuthClientEmailsEnabled = await createOAuthClient(organization.id, true); + + const user = await userRepositoryFixture.create({ + email: `alice-${Math.floor(Math.random() * 1000)}@gmail.com`, + platformOAuthClients: { + connect: { + id: oAuthClientEmailsEnabled.id, + }, + }, + }); + + const userSchedule: CreateScheduleInput_2024_04_15 = { + name: "working time", + timeZone: "Europe/Rome", + isDefault: true, + }; + await schedulesService.createUserSchedule(user.id, userSchedule); + + const event = await eventTypesRepositoryFixture.create( + { title: "peer coding", slug: "peer-coding", length: 60 }, + user.id + ); + + const recurringEvent = await eventTypesRepositoryFixture.create( + // note(Lauris): freq 2 means weekly, interval 1 means every week and count 3 means 3 weeks in a row + { + title: "peer coding recurring", + slug: "peer-coding-recurring", + length: 60, + recurringEvent: { freq: 2, count: 3, interval: 1 }, + }, + user.id + ); + + emailsEnabledSetup = { + user, + eventTypeId: event.id, + recurringEventTypeId: recurringEvent.id, + createdBookingUid: "", + rescheduledBookingUid: "", + }; + } + + async function setupDisabledEmails() { + const oAuthClientEmailsDisabled = await createOAuthClient(organization.id, false); + + const user = await userRepositoryFixture.create({ + email: `bob-${Math.floor(Math.random() * 1000)}@gmail.com`, + platformOAuthClients: { + connect: { + id: oAuthClientEmailsDisabled.id, + }, + }, + }); + const userSchedule: CreateScheduleInput_2024_04_15 = { + name: "working time", + timeZone: "Europe/Rome", + isDefault: true, + }; + await schedulesService.createUserSchedule(user.id, userSchedule); + const event = await eventTypesRepositoryFixture.create( + { title: "peer coding", slug: "peer-coding", length: 60 }, + user.id + ); + + const recurringEvent = await eventTypesRepositoryFixture.create( + // note(Lauris): freq 2 means weekly, interval 1 means every week and count 3 means 3 weeks in a row + { + title: "peer coding recurring", + slug: "peer-coding-recurring", + length: 60, + recurringEvent: { freq: 2, count: 3, interval: 1 }, + }, + user.id + ); + + emailsDisabledSetup = { + user, + eventTypeId: event.id, + recurringEventTypeId: recurringEvent.id, + createdBookingUid: "", + rescheduledBookingUid: "", + }; + } + + async function createOAuthClient(organizationId: number, emailsEnabled: boolean) { + const data = { + logo: "logo-url", + name: "name", + redirectUris: ["http://localhost:5555"], + permissions: 32, + areEmailsEnabled: emailsEnabled, + }; + const secret = "secret"; + + const client = await oauthClientRepositoryFixture.create(organizationId, data, secret); + return client; + } + + beforeEach(async () => { + jest.clearAllMocks(); + }); + + describe("OAuth client managed user bookings - emails disabled", () => { + it("should not send an email when creating a booking", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(), + eventTypeId: emailsDisabledSetup.eventTypeId, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + emailsDisabledSetup.createdBookingUid = responseBody.data.uid; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should not send an email when creating a recurring booking", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 9, 0, 0)).toISOString(), + eventTypeId: emailsDisabledSetup.recurringEventTypeId, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsRecurringBooking(responseBody.data)) { + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + } else { + throw new Error("Invalid response data - expected booking array but received single booking"); + } + }); + }); + + it("should not send an email when rescheduling a booking", async () => { + const body: RescheduleBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2035, 0, 8, 14, 0, 0)).toISOString(), + reschedulingReason: "Flying to mars that day", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.createdBookingUid}/reschedule`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: RescheduleBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(AttendeeRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerRescheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + emailsDisabledSetup.rescheduledBookingUid = responseBody.data.uid; + }); + }); + + it("should not send an email when cancelling a booking", async () => { + const body: CancelBookingInput_2024_08_13 = { + cancellationReason: "Going on a vacation", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsDisabledSetup.rescheduledBookingUid}/cancel`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerCancelledEmail.prototype.getHtml).not.toHaveBeenCalled(); + }); + }); + }); + + describe("OAuth client managed user bookings - emails enabled", () => { + it("should send an email when creating a booking", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 13, 0, 0)).toISOString(), + eventTypeId: emailsEnabledSetup.eventTypeId, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsBooking(responseBody.data)) { + const data: BookingOutput_2024_08_13 = responseBody.data; + expect(AttendeeScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + emailsEnabledSetup.createdBookingUid = responseBody.data.uid; + } else { + throw new Error( + "Invalid response data - expected booking but received array of possibily recurring bookings" + ); + } + }); + }); + + it("should send an email when creating a recurring booking", async () => { + const body: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 8, 9, 0, 0)).toISOString(), + eventTypeId: emailsEnabledSetup.recurringEventTypeId, + attendee: { + name: "Mr Proper", + email: "mr_proper@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + return request(app.getHttpServer()) + .post("/v2/bookings") + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: CreateBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + if (responseDataIsRecurringBooking(responseBody.data)) { + expect(AttendeeScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).toHaveBeenCalled(); + } else { + throw new Error("Invalid response data - expected booking array but received single booking"); + } + }); + }); + + it("should send an email when rescheduling a booking", async () => { + const body: RescheduleBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2035, 0, 8, 14, 0, 0)).toISOString(), + reschedulingReason: "Flying to mars that day", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.createdBookingUid}/reschedule`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201) + .then(async (response) => { + const responseBody: RescheduleBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + expect(OrganizerScheduledEmail.prototype.getHtml).not.toHaveBeenCalled(); + + expect(AttendeeRescheduledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerRescheduledEmail.prototype.getHtml).toHaveBeenCalled(); + + emailsEnabledSetup.rescheduledBookingUid = responseBody.data.uid; + }); + }); + + it("should send an email when cancelling a booking", async () => { + const body: CancelBookingInput_2024_08_13 = { + cancellationReason: "Going on a vacation", + }; + + return request(app.getHttpServer()) + .post(`/v2/bookings/${emailsEnabledSetup.rescheduledBookingUid}/cancel`) + .send(body) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(200) + .then(async (response) => { + const responseBody: CancelBookingOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(AttendeeCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + expect(OrganizerCancelledEmail.prototype.getHtml).toHaveBeenCalled(); + }); + }); + }); + + afterAll(async () => { + await teamRepositoryFixture.delete(organization.id); + await userRepositoryFixture.deleteByEmail(emailsEnabledSetup.user.email); + await userRepositoryFixture.deleteByEmail(emailsDisabledSetup.user.email); + await bookingsRepositoryFixture.deleteAllBookings( + emailsEnabledSetup.user.id, + emailsEnabledSetup.user.email + ); + await bookingsRepositoryFixture.deleteAllBookings( + emailsDisabledSetup.user.id, + emailsDisabledSetup.user.email + ); + await app.close(); + }); + + function responseDataIsBooking(data: any): data is BookingOutput_2024_08_13 { + return !Array.isArray(data) && typeof data === "object" && data && "id" in data; + } + + function responseDataIsRecurringBooking(data: any): data is RecurringBookingOutput_2024_08_13[] { + return Array.isArray(data); + } +}); diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/reassign-bookings.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/reassign-bookings.e2e-spec.ts similarity index 94% rename from apps/api/v2/src/ee/bookings/2024-08-13/controllers/reassign-bookings.e2e-spec.ts rename to apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/reassign-bookings.e2e-spec.ts index b327b60e2a..63219cd7e8 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/reassign-bookings.e2e-spec.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/reassign-bookings.e2e-spec.ts @@ -1,6 +1,5 @@ import { bootstrap } from "@/app"; import { AppModule } from "@/app.module"; -import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output"; import { ReassignBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reassign-booking.output"; import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; @@ -25,26 +24,9 @@ import { UserRepositoryFixture } from "test/fixtures/repository/users.repository import { withApiAuth } from "test/utils/withApiAuth"; import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; -import { - AttendeeScheduledEmail, - OrganizerScheduledEmail, - OrganizerReassignedEmail, -} from "@calcom/platform-libraries"; import { CreateBookingInput_2024_08_13, BookingOutput_2024_08_13 } from "@calcom/platform-types"; import { PlatformOAuthClient, Team } from "@calcom/prisma/client"; -jest.spyOn(AttendeeScheduledEmail.prototype as any, "getHtml").mockImplementation(async function () { - return "Mocked Email Content"; -}); - -jest.spyOn(OrganizerScheduledEmail.prototype as any, "getHtml").mockImplementation(async function () { - return "Mocked Email Content"; -}); - -jest.spyOn(OrganizerReassignedEmail.prototype as any, "getHtml").mockImplementation(async function () { - return "Mocked Email Content"; -}); - describe("Bookings Endpoints 2024-08-13", () => { describe("Reassign bookings", () => { let app: INestApplication; @@ -97,14 +79,19 @@ describe("Bookings Endpoints 2024-08-13", () => { schedulesService = moduleRef.get(SchedulesService_2024_04_15); organization = await organizationsRepositoryFixture.create({ name: "organization team bookings" }); + oAuthClient = await createOAuthClient(organization.id); + team = await teamRepositoryFixture.create({ name: "team 1", isOrganization: false, parent: { connect: { id: organization.id } }, + createdByOAuthClient: { + connect: { + id: oAuthClient.id, + }, + }, }); - oAuthClient = await createOAuthClient(organization.id); - teamUser1 = await userRepositoryFixture.create({ email: teamUserEmail, locale: "it", diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/recurring-bookings.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/recurring-bookings.e2e-spec.ts similarity index 98% rename from apps/api/v2/src/ee/bookings/2024-08-13/controllers/recurring-bookings.e2e-spec.ts rename to apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/recurring-bookings.e2e-spec.ts index bdece2e420..dea1ee4046 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/recurring-bookings.e2e-spec.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/recurring-bookings.e2e-spec.ts @@ -72,6 +72,11 @@ describe("Bookings Endpoints 2024-08-13", () => { user = await userRepositoryFixture.create({ email: userEmail, + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { @@ -375,6 +380,11 @@ describe("Bookings Endpoints 2024-08-13", () => { user = await userRepositoryFixture.create({ email: userEmail, + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { @@ -577,6 +587,11 @@ describe("Bookings Endpoints 2024-08-13", () => { user = await userRepositoryFixture.create({ email: userEmail, + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/seated-bookings.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/seated-bookings.e2e-spec.ts similarity index 99% rename from apps/api/v2/src/ee/bookings/2024-08-13/controllers/seated-bookings.e2e-spec.ts rename to apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/seated-bookings.e2e-spec.ts index d212447cf6..c97b64d3fb 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/seated-bookings.e2e-spec.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/seated-bookings.e2e-spec.ts @@ -22,7 +22,6 @@ import { UserRepositoryFixture } from "test/fixtures/repository/users.repository import { withApiAuth } from "test/utils/withApiAuth"; import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; -import { AttendeeCancelledEmail, OrganizerCancelledEmail } from "@calcom/platform-libraries"; import { CancelSeatedBookingInput_2024_08_13, CreateRecurringSeatedBookingOutput_2024_08_13, @@ -39,14 +38,6 @@ import { } from "@calcom/platform-types"; import { PlatformOAuthClient, Team } from "@calcom/prisma/client"; -jest.spyOn(AttendeeCancelledEmail.prototype as any, "getHtml").mockImplementation(async function () { - return "Mocked Email Content"; -}); - -jest.spyOn(OrganizerCancelledEmail.prototype as any, "getHtml").mockImplementation(async function () { - return "Mocked Email Content"; -}); - describe("Bookings Endpoints 2024-08-13", () => { describe("Seated bookings", () => { let app: INestApplication; @@ -102,6 +93,11 @@ describe("Bookings Endpoints 2024-08-13", () => { user = await userRepositoryFixture.create({ email: userEmail, + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { @@ -721,6 +717,11 @@ describe("Bookings Endpoints 2024-08-13", () => { user = await userRepositoryFixture.create({ email: userEmail, + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/team-bookings.controller.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/team-bookings.e2e-spec.ts similarity index 97% rename from apps/api/v2/src/ee/bookings/2024-08-13/controllers/team-bookings.controller.e2e-spec.ts rename to apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/team-bookings.e2e-spec.ts index 17c9b343d5..10c5a86deb 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/team-bookings.controller.e2e-spec.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/team-bookings.e2e-spec.ts @@ -85,30 +85,50 @@ describe("Bookings Endpoints 2024-08-13", () => { schedulesService = moduleRef.get(SchedulesService_2024_04_15); organization = await organizationsRepositoryFixture.create({ name: "organization team bookings" }); + oAuthClient = await createOAuthClient(organization.id); + team1 = await teamRepositoryFixture.create({ name: "team 1", isOrganization: false, parent: { connect: { id: organization.id } }, + createdByOAuthClient: { + connect: { + id: oAuthClient.id, + }, + }, }); team2 = await teamRepositoryFixture.create({ name: "team 2", isOrganization: false, parent: { connect: { id: organization.id } }, + createdByOAuthClient: { + connect: { + id: oAuthClient.id, + }, + }, }); - oAuthClient = await createOAuthClient(organization.id); - teamUser = await userRepositoryFixture.create({ email: teamUserEmail, locale: "it", name: "orgUser1team1", + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); teamUser2 = await userRepositoryFixture.create({ email: teamUserEmail2, locale: "es", name: "orgUser2team1", + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/user-bookings.controller.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/user-bookings.e2e-spec.ts similarity index 99% rename from apps/api/v2/src/ee/bookings/2024-08-13/controllers/user-bookings.controller.e2e-spec.ts rename to apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/user-bookings.e2e-spec.ts index 805c747557..8edf53263f 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/user-bookings.controller.e2e-spec.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/user-bookings.e2e-spec.ts @@ -96,6 +96,11 @@ describe("Bookings Endpoints 2024-08-13", () => { user = await userRepositoryFixture.create({ email: userEmail, + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/variable-length-bookings.controller.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/variable-length-bookings.e2e-spec.ts similarity index 96% rename from apps/api/v2/src/ee/bookings/2024-08-13/controllers/variable-length-bookings.controller.e2e-spec.ts rename to apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/variable-length-bookings.e2e-spec.ts index 82fa04ad3f..bb406fd1ae 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/variable-length-bookings.controller.e2e-spec.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/variable-length-bookings.e2e-spec.ts @@ -1,9 +1,6 @@ import { bootstrap } from "@/app"; import { AppModule } from "@/app.module"; -import { CancelBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/cancel-booking.output"; import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output"; -import { MarkAbsentBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/mark-absent.output"; -import { RescheduleBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/reschedule-booking.output"; import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input"; import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service"; @@ -71,6 +68,11 @@ describe("Bookings Endpoints 2024-08-13", () => { user = await userRepositoryFixture.create({ email: userEmail, + platformOAuthClients: { + connect: { + id: oAuthClient.id, + }, + }, }); const userSchedule: CreateScheduleInput_2024_04_15 = { diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/services/bookings.service.ts b/apps/api/v2/src/ee/bookings/2024-08-13/services/bookings.service.ts index 976a53ace0..757d6c849c 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/services/bookings.service.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/services/bookings.service.ts @@ -389,11 +389,14 @@ export class BookingsService_2024_08_13 { throw new NotFoundException(`Booking with uid=${bookingUid} was not found in the database`); } + const emailsEnabled = booking.eventTypeId ? await this.getEmailsEnabled(booking.eventTypeId) : true; + const profile = this.usersService.getUserMainProfile(requestUser); await roundRobinReassignment({ bookingId: booking.id, orgId: profile?.organizationId || null, + emailsEnabled, }); const reassigned = await this.bookingsRepository.getByUidWithUser(bookingUid); @@ -404,6 +407,12 @@ export class BookingsService_2024_08_13 { return this.outputService.getOutputReassignedBooking(reassigned); } + async getEmailsEnabled(eventTypeId: number) { + const oAuthParams = await this.inputService.getOAuthClientParams(eventTypeId); + const emailsEnabled = oAuthParams ? oAuthParams.arePlatformEmailsEnabled : true; + return emailsEnabled; + } + async reassignBookingToUser( bookingUid: string, newUserId: number, @@ -420,6 +429,8 @@ export class BookingsService_2024_08_13 { throw new NotFoundException(`User with id=${newUserId} was not found in the database`); } + const emailsEnabled = booking.eventTypeId ? await this.getEmailsEnabled(booking.eventTypeId) : true; + const profile = this.usersService.getUserMainProfile(user); const reassigned = await roundRobinManualReassignment({ @@ -428,6 +439,7 @@ export class BookingsService_2024_08_13 { orgId: profile?.organizationId || null, reassignReason: body.reason, reassignedById, + emailsEnabled, }); return this.outputService.getOutputReassignedBooking(reassigned); @@ -439,6 +451,8 @@ export class BookingsService_2024_08_13 { throw new NotFoundException(`Booking with uid=${bookingUid} was not found in the database`); } + const emailsEnabled = booking.eventTypeId ? await this.getEmailsEnabled(booking.eventTypeId) : true; + await confirmBookingHandler({ ctx: { user: requestUser, @@ -447,6 +461,7 @@ export class BookingsService_2024_08_13 { bookingId: booking.id, confirmed: true, recurringEventId: booking.recurringEventId, + emailsEnabled, }, }); @@ -459,6 +474,8 @@ export class BookingsService_2024_08_13 { throw new NotFoundException(`Booking with uid=${bookingUid} was not found in the database`); } + const emailsEnabled = booking.eventTypeId ? await this.getEmailsEnabled(booking.eventTypeId) : true; + await confirmBookingHandler({ ctx: { user: requestUser, @@ -468,6 +485,7 @@ export class BookingsService_2024_08_13 { confirmed: false, recurringEventId: booking.recurringEventId, reason, + emailsEnabled, }, }); diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/services/input.service.ts b/apps/api/v2/src/ee/bookings/2024-08-13/services/input.service.ts index dbcf7e509c..6ff5d1a762 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/services/input.service.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/services/input.service.ts @@ -18,7 +18,6 @@ import { NextApiRequest } from "next/types"; import { v4 as uuidv4 } from "uuid"; import { z } from "zod"; -import { X_CAL_CLIENT_ID } from "@calcom/platform-constants"; import { EventTypeMetaDataSchema } from "@calcom/platform-libraries"; import { CancelBookingInput, @@ -33,19 +32,10 @@ import { RescheduleBookingInput_2024_08_13, RescheduleSeatedBookingInput_2024_08_13, } from "@calcom/platform-types"; -import { EventType } from "@calcom/prisma/client"; +import { EventType, PlatformOAuthClient } from "@calcom/prisma/client"; type BookingRequest = NextApiRequest & { userId: number | undefined } & OAuthRequestParams; -const DEFAULT_PLATFORM_PARAMS = { - platformClientId: "", - platformCancelUrl: "", - platformRescheduleUrl: "", - platformBookingUrl: "", - arePlatformEmailsEnabled: false, - platformBookingLocation: undefined, -}; - type OAuthRequestParams = { platformClientId: string; platformRescheduleUrl: string; @@ -92,30 +82,53 @@ export class InputBookingsService_2024_08_13 { body: CreateBookingInput_2024_08_13 | CreateInstantBookingInput_2024_08_13 ): Promise { const bodyTransformed = await this.transformInputCreateBooking(body); - const oAuthClientId = request.get(X_CAL_CLIENT_ID); - const requestId = request.get("X-Request-Id"); + const oAuthClientParams = await this.getOAuthClientParams(body.eventTypeId); const newRequest = { ...request }; const userId = (await this.createBookingRequestOwnerId(request)) ?? undefined; - const oAuthParams = oAuthClientId - ? await this.createBookingRequestOAuthClientParams(oAuthClientId) - : DEFAULT_PLATFORM_PARAMS; const location = request.body.location || request.body.meetingUrl; this.logger.log(`createBookingRequest_2024_04_15`, { - requestId, + requestId: request.get("X-Request-Id"), ownerId: userId, location, - oAuthClientId, - ...oAuthParams, + oAuthClientParams, }); - Object.assign(newRequest, { userId, ...oAuthParams, platformBookingLocation: location }); - newRequest.body = { ...bodyTransformed, noEmail: !oAuthParams.arePlatformEmailsEnabled }; + if (oAuthClientParams) { + Object.assign(newRequest, { userId, ...oAuthClientParams, platformBookingLocation: location }); + newRequest.body = { ...bodyTransformed, noEmail: !oAuthClientParams.arePlatformEmailsEnabled }; + } else { + Object.assign(newRequest, { userId, platformBookingLocation: location }); + newRequest.body = { ...bodyTransformed, noEmail: false }; + } return newRequest as unknown as BookingRequest; } + async getOAuthClientParams(eventTypeId: number) { + const eventType = await this.eventTypesRepository.getEventTypeById(eventTypeId); + + let oAuthClient: PlatformOAuthClient | null = null; + if (eventType?.userId) { + oAuthClient = await this.oAuthClientRepository.getByUserId(eventType.userId); + } else if (eventType?.teamId) { + oAuthClient = await this.oAuthClientRepository.getByTeamId(eventType.teamId); + } + + if (oAuthClient) { + return { + platformClientId: oAuthClient.id, + platformCancelUrl: oAuthClient.bookingCancelRedirectUri, + platformRescheduleUrl: oAuthClient.bookingRescheduleRedirectUri, + platformBookingUrl: oAuthClient.bookingRedirectUri, + arePlatformEmailsEnabled: oAuthClient.areEmailsEnabled, + }; + } + + return undefined; + } + async transformInputCreateBooking(inputBooking: CreateBookingInput_2024_08_13) { const eventType = await this.eventTypesRepository.getEventTypeByIdWithOwnerAndTeam( inputBooking.eventTypeId @@ -178,21 +191,23 @@ export class InputBookingsService_2024_08_13 { ): Promise { // note(Lauris): update to this.transformInputCreate when rescheduling is implemented const bodyTransformed = await this.transformInputCreateRecurringBooking(body); - const oAuthClientId = request.get(X_CAL_CLIENT_ID); + const oAuthClientParams = await this.getOAuthClientParams(body.eventTypeId); const newRequest = { ...request }; const userId = (await this.createBookingRequestOwnerId(request)) ?? undefined; - const oAuthParams = oAuthClientId - ? await this.createBookingRequestOAuthClientParams(oAuthClientId) - : DEFAULT_PLATFORM_PARAMS; const location = request.body.location || request.body.meetingUrl; - Object.assign(newRequest, { - userId, - ...oAuthParams, - platformBookingLocation: location, - noEmail: !oAuthParams.arePlatformEmailsEnabled, - }); + + if (oAuthClientParams) { + Object.assign(newRequest, { + userId, + ...oAuthClientParams, + platformBookingLocation: location, + noEmail: !oAuthClientParams.arePlatformEmailsEnabled, + }); + } else { + Object.assign(newRequest, { userId, platformBookingLocation: location }); + } newRequest.body = bodyTransformed.map((event) => ({ ...event, @@ -282,18 +297,19 @@ export class InputBookingsService_2024_08_13 { ? await this.transformInputRescheduleSeatedBooking(bookingUid, body) : await this.transformInputRescheduleBooking(bookingUid, body); - const oAuthClientId = request.get(X_CAL_CLIENT_ID); + const oAuthClientParams = await this.getOAuthClientParams(bodyTransformed.eventTypeId); const newRequest = { ...request }; const userId = (await this.createBookingRequestOwnerId(request)) ?? undefined; - const oAuthParams = oAuthClientId - ? await this.createBookingRequestOAuthClientParams(oAuthClientId) - : DEFAULT_PLATFORM_PARAMS; const location = await this.getRescheduleBookingLocation(bookingUid); - Object.assign(newRequest, { userId, ...oAuthParams, platformBookingLocation: location }); - - newRequest.body = { ...bodyTransformed, noEmail: !oAuthParams.arePlatformEmailsEnabled }; + if (oAuthClientParams) { + Object.assign(newRequest, { userId, ...oAuthClientParams, platformBookingLocation: location }); + newRequest.body = { ...bodyTransformed, noEmail: !oAuthClientParams.arePlatformEmailsEnabled }; + } else { + Object.assign(newRequest, { userId, platformBookingLocation: location }); + newRequest.body = { ...bodyTransformed, noEmail: false }; + } return newRequest as unknown as BookingRequest; } @@ -416,24 +432,6 @@ export class InputBookingsService_2024_08_13 { } } - private async createBookingRequestOAuthClientParams(clientId: string) { - const params = DEFAULT_PLATFORM_PARAMS; - try { - const client = await this.oAuthClientRepository.getOAuthClient(clientId); - if (client) { - params.platformClientId = clientId; - params.platformCancelUrl = client.bookingCancelRedirectUri ?? ""; - params.platformRescheduleUrl = client.bookingRescheduleRedirectUri ?? ""; - params.platformBookingUrl = client.bookingRedirectUri ?? ""; - params.arePlatformEmailsEnabled = client.areEmailsEnabled ?? false; - } - return params; - } catch (err) { - this.logger.error(err); - return params; - } - } - transformGetBookingsFilters(queryParams: GetBookingsInput_2024_08_13) { return { attendeeEmail: queryParams.attendeeEmail, @@ -466,17 +464,26 @@ export class InputBookingsService_2024_08_13 { const bodyTransformed = this.isCancelSeatedBody(body) ? await this.transformInputCancelSeatedBooking(bookingUid, body) : await this.transformInputCancelBooking(bookingUid, body); - const oAuthClientId = request.get(X_CAL_CLIENT_ID); + + const booking = await this.bookingsRepository.getByUid(bodyTransformed.uid); + if (!booking) { + throw new NotFoundException(`Booking with uid=${bookingUid} not found`); + } + + const oAuthClientParams = booking.eventTypeId + ? await this.getOAuthClientParams(booking.eventTypeId) + : undefined; const newRequest = { ...request }; const userId = (await this.createBookingRequestOwnerId(request)) ?? undefined; - const oAuthParams = oAuthClientId - ? await this.createBookingRequestOAuthClientParams(oAuthClientId) - : DEFAULT_PLATFORM_PARAMS; - Object.assign(newRequest, { userId, ...oAuthParams }); - - newRequest.body = { ...bodyTransformed, noEmail: !oAuthParams.arePlatformEmailsEnabled }; + if (oAuthClientParams) { + Object.assign(newRequest, { userId, ...oAuthClientParams }); + newRequest.body = { ...bodyTransformed, noEmail: !oAuthClientParams.arePlatformEmailsEnabled }; + } else { + Object.assign(newRequest, { userId }); + newRequest.body = { ...bodyTransformed, noEmail: false }; + } return newRequest as unknown as BookingRequest; } diff --git a/apps/api/v2/src/modules/oauth-clients/oauth-client.repository.ts b/apps/api/v2/src/modules/oauth-clients/oauth-client.repository.ts index ed356afaf1..dbbf2dbf21 100644 --- a/apps/api/v2/src/modules/oauth-clients/oauth-client.repository.ts +++ b/apps/api/v2/src/modules/oauth-clients/oauth-client.repository.ts @@ -99,4 +99,28 @@ export class OAuthClientRepository { where: { id: clientId }, }); } + + async getByUserId(userId: number) { + return this.dbRead.prisma.platformOAuthClient.findFirst({ + where: { + users: { + some: { + id: userId, + }, + }, + }, + }); + } + + async getByTeamId(teamId: number) { + return this.dbRead.prisma.platformOAuthClient.findFirst({ + where: { + teams: { + some: { + id: teamId, + }, + }, + }, + }); + } } diff --git a/packages/emails/templates/attendee-cancelled-email.ts b/packages/emails/templates/attendee-cancelled-email.ts index d39384017f..b2243db7db 100644 --- a/packages/emails/templates/attendee-cancelled-email.ts +++ b/packages/emails/templates/attendee-cancelled-email.ts @@ -24,7 +24,7 @@ export default class AttendeeCancelledEmail extends AttendeeScheduledEmail { }; } - protected async getHtml(calEvent: CalendarEvent, attendee: Person) { + async getHtml(calEvent: CalendarEvent, attendee: Person) { return await renderEmail("AttendeeCancelledEmail", { calEvent, attendee, diff --git a/packages/emails/templates/attendee-declined-email.ts b/packages/emails/templates/attendee-declined-email.ts index 4933a41663..90f1700c6d 100644 --- a/packages/emails/templates/attendee-declined-email.ts +++ b/packages/emails/templates/attendee-declined-email.ts @@ -20,7 +20,7 @@ export default class AttendeeDeclinedEmail extends AttendeeScheduledEmail { }; } - protected async getHtml(calEvent: CalendarEvent, attendee: Person) { + async getHtml(calEvent: CalendarEvent, attendee: Person) { return await renderEmail("AttendeeDeclinedEmail", { calEvent, attendee, diff --git a/packages/emails/templates/attendee-request-email.ts b/packages/emails/templates/attendee-request-email.ts index 24e36538e4..c58b3d1491 100644 --- a/packages/emails/templates/attendee-request-email.ts +++ b/packages/emails/templates/attendee-request-email.ts @@ -1,4 +1,5 @@ import { EMAIL_FROM_NAME } from "@calcom/lib/constants"; +import type { CalendarEvent, Person } from "@calcom/types/Calendar"; import { renderEmail } from "../"; import AttendeeScheduledEmail from "./attendee-scheduled-email"; @@ -15,10 +16,7 @@ export default class AttendeeRequestEmail extends AttendeeScheduledEmail { title: this.calEvent.title, date: this.getFormattedDate(), })}`, - html: await renderEmail("AttendeeRequestEmail", { - calEvent: this.calEvent, - attendee: this.attendee, - }), + html: await this.getHtmlRequestEmail(this.calEvent, this.attendee), text: this.getTextBody( this.calEvent.attendees[0].language.translate("booking_submitted", { name: this.calEvent.attendees[0].name, @@ -29,4 +27,11 @@ export default class AttendeeRequestEmail extends AttendeeScheduledEmail { ), }; } + + async getHtmlRequestEmail(calEvent: CalendarEvent, attendee: Person) { + return await renderEmail("AttendeeRequestEmail", { + calEvent, + attendee, + }); + } } diff --git a/packages/emails/templates/attendee-rescheduled-email.ts b/packages/emails/templates/attendee-rescheduled-email.ts index 540179f496..33e79c7fb0 100644 --- a/packages/emails/templates/attendee-rescheduled-email.ts +++ b/packages/emails/templates/attendee-rescheduled-email.ts @@ -1,3 +1,5 @@ +import type { CalendarEvent, Person } from "@calcom/types/Calendar"; + import { renderEmail } from "../"; import generateIcsFile, { GenerateIcsRole } from "../lib/generateIcsFile"; import AttendeeScheduledEmail from "./attendee-scheduled-email"; @@ -17,11 +19,15 @@ export default class AttendeeRescheduledEmail extends AttendeeScheduledEmail { title: this.calEvent.title, date: this.getFormattedDate(), })}`, - html: await renderEmail("AttendeeRescheduledEmail", { - calEvent: this.calEvent, - attendee: this.attendee, - }), + html: await this.getHtml(this.calEvent, this.attendee), text: this.getTextBody("event_has_been_rescheduled", "emailed_you_and_any_other_attendees"), }; } + + async getHtml(calEvent: CalendarEvent, attendee: Person) { + return await renderEmail("AttendeeRescheduledEmail", { + calEvent, + attendee, + }); + } } diff --git a/packages/emails/templates/attendee-scheduled-email.ts b/packages/emails/templates/attendee-scheduled-email.ts index 7dbb22d498..5564c31540 100644 --- a/packages/emails/templates/attendee-scheduled-email.ts +++ b/packages/emails/templates/attendee-scheduled-email.ts @@ -47,7 +47,7 @@ export default class AttendeeScheduledEmail extends BaseEmail { }; } - protected async getHtml(calEvent: CalendarEvent, attendee: Person) { + async getHtml(calEvent: CalendarEvent, attendee: Person) { return await renderEmail("AttendeeScheduledEmail", { calEvent, attendee, diff --git a/packages/emails/templates/organizer-cancelled-email.ts b/packages/emails/templates/organizer-cancelled-email.ts index 19a1729938..25ab1a2097 100644 --- a/packages/emails/templates/organizer-cancelled-email.ts +++ b/packages/emails/templates/organizer-cancelled-email.ts @@ -26,7 +26,7 @@ export default class OrganizerCancelledEmail extends OrganizerScheduledEmail { }; } - protected async getHtml(calEvent: CalendarEvent, organizer: Person) { + async getHtml(calEvent: CalendarEvent, organizer: Person) { return await renderEmail("OrganizerCancelledEmail", { calEvent, attendee: organizer, diff --git a/packages/emails/templates/organizer-reassigned-email.ts b/packages/emails/templates/organizer-reassigned-email.ts index fe73560e95..e24c0277fb 100644 --- a/packages/emails/templates/organizer-reassigned-email.ts +++ b/packages/emails/templates/organizer-reassigned-email.ts @@ -27,7 +27,7 @@ export default class OrganizerReassignedEmail extends OrganizerScheduledEmail { }; } - protected async getHtml(calEvent: CalendarEvent, attendee: Person, reassigned: Reassigned | undefined) { + async getHtml(calEvent: CalendarEvent, attendee: Person, reassigned: Reassigned | undefined) { return await renderEmail("OrganizerReassignedEmail", { calEvent, attendee, diff --git a/packages/emails/templates/organizer-request-email.ts b/packages/emails/templates/organizer-request-email.ts index 424a6e141f..02e1c08c35 100644 --- a/packages/emails/templates/organizer-request-email.ts +++ b/packages/emails/templates/organizer-request-email.ts @@ -1,5 +1,6 @@ import { checkIfUserHasFeatureController } from "@calcom/features/flags/operations/check-if-user-has-feature.controller"; import { EMAIL_FROM_NAME } from "@calcom/lib/constants"; +import type { CalendarEvent, Person } from "@calcom/types/Calendar"; import { renderEmail } from "../"; import OrganizerScheduledEmail from "./organizer-scheduled-email"; @@ -22,10 +23,7 @@ export default class OrganizerRequestEmail extends OrganizerScheduledEmail { to: toAddresses.join(","), replyTo: [this.calEvent.organizer.email, ...this.calEvent.attendees.map(({ email }) => email)], subject: `${this.t("awaiting_approval")}: ${this.calEvent.title}`, - html: await renderEmail(template, { - calEvent: this.calEvent, - attendee: this.calEvent.organizer, - }), + html: await this.getHtmlRequestEmail(template, this.calEvent, this.calEvent.organizer), text: this.getTextBody("event_awaiting_approval"), }; } @@ -41,4 +39,15 @@ ${process.env.NEXT_PUBLIC_WEBAPP_URL} + ${ }` ); } + + async getHtmlRequestEmail( + template: "OrganizerRequestEmailV2" | "OrganizerRequestEmail", + calEvent: CalendarEvent, + attendee: Person + ) { + return await renderEmail(template, { + calEvent, + attendee, + }); + } } diff --git a/packages/emails/templates/organizer-rescheduled-email.ts b/packages/emails/templates/organizer-rescheduled-email.ts index 2a073a92d7..edac446108 100644 --- a/packages/emails/templates/organizer-rescheduled-email.ts +++ b/packages/emails/templates/organizer-rescheduled-email.ts @@ -1,4 +1,5 @@ import { EMAIL_FROM_NAME } from "@calcom/lib/constants"; +import type { CalendarEvent, Person } from "@calcom/types/Calendar"; import { renderEmail } from "../"; import generateIcsFile, { GenerateIcsRole } from "../lib/generateIcsFile"; @@ -21,11 +22,15 @@ export default class OrganizerRescheduledEmail extends OrganizerScheduledEmail { title: this.calEvent.title, date: this.getFormattedDate(), })}`, - html: await renderEmail("OrganizerRescheduledEmail", { - calEvent: { ...this.calEvent, attendeeSeatId: undefined }, - attendee: this.calEvent.organizer, - }), + html: await this.getHtml({ ...this.calEvent, attendeeSeatId: undefined }, this.calEvent.organizer), text: this.getTextBody("event_has_been_rescheduled"), }; } + + async getHtml(calEvent: CalendarEvent, attendee: Person) { + return await renderEmail("OrganizerRescheduledEmail", { + calEvent, + attendee, + }); + } } diff --git a/packages/emails/templates/organizer-scheduled-email.ts b/packages/emails/templates/organizer-scheduled-email.ts index 44eb9f7924..cd6168fbd1 100644 --- a/packages/emails/templates/organizer-scheduled-email.ts +++ b/packages/emails/templates/organizer-scheduled-email.ts @@ -60,7 +60,7 @@ export default class OrganizerScheduledEmail extends BaseEmail { }; } - protected async getHtml( + async getHtml( calEvent: CalendarEvent, attendee: Person, teamMember?: Person, diff --git a/packages/features/bookings/lib/handleConfirmation.ts b/packages/features/bookings/lib/handleConfirmation.ts index eb949e11a8..9611748134 100644 --- a/packages/features/bookings/lib/handleConfirmation.ts +++ b/packages/features/bookings/lib/handleConfirmation.ts @@ -67,8 +67,9 @@ export async function handleConfirmation(args: { userId: number | null; }; paid?: boolean; + emailsEnabled?: boolean; }) { - const { user, evt, recurringEventId, prisma, bookingId, booking, paid } = args; + const { user, evt, recurringEventId, prisma, bookingId, booking, paid, emailsEnabled = true } = args; const eventType = booking.eventType; const eventTypeMetadata = EventTypeMetaDataSchema.parse(eventType?.metadata || {}); const eventManager = new EventManager(user, eventTypeMetadata?.apps); @@ -113,13 +114,15 @@ export async function handleConfirmation(args: { } } - await sendScheduledEmailsAndSMS( - { ...evt, additionalInformation: metadata }, - undefined, - isHostConfirmationEmailsDisabled, - isAttendeeConfirmationEmailDisabled, - eventTypeMetadata - ); + if (emailsEnabled) { + await sendScheduledEmailsAndSMS( + { ...evt, additionalInformation: metadata }, + undefined, + isHostConfirmationEmailsDisabled, + isAttendeeConfirmationEmailDisabled, + eventTypeMetadata + ); + } } catch (error) { log.error(error); } diff --git a/packages/features/bookings/lib/handleNewRecurringBooking.ts b/packages/features/bookings/lib/handleNewRecurringBooking.ts index 3185046f38..36f08bee73 100644 --- a/packages/features/bookings/lib/handleNewRecurringBooking.ts +++ b/packages/features/bookings/lib/handleNewRecurringBooking.ts @@ -44,7 +44,7 @@ export const handleNewRecurringBooking = async ( thirdPartyRecurringEventId, numSlotsToCheckForAvailability, currentRecurringIndex: 0, - noEmail: false, + noEmail: req.noEmail !== undefined ? req.noEmail : false, }; const firstBookingResult = await handleNewBooking(recurringEventReq); diff --git a/packages/features/ee/round-robin/roundRobinManualReassignment.ts b/packages/features/ee/round-robin/roundRobinManualReassignment.ts index 762e568f68..92d805e208 100644 --- a/packages/features/ee/round-robin/roundRobinManualReassignment.ts +++ b/packages/features/ee/round-robin/roundRobinManualReassignment.ts @@ -44,12 +44,14 @@ export const roundRobinManualReassignment = async ({ orgId, reassignReason, reassignedById, + emailsEnabled = true, }: { bookingId: number; newUserId: number; orgId: number | null; reassignReason?: string; reassignedById: number; + emailsEnabled?: boolean; }) => { const roundRobinReassignLogger = logger.getSubLogger({ prefix: ["roundRobinManualReassign", `${bookingId}`], @@ -289,24 +291,26 @@ export const roundRobinManualReassignment = async ({ const { cancellationReason, ...evtWithoutCancellationReason } = evtWithAdditionalInfo; // Send emails - await sendRoundRobinScheduledEmailsAndSMS({ - calEvent: evtWithoutCancellationReason, - members: [ - { - ...newUser, - name: newUser.name || "", - username: newUser.username || "", - timeFormat: getTimeFormatStringFromUserTimeFormat(newUser.timeFormat), - language: { translate: newUserT, locale: newUser.locale || "en" }, + if (emailsEnabled) { + await sendRoundRobinScheduledEmailsAndSMS({ + calEvent: evtWithoutCancellationReason, + members: [ + { + ...newUser, + name: newUser.name || "", + username: newUser.username || "", + timeFormat: getTimeFormatStringFromUserTimeFormat(newUser.timeFormat), + language: { translate: newUserT, locale: newUser.locale || "en" }, + }, + ], + reassigned: { + name: newUser.name, + email: newUser.email, + reason: reassignReason, + byUser: originalOrganizer.name || undefined, }, - ], - reassigned: { - name: newUser.name, - email: newUser.email, - reason: reassignReason, - byUser: originalOrganizer.name || undefined, - }, - }); + }); + } // Send cancellation email to previous RR host const cancelledEvt = cloneDeep(evtWithAdditionalInfo); @@ -317,7 +321,7 @@ export const roundRobinManualReassignment = async ({ language: { translate: originalOrganizerT, locale: originalOrganizer.locale || "en" }, }; - if (previousRRHost) { + if (previousRRHost && emailsEnabled) { await sendRoundRobinCancelledEmailsAndSMS( cancelledEvt, [ diff --git a/packages/features/ee/round-robin/roundRobinReassignment.ts b/packages/features/ee/round-robin/roundRobinReassignment.ts index bce27032c3..709b4e8aed 100644 --- a/packages/features/ee/round-robin/roundRobinReassignment.ts +++ b/packages/features/ee/round-robin/roundRobinReassignment.ts @@ -37,9 +37,11 @@ import { getTeamMembers } from "./utils/getTeamMembers"; export const roundRobinReassignment = async ({ bookingId, orgId, + emailsEnabled = true, }: { bookingId: number; orgId: number | null; + emailsEnabled?: boolean; }) => { const roundRobinReassignLogger = logger.getSubLogger({ prefix: ["roundRobinReassign", `${bookingId}`], @@ -321,18 +323,20 @@ export const roundRobinReassignment = async ({ const { cancellationReason, ...evtWithoutCancellationReason } = evtWithAdditionalInfo; // Send to new RR host - await sendRoundRobinScheduledEmailsAndSMS({ - calEvent: evtWithoutCancellationReason, - members: [ - { - ...reassignedRRHost, - name: reassignedRRHost.name || "", - username: reassignedRRHost.username || "", - timeFormat: getTimeFormatStringFromUserTimeFormat(reassignedRRHost.timeFormat), - language: { translate: reassignedRRHostT, locale: reassignedRRHost.locale || "en" }, - }, - ], - }); + if (emailsEnabled) { + await sendRoundRobinScheduledEmailsAndSMS({ + calEvent: evtWithoutCancellationReason, + members: [ + { + ...reassignedRRHost, + name: reassignedRRHost.name || "", + username: reassignedRRHost.username || "", + timeFormat: getTimeFormatStringFromUserTimeFormat(reassignedRRHost.timeFormat), + language: { translate: reassignedRRHostT, locale: reassignedRRHost.locale || "en" }, + }, + ], + }); + } if (previousRRHost) { // Send to cancelled RR host @@ -365,20 +369,22 @@ export const roundRobinReassignment = async ({ }); } - await sendRoundRobinCancelledEmailsAndSMS( - cancelledRRHostEvt, - [ - { - ...previousRRHost, - name: previousRRHost.name || "", - username: previousRRHost.username || "", - timeFormat: getTimeFormatStringFromUserTimeFormat(previousRRHost.timeFormat), - language: { translate: previousRRHostT, locale: previousRRHost.locale || "en" }, - }, - ], - eventType?.metadata as EventTypeMetadata, - { name: reassignedRRHost.name, email: reassignedRRHost.email } - ); + if (emailsEnabled) { + await sendRoundRobinCancelledEmailsAndSMS( + cancelledRRHostEvt, + [ + { + ...previousRRHost, + name: previousRRHost.name || "", + username: previousRRHost.username || "", + timeFormat: getTimeFormatStringFromUserTimeFormat(previousRRHost.timeFormat), + language: { translate: previousRRHostT, locale: previousRRHost.locale || "en" }, + }, + ], + eventType?.metadata as EventTypeMetadata, + { name: reassignedRRHost.name, email: reassignedRRHost.email } + ); + } } // Handle changing workflows with organizer diff --git a/packages/platform/libraries/index.ts b/packages/platform/libraries/index.ts index e944c47a00..e53978b604 100644 --- a/packages/platform/libraries/index.ts +++ b/packages/platform/libraries/index.ts @@ -7,9 +7,13 @@ import { getAppFromSlug } from "@calcom/app-store/utils"; import type { CredentialDataWithTeamName, LocationOption } from "@calcom/app-store/utils"; import AttendeeCancelledEmail from "@calcom/emails/templates/attendee-cancelled-email"; import AttendeeDeclinedEmail from "@calcom/emails/templates/attendee-declined-email"; +import AttendeeRequestEmail from "@calcom/emails/templates/attendee-request-email"; +import AttendeeRescheduledEmail from "@calcom/emails/templates/attendee-rescheduled-email"; import AttendeeScheduledEmail from "@calcom/emails/templates/attendee-scheduled-email"; import OrganizerCancelledEmail from "@calcom/emails/templates/organizer-cancelled-email"; import OrganizerReassignedEmail from "@calcom/emails/templates/organizer-reassigned-email"; +import OrganizerRequestEmail from "@calcom/emails/templates/organizer-request-email"; +import OrganizerRescheduledEmail from "@calcom/emails/templates/organizer-rescheduled-email"; import OrganizerScheduledEmail from "@calcom/emails/templates/organizer-scheduled-email"; import { getBookingForReschedule } from "@calcom/features/bookings/lib/get-booking"; import getBookingInfo from "@calcom/features/bookings/lib/getBookingInfo"; @@ -203,3 +207,11 @@ export { AttendeeCancelledEmail }; export { OrganizerCancelledEmail }; export { OrganizerReassignedEmail }; + +export { OrganizerRescheduledEmail }; + +export { AttendeeRescheduledEmail }; + +export { OrganizerRequestEmail }; + +export { AttendeeRequestEmail }; diff --git a/packages/prisma/zod-utils.ts b/packages/prisma/zod-utils.ts index 09362b0445..8b41c959f9 100644 --- a/packages/prisma/zod-utils.ts +++ b/packages/prisma/zod-utils.ts @@ -281,6 +281,7 @@ export const bookingConfirmPatchBodySchema = z.object({ confirmed: z.boolean(), recurringEventId: z.string().optional(), reason: z.string().optional(), + emailsEnabled: z.boolean().default(true), }); // `responses` is merged with it during handleNewBooking call because `responses` schema is dynamic and depends on eventType diff --git a/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts b/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts index a34f1946cf..f3d56ab268 100644 --- a/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts +++ b/packages/trpc/server/routers/viewer/bookings/confirm.handler.ts @@ -41,7 +41,7 @@ type ConfirmOptions = { export const confirmHandler = async ({ ctx, input }: ConfirmOptions) => { const { user } = ctx; - const { bookingId, recurringEventId, reason: rejectionReason, confirmed } = input; + const { bookingId, recurringEventId, reason: rejectionReason, confirmed, emailsEnabled } = input; const tOrganizer = await getTranslation(user.locale ?? "en", "common"); @@ -269,6 +269,7 @@ export const confirmHandler = async ({ ctx, input }: ConfirmOptions) => { prisma, bookingId, booking, + emailsEnabled, }); } else { evt.rejectionReason = rejectionReason; @@ -368,7 +369,9 @@ export const confirmHandler = async ({ ctx, input }: ConfirmOptions) => { }); } - await sendDeclinedEmailsAndSMS(evt, booking.eventType?.metadata as EventTypeMetadata); + if (emailsEnabled) { + await sendDeclinedEmailsAndSMS(evt, booking.eventType?.metadata as EventTypeMetadata); + } const teamId = await getTeamIdFromEventType({ eventType: { diff --git a/yarn.lock b/yarn.lock index 7509681cb8..b78b4e7b67 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4168,7 +4168,7 @@ __metadata: "@axiomhq/winston": ^1.2.0 "@calcom/platform-constants": "*" "@calcom/platform-enums": "*" - "@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.62" + "@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.63" "@calcom/platform-libraries-0.0.2": "npm:@calcom/platform-libraries@0.0.2" "@calcom/platform-types": "*" "@calcom/platform-utils": "*" @@ -5210,14 +5210,14 @@ __metadata: languageName: node linkType: hard -"@calcom/platform-libraries@npm:@calcom/platform-libraries@0.0.62": - version: 0.0.62 - resolution: "@calcom/platform-libraries@npm:0.0.62" +"@calcom/platform-libraries@npm:@calcom/platform-libraries@0.0.63": + version: 0.0.63 + resolution: "@calcom/platform-libraries@npm:0.0.63" dependencies: "@calcom/core": "*" "@calcom/features": "*" "@calcom/lib": "*" - checksum: 4bbc739fd5846529aa014ec0809078839a952580bb53e4fdfaf0a7418055836564ee4811b527abc211cba7b983b2f4bb8598a0a0ca184b03999b81f9ffd74693 + checksum: bb567ad7330a41717c9744ec4c4d6a90d8a585bca8c90b6dacf30f4bd3a97cb5572ce42df698cf1c3711b25222635b7483fd925dfa6f1df83b774d0fd2857099 languageName: node linkType: hard