diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/bookings.module.ts b/apps/api/v2/src/ee/bookings/2024-08-13/bookings.module.ts index 3ed1af1e63..905668cf1c 100644 --- a/apps/api/v2/src/ee/bookings/2024-08-13/bookings.module.ts +++ b/apps/api/v2/src/ee/bookings/2024-08-13/bookings.module.ts @@ -1,9 +1,12 @@ +import { Module } from "@nestjs/common"; +import { BookingAttendeesController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-attendees.controller"; import { BookingGuestsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-guests.controller"; import { BookingLocationController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-location.controller"; import { BookingsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/bookings.controller"; import { BookingPbacGuard } from "@/ee/bookings/2024-08-13/guards/booking-pbac.guard"; import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository"; import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; +import { BookingAttendeesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-attendees.service"; import { BookingGuestsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-guests.service"; import { BookingLocationService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-location.service"; import { BookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-references.service"; @@ -12,17 +15,18 @@ import { CalVideoOutputService } from "@/ee/bookings/2024-08-13/services/cal-vid import { CalVideoService } from "@/ee/bookings/2024-08-13/services/cal-video.service"; import { ErrorsBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/errors.service"; import { InputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/input.service"; -import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service"; import { OutputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output.service"; +import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service"; import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service"; import { CalendarsRepository } from "@/ee/calendars/calendars.repository"; -import { CalendarsCacheService } from "@/ee/calendars/services/calendars-cache.service"; import { CalendarsService } from "@/ee/calendars/services/calendars.service"; +import { CalendarsCacheService } from "@/ee/calendars/services/calendars-cache.service"; import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.module"; import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module"; import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository"; import { OutputEventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/output-event-types.service"; import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module"; +import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.module"; import { InstantBookingModule } from "@/lib/modules/instant-booking.module"; import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module"; import { RegularBookingModule } from "@/lib/modules/regular-booking.module"; @@ -50,8 +54,6 @@ import { TeamsModule } from "@/modules/teams/teams/teams.module"; import { TokensModule } from "@/modules/tokens/tokens.module"; import { TokensRepository } from "@/modules/tokens/tokens.repository"; import { UsersModule } from "@/modules/users/users.module"; -import { Module } from "@nestjs/common"; -import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.module"; @Module({ imports: [ @@ -81,6 +83,7 @@ import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.m OAuthClientRepository, OAuthClientUsersService, BookingsService_2024_08_13, + BookingAttendeesService_2024_08_13, BookingGuestsService_2024_08_13, InputBookingsService_2024_08_13, OutputBookingsService_2024_08_13, @@ -110,6 +113,7 @@ import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.m ], controllers: [ BookingsController_2024_08_13, + BookingAttendeesController_2024_08_13, BookingGuestsController_2024_08_13, BookingLocationController_2024_08_13, ], diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/booking-attendees.controller.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/booking-attendees.controller.ts new file mode 100644 index 0000000000..a64afcbc2b --- /dev/null +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/booking-attendees.controller.ts @@ -0,0 +1,71 @@ +import { BOOKING_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants"; +import { AddAttendeeInput_2024_08_13 } from "@calcom/platform-types"; +import { Body, Controller, HttpCode, HttpStatus, Param, Post, UseGuards } from "@nestjs/common"; +import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger"; +import { BookingPbacGuard } from "@/ee/bookings/2024-08-13/guards/booking-pbac.guard"; +import { BookingUidGuard } from "@/ee/bookings/2024-08-13/guards/booking-uid.guard"; +import { AddAttendeeOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-attendee.output"; +import { BookingAttendeesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-attendees.service"; +import { VERSION_2024_08_13, VERSION_2024_08_13_VALUE } from "@/lib/api-versions"; +import { API_KEY_OR_ACCESS_TOKEN_HEADER } from "@/lib/docs/headers"; +import { Throttle } from "@/lib/endpoint-throttler-decorator"; +import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator"; +import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator"; +import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard"; +import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard"; +import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy"; + +@Controller({ + path: "/v2/bookings/:bookingUid/attendees", + version: VERSION_2024_08_13_VALUE, +}) +@UseGuards(PermissionsGuard) +@DocsTags("Bookings / Attendees") +@ApiHeader({ + name: "cal-api-version", + description: `Must be set to ${VERSION_2024_08_13}. This header is required as this endpoint does not exist in older API versions.`, + example: VERSION_2024_08_13, + required: true, +}) +export class BookingAttendeesController_2024_08_13 { + constructor(private readonly bookingAttendeesService: BookingAttendeesService_2024_08_13) {} + + @Post("/") + @HttpCode(HttpStatus.CREATED) + @Permissions([BOOKING_WRITE]) + @UseGuards(ApiAuthGuard, BookingUidGuard, BookingPbacGuard) + @Throttle({ + limit: 5, + ttl: 60000, + blockDuration: 60000, + name: "booking_attendees_add", + }) + @ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER) + @ApiOperation({ + summary: "Add an attendee to a booking", + description: `Add a new attendee to an existing booking by its UID. + + **Side effects:** + - The booking's attendee list is updated in the database + - The calendar event is updated on connected calendars (Google Calendar, Outlook, etc.) to include the new attendee + - An email notification is sent to the new attendee with the booking details + + **Permissions:** + - The authenticated user must be either the booking organizer, an existing attendee, or have the \`booking.update\` permission for the team + + The cal-api-version header is required for this endpoint. Without it, the request will fail with a 404 error. + `, + }) + async addAttendee( + @Param("bookingUid") bookingUid: string, + @Body() body: AddAttendeeInput_2024_08_13, + @GetUser() user: ApiAuthGuardUser + ): Promise { + const attendee = await this.bookingAttendeesService.addAttendee(bookingUid, body, user); + + return { + status: SUCCESS_STATUS, + data: attendee, + }; + } +} diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/add-attendee.e2e-spec.ts b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/add-attendee.e2e-spec.ts new file mode 100644 index 0000000000..d773ae7f9d --- /dev/null +++ b/apps/api/v2/src/ee/bookings/2024-08-13/controllers/e2e/add-attendee.e2e-spec.ts @@ -0,0 +1,415 @@ +import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants"; +import { + AttendeeAddGuestsEmail, + AttendeeScheduledEmail, + OrganizerAddGuestsEmail, +} from "@calcom/platform-libraries/emails"; +import type { BookingOutput_2024_08_13, CreateBookingInput_2024_08_13 } from "@calcom/platform-types"; +import type { Team, User } from "@calcom/prisma/client"; +import { INestApplication } from "@nestjs/common"; +import { NestExpressApplication } from "@nestjs/platform-express"; +import { Test } from "@nestjs/testing"; +import 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 { TokensRepositoryFixture } from "test/fixtures/repository/tokens.repository.fixture"; +import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture"; +import { randomString } from "test/utils/randomString"; +import { mockThrottlerGuard } from "test/utils/withNoThrottler"; +import { AppModule } from "@/app.module"; +import { bootstrap } from "@/bootstrap"; +import { AddAttendeeOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-attendee.output"; +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"; + +const attendeeAddGuestsEmailSpy = jest + .spyOn(AttendeeAddGuestsEmail.prototype, "getHtml") + .mockImplementation(() => Promise.resolve("

email

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

email

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

email

")); + +type TestUser = { + user: User; + accessToken: string; + refreshToken: string; +}; + +type TestSetup = { + organizer: TestUser; + unrelatedUser: TestUser; + eventTypeId: number; + bookingUid: string; + bookingId: number; +}; + +describe("Bookings Endpoints 2024-08-13 add attendee", () => { + 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 tokensRepositoryFixture: TokensRepositoryFixture; + + let testSetup: TestSetup; + + beforeAll(async () => { + mockThrottlerGuard(); + + const moduleRef = await 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); + tokensRepositoryFixture = new TokensRepositoryFixture(moduleRef); + + organization = await teamRepositoryFixture.create({ + name: `add-attendee-2024-08-13-organization-${randomString()}`, + }); + + await setupTestData(); + + app = moduleRef.createNestApplication(); + bootstrap(app as NestExpressApplication); + + await app.init(); + }); + + async function setupTestData() { + const oAuthClient = await createOAuthClient(organization.id, true); + + const organizerUser = await userRepositoryFixture.create({ + email: `add-attendee-2024-08-13-organizer-${randomString()}@api.com`, + platformOAuthClients: { + connect: { id: oAuthClient.id }, + }, + }); + + const unrelatedUserData = await userRepositoryFixture.create({ + email: `add-attendee-2024-08-13-unrelated-${randomString()}@api.com`, + platformOAuthClients: { + connect: { id: oAuthClient.id }, + }, + }); + + const organizerTokens = await tokensRepositoryFixture.createTokens(organizerUser.id, oAuthClient.id); + const unrelatedUserTokens = await tokensRepositoryFixture.createTokens( + unrelatedUserData.id, + oAuthClient.id + ); + + const schedule: CreateScheduleInput_2024_04_15 = { + name: `add-attendee-2024-08-13-schedule-${randomString()}`, + timeZone: "Europe/Rome", + isDefault: true, + }; + await schedulesService.createUserSchedule(organizerUser.id, schedule); + + const eventType = await eventTypesRepositoryFixture.create( + { + title: `add-attendee-2024-08-13-event-type-${randomString()}`, + slug: `add-attendee-2024-08-13-event-type-${randomString()}`, + length: 60, + }, + organizerUser.id + ); + + testSetup = { + organizer: { + user: organizerUser, + accessToken: organizerTokens.accessToken, + refreshToken: organizerTokens.refreshToken, + }, + unrelatedUser: { + user: unrelatedUserData, + accessToken: unrelatedUserTokens.accessToken, + refreshToken: unrelatedUserTokens.refreshToken, + }, + eventTypeId: eventType.id, + bookingUid: "", + bookingId: 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 () => { + attendeeAddGuestsEmailSpy.mockClear(); + organizerAddGuestsEmailSpy.mockClear(); + attendeeScheduledEmailSpy.mockClear(); + }); + + describe("POST /v2/bookings/:bookingUid/attendees", () => { + beforeAll(async () => { + const createBookingBody: CreateBookingInput_2024_08_13 = { + start: new Date(Date.UTC(2030, 0, 10, 13, 0, 0)).toISOString(), + eventTypeId: testSetup.eventTypeId, + attendee: { + name: "Original Attendee", + email: "original.attendee@gmail.com", + timeZone: "Europe/Rome", + language: "it", + }, + location: "https://meet.google.com/abc-def-ghi", + bookingFieldsResponses: { + customField: "customValue", + }, + metadata: { + userId: "100", + }, + }; + + const createBookingResponse = await request(app.getHttpServer()) + .post("/v2/bookings") + .send(createBookingBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .expect(201); + + const createBookingResponseBody: CreateBookingOutput_2024_08_13 = createBookingResponse.body; + expect(createBookingResponseBody.status).toEqual(SUCCESS_STATUS); + + if (!responseDataIsBooking(createBookingResponseBody.data)) { + throw new Error( + "Invalid response data - expected booking but received array of possibly recurring bookings" + ); + } + + testSetup.bookingUid = createBookingResponseBody.data.uid; + testSetup.bookingId = createBookingResponseBody.data.id; + }); + + describe("Authentication", () => { + it("should return 401 when adding attendee without authentication", async () => { + const addAttendeeBody = { + email: "unauthenticated.attendee@example.com", + name: "Unauthenticated Attendee", + timeZone: "Europe/London", + }; + + const response = await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13); + + expect(response.status).toBe(401); + }); + }); + + describe("Authorization", () => { + it("should allow booking organizer to add an attendee", async () => { + const addAttendeeBody = { + email: "new.attendee@example.com", + name: "New Attendee", + timeZone: "Europe/London", + }; + + const response = await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.organizer.accessToken}`) + .expect(201); + + const responseBody: AddAttendeeOutput_2024_08_13 = response.body; + expect(responseBody.status).toEqual(SUCCESS_STATUS); + expect(responseBody.data).toBeDefined(); + expect(responseBody.data.email).toEqual(addAttendeeBody.email); + expect(responseBody.data.name).toEqual(addAttendeeBody.name); + expect(responseBody.data.timeZone).toEqual(addAttendeeBody.timeZone); + expect(responseBody.data.bookingId).toEqual(testSetup.bookingId); + expect(responseBody.data.id).toBeDefined(); + }); + + it("should return 403 when unrelated user tries to add attendee", async () => { + const addAttendeeBody = { + email: "unauthorized.attendee@example.com", + name: "Unauthorized Attendee", + timeZone: "America/New_York", + }; + + await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.unrelatedUser.accessToken}`) + .expect(403); + }); + }); + + describe("Response format", () => { + it("should return attendee with correct structure", async () => { + const addAttendeeBody = { + email: "structure.test@example.com", + name: "Structure Test Attendee", + timeZone: "Asia/Tokyo", + }; + + const response = await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.organizer.accessToken}`) + .expect(201); + + const responseBody: AddAttendeeOutput_2024_08_13 = response.body; + + expect(responseBody).toHaveProperty("status", SUCCESS_STATUS); + expect(responseBody).toHaveProperty("data"); + expect(responseBody.data).toHaveProperty("id"); + expect(responseBody.data).toHaveProperty("bookingId"); + expect(responseBody.data).toHaveProperty("name"); + expect(responseBody.data).toHaveProperty("email"); + expect(responseBody.data).toHaveProperty("timeZone"); + + expect(typeof responseBody.data.id).toBe("number"); + expect(typeof responseBody.data.bookingId).toBe("number"); + expect(typeof responseBody.data.name).toBe("string"); + expect(typeof responseBody.data.email).toBe("string"); + expect(typeof responseBody.data.timeZone).toBe("string"); + }); + }); + + describe("Validation", () => { + it("should return 400 when email is missing", async () => { + const addAttendeeBody = { + name: "No Email Attendee", + timeZone: "Europe/London", + }; + + await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.organizer.accessToken}`) + .expect(400); + }); + + it("should return 400 when email is invalid", async () => { + const addAttendeeBody = { + email: "invalid-email", + name: "Invalid Email Attendee", + timeZone: "Europe/London", + }; + + await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.organizer.accessToken}`) + .expect(400); + }); + + it("should return 400 when name is missing", async () => { + const addAttendeeBody = { + email: "no.name@example.com", + timeZone: "Europe/London", + }; + + await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.organizer.accessToken}`) + .expect(400); + }); + + it("should return 400 when timeZone is missing", async () => { + const addAttendeeBody = { + email: "no.timezone@example.com", + name: "No TimeZone Attendee", + }; + + await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.organizer.accessToken}`) + .expect(400); + }); + + it("should return 400 when timeZone is invalid", async () => { + const addAttendeeBody = { + email: "invalid.timezone@example.com", + name: "Invalid TimeZone Attendee", + timeZone: "Invalid/TimeZone", + }; + + await request(app.getHttpServer()) + .post(`/v2/bookings/${testSetup.bookingUid}/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.organizer.accessToken}`) + .expect(400); + }); + + it("should return 403 when booking does not exist", async () => { + const addAttendeeBody = { + email: "nonexistent.booking@example.com", + name: "Nonexistent Booking Attendee", + timeZone: "Europe/London", + }; + + await request(app.getHttpServer()) + .post(`/v2/bookings/non-existent-booking-uid/attendees`) + .send(addAttendeeBody) + .set(CAL_API_VERSION_HEADER, VERSION_2024_08_13) + .set("Authorization", `Bearer ${testSetup.organizer.accessToken}`) + .expect(403); + }); + }); + }); + + afterAll(async () => { + await teamRepositoryFixture.delete(organization.id); + + await userRepositoryFixture.deleteByEmail(testSetup.organizer.user.email); + await userRepositoryFixture.deleteByEmail(testSetup.unrelatedUser.user.email); + + await bookingsRepositoryFixture.deleteAllBookings( + testSetup.organizer.user.id, + testSetup.organizer.user.email + ); + + await app.close(); + }); + + function responseDataIsBooking(data: unknown): data is BookingOutput_2024_08_13 { + return !Array.isArray(data) && typeof data === "object" && data !== null && "id" in data; + } +}); diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/outputs/add-attendee.output.ts b/apps/api/v2/src/ee/bookings/2024-08-13/outputs/add-attendee.output.ts new file mode 100644 index 0000000000..28b4968a32 --- /dev/null +++ b/apps/api/v2/src/ee/bookings/2024-08-13/outputs/add-attendee.output.ts @@ -0,0 +1,28 @@ +import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants"; +import { BookingAttendee } from "@calcom/platform-types"; +import { ApiProperty } from "@nestjs/swagger"; +import { Expose, Type } from "class-transformer"; +import { IsEnum, IsNumber, ValidateNested } from "class-validator"; + +export class BookingAttendeeOutput_2024_08_13 extends BookingAttendee { + @ApiProperty({ type: Number, example: 251 }) + @IsNumber() + @Expose() + id!: number; + + @ApiProperty({ type: Number, example: 313 }) + @IsNumber() + @Expose() + bookingId!: number; +} + +export class AddAttendeeOutput_2024_08_13 { + @ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] }) + @IsEnum([SUCCESS_STATUS, ERROR_STATUS]) + status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS; + + @ApiProperty({ type: BookingAttendeeOutput_2024_08_13 }) + @ValidateNested() + @Type(() => BookingAttendeeOutput_2024_08_13) + data!: BookingAttendeeOutput_2024_08_13; +} diff --git a/apps/api/v2/src/ee/bookings/2024-08-13/services/booking-attendees.service.ts b/apps/api/v2/src/ee/bookings/2024-08-13/services/booking-attendees.service.ts new file mode 100644 index 0000000000..88e22bd2b1 --- /dev/null +++ b/apps/api/v2/src/ee/bookings/2024-08-13/services/booking-attendees.service.ts @@ -0,0 +1,76 @@ +import { BookingAttendeesService } from "@calcom/platform-libraries/bookings"; +import type { AddAttendeeInput_2024_08_13 } from "@calcom/platform-types"; +import { HttpException, Injectable, NotFoundException } from "@nestjs/common"; +import { plainToClass } from "class-transformer"; +import { BookingAttendeeOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-attendee.output"; +import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository"; +import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service"; +import type { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy"; + +@Injectable() +export class BookingAttendeesService_2024_08_13 { + private bookingAttendeesService: BookingAttendeesService; + + constructor( + private readonly bookingsRepository: BookingsRepository_2024_08_13, + private readonly platformBookingsService: PlatformBookingsService + ) { + this.bookingAttendeesService = new BookingAttendeesService(); + } + + async addAttendee( + bookingUid: string, + input: AddAttendeeInput_2024_08_13, + user: ApiAuthGuardUser + ): Promise { + const booking = await this.bookingsRepository.getByUidWithEventType(bookingUid); + if (!booking) { + throw new NotFoundException(`Booking with uid ${bookingUid} not found`); + } + + const platformClientParams = booking.eventTypeId + ? await this.platformBookingsService.getOAuthClientParams(booking.eventTypeId) + : undefined; + + const emailsEnabled = platformClientParams ? platformClientParams.arePlatformEmailsEnabled : true; + + const createdAttendee = await this.bookingAttendeesService.addAttendee({ + bookingId: booking.id, + attendee: { + email: input.email, + name: input.name, + timeZone: input.timeZone, + phoneNumber: input.phoneNumber, + language: input.language, + }, + user: { + id: user.id, + email: user.email, + organizationId: user.organizationId, + uuid: user.uuid, + }, + emailsEnabled, + actionSource: "API_V2", + }); + + return plainToClass( + BookingAttendeeOutput_2024_08_13, + { + id: createdAttendee.id, + bookingId: createdAttendee.bookingId, + name: createdAttendee.name, + email: createdAttendee.email, + displayEmail: this.getDisplayEmail(createdAttendee.email), + timeZone: createdAttendee.timeZone, + language: createdAttendee.locale ?? undefined, + absent: false, + phoneNumber: createdAttendee.phoneNumber ?? undefined, + }, + { strategy: "excludeAll" } + ); + } + + private getDisplayEmail(email: string): string { + return email.replace(/\+[a-zA-Z0-9]{25}/, ""); + } +} diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json index 5d96943608..4479a9788e 100644 --- a/apps/web/public/static/locales/en/common.json +++ b/apps/web/public/static/locales/en/common.json @@ -1549,6 +1549,8 @@ "new_guests_added": "Added - New guests added to your event", "location_changed_event_type_subject": "Location Changed: {{eventType}} with {{name}} at {{date}}", "guests_added_event_type_subject": "Guests Added: {{eventType}} with {{name}} at {{date}}", + "new_attendee_added": "Added - New attendee added to your event", + "attendee_added_event_type_subject": "Attendee Added: {{eventType}} with {{name}} at {{date}}", "current_location": "Current location", "new_location": "New location", "session": "Session", diff --git a/packages/emails/email-manager.ts b/packages/emails/email-manager.ts index ed5af1d773..6e00457310 100644 --- a/packages/emails/email-manager.ts +++ b/packages/emails/email-manager.ts @@ -1,6 +1,3 @@ -import { default as cloneDeep } from "lodash/cloneDeep"; -import type { z } from "zod"; - import dayjs from "@calcom/dayjs"; import type BaseEmail from "@calcom/emails/templates/_base-email"; import type { EventNameObjectType } from "@calcom/features/eventtypes/lib/eventNaming"; @@ -13,7 +10,8 @@ import { withReporting } from "@calcom/lib/sentryWrapper"; import { prisma } from "@calcom/prisma"; import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils"; import type { CalendarEvent, Person } from "@calcom/types/Calendar"; - +import { default as cloneDeep } from "lodash/cloneDeep"; +import type { z } from "zod"; import AwaitingPaymentSMS from "../sms/attendee/awaiting-payment-sms"; import CancelledSeatSMS from "../sms/attendee/cancelled-seat-sms"; import EventCancelledSMS from "../sms/attendee/event-cancelled-sms"; @@ -35,6 +33,7 @@ import AttendeeRescheduledEmail from "./templates/attendee-rescheduled-email"; import AttendeeScheduledEmail from "./templates/attendee-scheduled-email"; import AttendeeUpdatedEmail from "./templates/attendee-updated-email"; import AttendeeWasRequestedToRescheduleEmail from "./templates/attendee-was-requested-to-reschedule-email"; +import OrganizerAddAttendeeEmail from "./templates/organizer-add-attendee-email"; import OrganizerAddGuestsEmail from "./templates/organizer-add-guests-email"; import OrganizerAttendeeCancelledSeatEmail from "./templates/organizer-attendee-cancelled-seat-email"; import OrganizerCancelledEmail from "./templates/organizer-cancelled-email"; @@ -770,3 +769,52 @@ export const sendAddGuestsEmailsAndSMS = async (args: { await Promise.all(emailsAndSMSToSend); }; + +export const sendAddAttendeeEmailsAndSMS = async (args: { + calEvent: CalendarEvent; + newAttendees: string[]; + eventTypeMetadata?: EventTypeMetadata; +}) => { + const { calEvent, newAttendees, eventTypeMetadata } = args; + const calendarEvent = formatCalEvent(calEvent); + + const emailsAndSMSToSend: Promise[] = []; + + if (!eventTypeDisableHostEmail(eventTypeMetadata)) { + emailsAndSMSToSend.push(sendEmail(() => new OrganizerAddAttendeeEmail({ calEvent: calendarEvent }))); + + if (calendarEvent.team?.members) { + for (const teamMember of calendarEvent.team.members) { + emailsAndSMSToSend.push( + sendEmail(() => new OrganizerAddAttendeeEmail({ calEvent: calendarEvent, teamMember })) + ); + } + } + } + + const eventScheduledSMS = new EventSuccessfullyScheduledSMS(calEvent); + const organizationSettings = await fetchOrganizationEmailSettings(calEvent.organizationId); + + for (const attendee of calendarEvent.attendees) { + if (newAttendees.includes(attendee.email)) { + // new attendees get confirmation emails + if ( + !shouldSkipAttendeeEmailWithSettings(eventTypeMetadata, organizationSettings, EmailType.CONFIRMATION) + ) { + emailsAndSMSToSend.push(sendEmail(() => new AttendeeScheduledEmail(calendarEvent, attendee))); + + if (attendee.phoneNumber) { + emailsAndSMSToSend.push(eventScheduledSMS.sendSMSToAttendee(attendee)); + } + } + } else { + if ( + !shouldSkipAttendeeEmailWithSettings(eventTypeMetadata, organizationSettings, EmailType.NEW_EVENT) + ) { + emailsAndSMSToSend.push(sendEmail(() => new AttendeeAddGuestsEmail(calendarEvent, attendee))); + } + } + } + + await Promise.all(emailsAndSMSToSend); +}; diff --git a/packages/emails/src/templates/OrganizerAddAttendeeEmail.tsx b/packages/emails/src/templates/OrganizerAddAttendeeEmail.tsx new file mode 100644 index 0000000000..3825886d44 --- /dev/null +++ b/packages/emails/src/templates/OrganizerAddAttendeeEmail.tsx @@ -0,0 +1,11 @@ +import { OrganizerScheduledEmail } from "./OrganizerScheduledEmail"; + +export const OrganizerAddAttendeeEmail = (props: React.ComponentProps) => ( + +); diff --git a/packages/emails/src/templates/index.ts b/packages/emails/src/templates/index.ts index 60a49b09e2..c14ac317b7 100644 --- a/packages/emails/src/templates/index.ts +++ b/packages/emails/src/templates/index.ts @@ -29,6 +29,7 @@ export { OrgAutoInviteEmail } from "./OrgAutoInviteEmail"; export { OrganisationAccountVerifyEmail } from "./OrganizationAccountVerifyEmail"; export { OrganizationAdminNoSlotsEmail } from "./OrganizationAdminNoSlots"; export { OrganizationCreationEmail } from "./OrganizationCreationEmail"; +export { OrganizerAddAttendeeEmail } from "./OrganizerAddAttendeeEmail"; export { OrganizerAddGuestsEmail } from "./OrganizerAddGuestsEmail"; export { OrganizerAttendeeCancelledSeatEmail } from "./OrganizerAttendeeCancelledSeatEmail"; export { OrganizerCancelledEmail } from "./OrganizerCancelledEmail"; diff --git a/packages/emails/templates/organizer-add-attendee-email.ts b/packages/emails/templates/organizer-add-attendee-email.ts new file mode 100644 index 0000000000..98b54d2226 --- /dev/null +++ b/packages/emails/templates/organizer-add-attendee-email.ts @@ -0,0 +1,40 @@ +import { APP_NAME } from "@calcom/lib/constants"; +import { getReplyToHeader } from "@calcom/lib/getReplyToHeader"; +import generateIcsFile, { GenerateIcsRole } from "../lib/generateIcsFile"; +import renderEmail from "../src/renderEmail"; +import OrganizerScheduledEmail from "./organizer-scheduled-email"; + +export default class OrganizerAddAttendeeEmail extends OrganizerScheduledEmail { + async getHtml() { + return await renderEmail("OrganizerAddAttendeeEmail", { + attendee: this.calEvent.organizer, + calEvent: this.calEvent, + }); + } + + protected async getNodeMailerPayload(): Promise> { + const toAddresses = [this.teamMember?.email || this.calEvent.organizer.email]; + + return { + icalEvent: generateIcsFile({ + calEvent: this.calEvent, + role: GenerateIcsRole.ORGANIZER, + status: "CONFIRMED", + }), + from: `${APP_NAME} <${this.getMailerOptions().from}>`, + to: toAddresses.join(","), + ...getReplyToHeader( + this.calEvent, + this.calEvent.attendees.map(({ email }) => email), + true + ), + subject: `${this.t("attendee_added_event_type_subject", { + eventType: this.calEvent.type, + name: this.calEvent.attendees[0].name, + date: this.getFormattedDate(), + })}`, + html: await this.getHtml(), + text: this.getTextBody("new_attendee_added"), + }; + } +} diff --git a/packages/features/bookings/lib/BookingEmailSmsHandler.ts b/packages/features/bookings/lib/BookingEmailSmsHandler.ts index 4071dc53df..6add256673 100644 --- a/packages/features/bookings/lib/BookingEmailSmsHandler.ts +++ b/packages/features/bookings/lib/BookingEmailSmsHandler.ts @@ -1,10 +1,7 @@ -import { default as cloneDeep } from "lodash/cloneDeep"; -import type { Logger } from "tslog"; - import dayjs from "@calcom/dayjs"; import { - allowDisablingHostConfirmationEmails, allowDisablingAttendeeConfirmationEmails, + allowDisablingHostConfirmationEmails, } from "@calcom/ee/workflows/lib/allowDisablingStandardEmails"; import type { Workflow as WorkflowType } from "@calcom/ee/workflows/lib/types"; import type { BookingType } from "@calcom/features/bookings/lib/handleNewBooking/originalRescheduledBookingUtils"; @@ -17,6 +14,8 @@ import type { Prisma, User } from "@calcom/prisma/client"; import type { SchedulingType } from "@calcom/prisma/enums"; import type { EventTypeMetadata } from "@calcom/prisma/zod-utils"; import type { AdditionalInformation, CalendarEvent, Person } from "@calcom/types/Calendar"; +import { default as cloneDeep } from "lodash/cloneDeep"; +import type { Logger } from "tslog"; export const BookingActionMap = { confirmed: "BOOKING_CONFIRMED", @@ -362,4 +361,29 @@ export class BookingEmailSmsHandler { this.log.error("Failed to send add guests related emails and SMS", err); } } + + public async handleAddAttendee(data: AddGuestsEmailAndSmsPayload) { + const { + evt, + eventType: { metadata }, + newGuests, + } = data; + + this.log.debug( + "Action: ADD_ATTENDEE. Sending add attendee emails and SMS.", + safeStringify({ calEvent: getPiiFreeCalendarEvent(evt) }) + ); + + const { sendAddAttendeeEmailsAndSMS } = await import("@calcom/emails/email-manager"); + + try { + await sendAddAttendeeEmailsAndSMS({ + calEvent: evt, + newAttendees: newGuests, + eventTypeMetadata: metadata, + }); + } catch (err) { + this.log.error("Failed to send add attendee related emails and SMS", err); + } + } } diff --git a/packages/features/bookings/repositories/BookingRepository.ts b/packages/features/bookings/repositories/BookingRepository.ts index cbf6a66896..f5a935725e 100644 --- a/packages/features/bookings/repositories/BookingRepository.ts +++ b/packages/features/bookings/repositories/BookingRepository.ts @@ -1818,7 +1818,13 @@ export class BookingRepository implements IBookingRepository { updatedResponses, }: { bookingId: number; - newAttendees: { name: string; email: string; timeZone: string; locale: string | null }[]; + newAttendees: { + name: string; + email: string; + timeZone: string; + locale: string | null; + phoneNumber?: string | null; + }[]; updatedResponses: Prisma.InputJsonValue; }) { return await this.prismaClient.booking.update({ diff --git a/packages/features/bookings/services/BookingAttendeesService.ts b/packages/features/bookings/services/BookingAttendeesService.ts new file mode 100644 index 0000000000..271148c383 --- /dev/null +++ b/packages/features/bookings/services/BookingAttendeesService.ts @@ -0,0 +1,143 @@ +import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils"; +import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor"; +import type { ActionSource } from "@calcom/features/booking-audit/lib/types/actionSource"; +import { getBookingEventHandlerService } from "@calcom/features/bookings/di/BookingEventHandlerService.container"; +import { BookingEmailSmsHandler } from "@calcom/features/bookings/lib/BookingEmailSmsHandler"; +import { getFeaturesRepository } from "@calcom/features/di/containers/FeaturesRepository"; +import logger from "@calcom/lib/logger"; +import type { Booking, TUser } from "@calcom/trpc/server/routers/viewer/bookings/addGuests.handler"; +import { + buildCalendarEvent, + getBooking, + getOrganizerData, + prepareAttendeesList, + sanitizeAndFilterGuests, + updateBookingAttendees, + updateCalendarEvent, + validateGuestsFieldEnabled, + validateUserPermissions, +} from "@calcom/trpc/server/routers/viewer/bookings/addGuests.handler"; +import type { TAddGuestsInputSchema } from "@calcom/trpc/server/routers/viewer/bookings/addGuests.schema"; +import type { CalendarEvent } from "@calcom/types/Calendar"; + +type Attendee = TAddGuestsInputSchema["guests"][number]; + +type AddAttendeeInput = { + bookingId: number; + attendee: Attendee; + user: TUser; + emailsEnabled?: boolean; + actionSource: ActionSource; +}; + +export type CreatedAttendee = { + id: number; + bookingId: number; + email: string; + name: string; + timeZone: string; + locale: string | null; + phoneNumber: string | null; +}; + +export class BookingAttendeesService { + async addAttendee({ + bookingId, + attendee, + user, + emailsEnabled = true, + actionSource, + }: AddAttendeeInput): Promise { + const booking = await getBooking(bookingId); + + await validateUserPermissions(booking, user); + + validateGuestsFieldEnabled(booking); + + const organizer = await getOrganizerData(booking.userId); + + const validatedAttendees = await sanitizeAndFilterGuests([attendee], booking); + + const newAttendeeDetails = validatedAttendees.map((a) => ({ + name: a.name || "", + email: a.email, + timeZone: a.timeZone || organizer.timeZone, + locale: a.language || organizer.locale, + phoneNumber: a.phoneNumber || null, + })); + + const attendeeEmail = attendee.email; + + const updatedBooking = await updateBookingAttendees( + bookingId, + newAttendeeDetails, + [attendeeEmail], + booking + ); + + const allAttendees = await prepareAttendeesList(updatedBooking.attendees); + + const evt = await buildCalendarEvent(booking, organizer, allAttendees); + + await updateCalendarEvent(booking, evt); + + if (emailsEnabled) { + await this.sendAttendeeNotification(evt, booking, attendeeEmail); + } + + const bookingEventHandlerService = getBookingEventHandlerService(); + const featuresRepository = getFeaturesRepository(); + const organizationId = user.organizationId ?? null; + const isBookingAuditEnabled = organizationId + ? await featuresRepository.checkIfTeamHasFeature(organizationId, "booking-audit") + : false; + + await bookingEventHandlerService.onAttendeeAdded({ + bookingUid: booking.uid, + actor: makeUserActor(user.uuid), + organizationId, + source: actionSource, + auditData: { + added: [attendeeEmail], + }, + isBookingAuditEnabled, + }); + + const createdAttendee = updatedBooking.attendees.find( + (a) => a.email.toLowerCase() === attendeeEmail.toLowerCase() + ); + + if (!createdAttendee) { + throw new Error("Attendee was created but could not be found"); + } + + return { + id: createdAttendee.id, + bookingId, + email: createdAttendee.email, + name: createdAttendee.name, + timeZone: createdAttendee.timeZone, + locale: createdAttendee.locale, + phoneNumber: createdAttendee.phoneNumber, + }; + } + + private async sendAttendeeNotification( + evt: CalendarEvent, + booking: Booking, + attendeeEmail: string + ): Promise { + const emailsAndSmsHandler = new BookingEmailSmsHandler({ + logger: logger, + }); + + await emailsAndSmsHandler.handleAddAttendee({ + evt, + eventType: { + metadata: eventTypeMetaDataSchemaWithTypedApps.parse(booking?.eventType?.metadata), + schedulingType: booking.eventType?.schedulingType || null, + }, + newGuests: [attendeeEmail], + }); + } +} diff --git a/packages/platform/libraries/bookings.ts b/packages/platform/libraries/bookings.ts index 0ffcea6205..babd10aa20 100644 --- a/packages/platform/libraries/bookings.ts +++ b/packages/platform/libraries/bookings.ts @@ -1,22 +1,23 @@ -export { LuckyUserService } from "@calcom/features/bookings/lib/getLuckyUser"; +export { getAuditActorRepository } from "@calcom/features/booking-audit/di/AuditActorRepository.container"; +export { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor"; +export { BookingAuditTaskerProducerService } from "@calcom/features/booking-audit/lib/service/BookingAuditTaskerProducerService"; +export { BookingEmailSmsHandler } from "@calcom/features/bookings/lib/BookingEmailSmsHandler"; export { CheckBookingLimitsService } from "@calcom/features/bookings/lib/checkBookingLimits"; -export { CheckBookingAndDurationLimitsService } from "@calcom/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits"; -export { RegularBookingService } from "@calcom/features/bookings/lib/service/RegularBookingService"; -export { RecurringBookingService } from "@calcom/features/bookings/lib/service/RecurringBookingService"; -export { InstantBookingCreateService } from "@calcom/features/bookings/lib/service/InstantBookingCreateService"; -export { BookingEventHandlerService } from "@calcom/features/bookings/lib/onBookingEvents/BookingEventHandlerService"; -export { BookingCancelService } from "@calcom/features/bookings/lib/handleCancelBooking"; export type { InstantBookingCreateResult, RegularBookingCreateResult, } from "@calcom/features/bookings/lib/dto/types"; +export { LuckyUserService } from "@calcom/features/bookings/lib/getLuckyUser"; +export { BookingCancelService } from "@calcom/features/bookings/lib/handleCancelBooking"; +export { CheckBookingAndDurationLimitsService } from "@calcom/features/bookings/lib/handleNewBooking/checkBookingAndDurationLimits"; +export { BookingEventHandlerService } from "@calcom/features/bookings/lib/onBookingEvents/BookingEventHandlerService"; +export { InstantBookingCreateService } from "@calcom/features/bookings/lib/service/InstantBookingCreateService"; +export { RecurringBookingService } from "@calcom/features/bookings/lib/service/RecurringBookingService"; +export { RegularBookingService } from "@calcom/features/bookings/lib/service/RegularBookingService"; +export { BookingEmailAndSmsSyncTasker } from "@calcom/features/bookings/lib/tasker/BookingEmailAndSmsSyncTasker"; +export { BookingEmailAndSmsTasker } from "@calcom/features/bookings/lib/tasker/BookingEmailAndSmsTasker"; +export { BookingEmailAndSmsTaskService } from "@calcom/features/bookings/lib/tasker/BookingEmailAndSmsTaskService"; +export { BookingEmailAndSmsTriggerDevTasker } from "@calcom/features/bookings/lib/tasker/BookingEmailAndSmsTriggerTasker"; +export { BookingAttendeesService } from "@calcom/features/bookings/services/BookingAttendeesService"; export { PrismaOrgMembershipRepository } from "@calcom/features/membership/repositories/PrismaOrgMembershipRepository"; export { addGuestsHandler } from "@calcom/trpc/server/routers/viewer/bookings/addGuests.handler"; -export { BookingEmailAndSmsTaskService } from "@calcom/features/bookings/lib/tasker/BookingEmailAndSmsTaskService"; -export { BookingEmailAndSmsSyncTasker } from "@calcom/features/bookings/lib/tasker/BookingEmailAndSmsSyncTasker"; -export { BookingEmailAndSmsTriggerDevTasker } from "@calcom/features/bookings/lib/tasker/BookingEmailAndSmsTriggerTasker"; -export { BookingEmailAndSmsTasker } from "@calcom/features/bookings/lib/tasker/BookingEmailAndSmsTasker"; -export { BookingEmailSmsHandler } from "@calcom/features/bookings/lib/BookingEmailSmsHandler"; -export { BookingAuditTaskerProducerService } from "@calcom/features/booking-audit/lib/service/BookingAuditTaskerProducerService"; -export { getAuditActorRepository } from "@calcom/features/booking-audit/di/AuditActorRepository.container"; -export { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor"; diff --git a/packages/platform/types/bookings/2024-08-13/inputs/add-attendee.input.ts b/packages/platform/types/bookings/2024-08-13/inputs/add-attendee.input.ts new file mode 100644 index 0000000000..42152e4257 --- /dev/null +++ b/packages/platform/types/bookings/2024-08-13/inputs/add-attendee.input.ts @@ -0,0 +1,13 @@ +import { ApiProperty } from "@nestjs/swagger"; +import { IsEmail } from "class-validator"; +import { BaseBookingAttendee } from "./create-booking.input"; + +export class AddAttendeeInput_2024_08_13 extends BaseBookingAttendee { + @ApiProperty({ + type: String, + description: "The email of the attendee.", + example: "john.doe@example.com", + }) + @IsEmail() + email!: string; +} diff --git a/packages/platform/types/bookings/2024-08-13/inputs/create-booking.input.ts b/packages/platform/types/bookings/2024-08-13/inputs/create-booking.input.ts index b25971ea82..00e4b186de 100644 --- a/packages/platform/types/bookings/2024-08-13/inputs/create-booking.input.ts +++ b/packages/platform/types/bookings/2024-08-13/inputs/create-booking.input.ts @@ -8,25 +8,24 @@ import { import { Transform, Type } from "class-transformer"; import type { ValidationArguments, ValidationOptions } from "class-validator"; import { - IsInt, - IsDateString, - IsTimeZone, - IsEnum, - ValidateNested, IsArray, - IsString, - isEmail, - IsOptional, - IsUrl, - IsObject, IsBoolean, + IsDateString, + IsDefined, + IsEnum, + IsInt, + IsObject, + IsOptional, + IsString, + IsTimeZone, + IsUrl, + isEmail, Min, registerDecorator, Validate, - IsDefined, + ValidateNested, } from "class-validator"; import { isValidPhoneNumber } from "libphonenumber-js/max"; - import type { BookingLanguageType } from "./language"; import { BookingLanguage } from "./language"; import type { BookingInputLocation_2024_08_13 } from "./location.input"; @@ -37,8 +36,8 @@ import { BookingInputAttendeePhoneLocation_2024_08_13, BookingInputIntegrationLocation_2024_08_13, BookingInputLinkLocation_2024_08_13, - BookingInputPhoneLocation_2024_08_13, BookingInputOrganizersDefaultAppLocation_2024_08_13, + BookingInputPhoneLocation_2024_08_13, ValidateBookingLocation_2024_08_13, } from "./location.input"; import { ValidateMetadata } from "./validators/validate-metadata"; @@ -48,7 +47,7 @@ export const FAILED_EVENT_TYPE_IDENTIFICATION_ERROR_MESSAGE = function RequireEventTypeIdentification(validationOptions?: ValidationOptions) { // eslint-disable-next-line @typescript-eslint/no-explicit-any - return function (object: any) { + return (object: any) => { registerDecorator({ name: "requireEventTypeIdentification", target: object, @@ -77,7 +76,7 @@ function RequireEventTypeIdentification(validationOptions?: ValidationOptions) { function RequireEmailOrPhone(validationOptions?: ValidationOptions) { // eslint-disable-next-line @typescript-eslint/no-explicit-any - return function (object: any) { + return (object: any) => { registerDecorator({ name: "requireEmailOrPhone", target: object, @@ -100,8 +99,7 @@ function RequireEmailOrPhone(validationOptions?: ValidationOptions) { }; } -@RequireEmailOrPhone() -class CreateBookingAttendee { +export class BaseBookingAttendee { @ApiProperty({ type: String, description: "The name of the attendee.", @@ -110,17 +108,6 @@ class CreateBookingAttendee { @IsString() name!: string; - @ApiPropertyOptional({ - type: String, - description: "The email of the attendee.", - example: "john.doe@example.com", - }) - @IsOptional() - @Validate((value: string) => !value || isEmail(value), { - message: "Invalid email format", - }) - email?: string; - @ApiProperty({ type: String, description: "The time zone of the attendee.", @@ -151,6 +138,20 @@ class CreateBookingAttendee { language?: BookingLanguageType; } +@RequireEmailOrPhone() +export class CreateBookingAttendee extends BaseBookingAttendee { + @ApiPropertyOptional({ + type: String, + description: "The email of the attendee.", + example: "john.doe@example.com", + }) + @IsOptional() + @Validate((value: string) => !value || isEmail(value), { + message: "Invalid email format", + }) + email?: string; +} + class Routing { @ApiProperty({ type: Number, diff --git a/packages/platform/types/bookings/2024-08-13/inputs/index.ts b/packages/platform/types/bookings/2024-08-13/inputs/index.ts index 59995ecae9..773576968e 100644 --- a/packages/platform/types/bookings/2024-08-13/inputs/index.ts +++ b/packages/platform/types/bookings/2024-08-13/inputs/index.ts @@ -1,14 +1,15 @@ +export * from "./add-attendee.input"; +export * from "./add-guests.input"; +export * from "./cancel-booking.input"; +export * from "./cancel-booking-input.pipe"; export * from "./create-booking.input"; export * from "./create-booking-input.pipe"; +export * from "./decline-booking.input"; export * from "./get-bookings.input"; -export * from "./reschedule-booking.input"; -export * from "./cancel-booking.input"; +export * from "./location.input"; export * from "./mark-absent.input"; export * from "./reassign-to-user.input"; +export * from "./reschedule-booking.input"; export * from "./reschedule-booking-input.pipe"; -export * from "./cancel-booking-input.pipe"; -export * from "./decline-booking.input"; -export * from "./validators/validate-metadata"; -export * from "./add-guests.input"; export * from "./update-location.input"; -export * from "./location.input"; +export * from "./validators/validate-metadata"; diff --git a/packages/platform/types/bookings/2024-08-13/outputs/booking.output.ts b/packages/platform/types/bookings/2024-08-13/outputs/booking.output.ts index ddcaa4bcaf..2d66174429 100644 --- a/packages/platform/types/bookings/2024-08-13/outputs/booking.output.ts +++ b/packages/platform/types/bookings/2024-08-13/outputs/booking.output.ts @@ -4,21 +4,20 @@ import { IsArray, IsBoolean, IsDateString, + IsEmail, IsEnum, IsInt, IsObject, IsOptional, IsString, - IsEmail, IsTimeZone, IsUrl, ValidateNested, } from "class-validator"; - import type { BookingLanguageType } from "../inputs/language"; import { BookingLanguage } from "../inputs/language"; -class BookingAttendee { +export class BookingAttendee { @ApiProperty({ type: String, example: "John Doe" }) @IsString() @Expose() @@ -100,7 +99,11 @@ class BookingHost { @Expose() email!: string; - @ApiProperty({ type: String, example: "jane100@example.com", description: "Clean email for display purposes" }) + @ApiProperty({ + type: String, + example: "jane100@example.com", + description: "Clean email for display purposes", + }) @IsString() @Expose() displayEmail!: string; @@ -406,7 +409,11 @@ class ReassignedToDto { @Expose() email!: string; - @ApiProperty({ type: String, example: "john.doe@example.com", description: "Clean email for display purposes" }) + @ApiProperty({ + type: String, + example: "john.doe@example.com", + description: "Clean email for display purposes", + }) @IsString() @Expose() displayEmail!: string; diff --git a/packages/trpc/server/routers/viewer/bookings/addGuests.handler.ts b/packages/trpc/server/routers/viewer/bookings/addGuests.handler.ts index abda8a55ad..cda0198ce9 100644 --- a/packages/trpc/server/routers/viewer/bookings/addGuests.handler.ts +++ b/packages/trpc/server/routers/viewer/bookings/addGuests.handler.ts @@ -4,10 +4,10 @@ import dayjs from "@calcom/dayjs"; import { makeUserActor } from "@calcom/features/booking-audit/lib/makeActor"; import type { ActionSource } from "@calcom/features/booking-audit/lib/types/actionSource"; import { getBookingEventHandlerService } from "@calcom/features/bookings/di/BookingEventHandlerService.container"; -import { getFeaturesRepository } from "@calcom/features/di/containers/FeaturesRepository"; import { BookingEmailSmsHandler } from "@calcom/features/bookings/lib/BookingEmailSmsHandler"; import EventManager from "@calcom/features/bookings/lib/EventManager"; import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository"; +import { getFeaturesRepository } from "@calcom/features/di/containers/FeaturesRepository"; import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service"; import { UserRepository } from "@calcom/features/users/repositories/UserRepository"; import { extractBaseEmail } from "@calcom/lib/extract-base-email"; @@ -19,13 +19,14 @@ import { MembershipRole } from "@calcom/prisma/enums"; import type { BookingResponses } from "@calcom/prisma/zod-utils"; import { eventTypeBookingFields } from "@calcom/prisma/zod-utils"; import type { CalendarEvent } from "@calcom/types/Calendar"; - import { TRPCError } from "@trpc/server"; - import type { TrpcSessionUser } from "../../../types"; import type { TAddGuestsInputSchema } from "./addGuests.schema"; -type TUser = Pick, "id" | "email" | "organizationId" | "uuid"> & +export type TUser = Pick< + NonNullable, + "id" | "email" | "organizationId" | "uuid" +> & Partial, "profile">>; type AddGuestsOptions = { @@ -37,8 +38,10 @@ type AddGuestsOptions = { actionSource: ActionSource; }; -type Booking = NonNullable>>; -type OrganizerData = Awaited>; +export type Booking = NonNullable< + Awaited> +>; +export type OrganizerData = Awaited>; export const addGuestsHandler = async ({ ctx, @@ -76,7 +79,9 @@ export const addGuestsHandler = async ({ ); // Capture new attendee emails after update for audit logging - const newAttendeeEmails = bookingAttendees.attendees.map((attendee) => attendee.email); + const newAttendeeEmails = bookingAttendees.attendees.map( + (attendee) => attendee.email + ); const attendeesList = await prepareAttendeesList(bookingAttendees.attendees); @@ -92,7 +97,10 @@ export const addGuestsHandler = async ({ const featuresRepository = getFeaturesRepository(); const organizationId = user.organizationId ?? null; const isBookingAuditEnabled = organizationId - ? await featuresRepository.checkIfTeamHasFeature(organizationId, "booking-audit") + ? await featuresRepository.checkIfTeamHasFeature( + organizationId, + "booking-audit" + ) : false; await bookingEventHandlerService.onAttendeeAdded({ @@ -109,9 +117,11 @@ export const addGuestsHandler = async ({ return { message: "Guests added" }; }; -async function getBooking(bookingId: number) { +export async function getBooking(bookingId: number) { const bookingRepository = new BookingRepository(prisma); - const booking = await bookingRepository.findByIdIncludeDestinationCalendar(bookingId); + const booking = await bookingRepository.findByIdIncludeDestinationCalendar( + bookingId + ); if (!booking || !booking.user) { throw new TRPCError({ code: "NOT_FOUND", message: "booking_not_found" }); @@ -120,9 +130,14 @@ async function getBooking(bookingId: number) { return booking; } -async function validateUserPermissions(booking: Booking, user: TUser): Promise { +export async function validateUserPermissions( + booking: Booking, + user: TUser +): Promise { const isOrganizer = booking.userId === user.id; - const isAttendee = !!booking.attendees.find((attendee) => attendee.email === user.email); + const isAttendee = !!booking.attendees.find( + (attendee) => attendee.email === user.email + ); let hasBookingUpdatePermission = false; if (booking.eventType?.teamId) { @@ -136,16 +151,21 @@ async function validateUserPermissions(booking: Booking, user: TUser): Promise field.name === "guests"); + const guestsBookingField = parsedBookingFields.find( + (field) => field.name === "guests" + ); if (guestsBookingField?.hidden) { throw new TRPCError({ code: "BAD_REQUEST", @@ -154,7 +174,7 @@ function validateGuestsFieldEnabled(booking: Booking): void { } } -async function getOrganizerData(userId: number | null) { +export async function getOrganizerData(userId: number | null) { if (!userId) { throw new TRPCError({ code: "BAD_REQUEST", message: "User not found" }); } @@ -186,24 +206,36 @@ function deduplicateGuestEmails(guests: string[]): string[] { function getBlacklistedEmails(): string[] { return process.env.BLACKLISTED_GUEST_EMAILS - ? process.env.BLACKLISTED_GUEST_EMAILS.split(",").map((email) => email.toLowerCase()) + ? process.env.BLACKLISTED_GUEST_EMAILS.split(",").map((email) => + email.toLowerCase() + ) : []; } -async function getEmailVerificationRequirements(guestEmails: string[]): Promise> { +async function getEmailVerificationRequirements( + guestEmails: string[] +): Promise> { const userRepo = new UserRepository(prisma); - const guestUsers = await userRepo.findManyByEmailsWithEmailVerificationSettings({ emails: guestEmails }); + const guestUsers = + await userRepo.findManyByEmailsWithEmailVerificationSettings({ + emails: guestEmails, + }); const emailToRequiresVerification = new Map(); for (const user of guestUsers) { - const matchedBase = extractBaseEmail(user.matchedEmail ?? user.email).toLowerCase(); - emailToRequiresVerification.set(matchedBase, user.requiresBookerEmailVerification === true); + const matchedBase = extractBaseEmail( + user.matchedEmail ?? user.email + ).toLowerCase(); + emailToRequiresVerification.set( + matchedBase, + user.requiresBookerEmailVerification === true + ); } return emailToRequiresVerification; } -async function sanitizeAndFilterGuests( +export async function sanitizeAndFilterGuests( guests: Array<{ email: string; name?: string; @@ -224,8 +256,12 @@ async function sanitizeAndFilterGuests( const guestEmails = guests.map((guest) => guest.email); const deduplicatedGuests = deduplicateGuestEmails(guestEmails); const blacklistedGuestEmails = getBlacklistedEmails(); - const guestEmailsLowerCase = deduplicatedGuests.map((email) => extractBaseEmail(email).toLowerCase()); - const emailToRequiresVerification = await getEmailVerificationRequirements(guestEmailsLowerCase); + const guestEmailsLowerCase = deduplicatedGuests.map((email) => + extractBaseEmail(email).toLowerCase() + ); + const emailToRequiresVerification = await getEmailVerificationRequirements( + guestEmailsLowerCase + ); // Create a map of email to guest object for easy lookup const emailToGuestMap = new Map( @@ -236,7 +272,8 @@ async function sanitizeAndFilterGuests( const baseGuestEmail = extractBaseEmail(email).toLowerCase(); return ( !booking.attendees.some( - (attendee) => extractBaseEmail(attendee.email).toLowerCase() === baseGuestEmail + (attendee) => + extractBaseEmail(attendee.email).toLowerCase() === baseGuestEmail ) && !blacklistedGuestEmails.includes(baseGuestEmail) && !emailToRequiresVerification.get(baseGuestEmail) @@ -244,7 +281,10 @@ async function sanitizeAndFilterGuests( }); if (uniqueGuestEmails.length === 0) { - throw new TRPCError({ code: "BAD_REQUEST", message: "emails_must_be_unique_valid" }); + throw new TRPCError({ + code: "BAD_REQUEST", + message: "emails_must_be_unique_valid", + }); } // Return the full guest objects for unique emails @@ -253,9 +293,14 @@ async function sanitizeAndFilterGuests( .filter((guest): guest is NonNullable => guest !== undefined); } -async function updateBookingAttendees( +export async function updateBookingAttendees( bookingId: number, - newAttendees: { name: string; email: string; timeZone: string; locale: string | null }[], + newAttendees: { + name: string; + email: string; + timeZone: string; + locale: string | null; + }[], uniqueGuestEmails: string[], booking: Booking ) { @@ -272,7 +317,7 @@ async function updateBookingAttendees( }); } -async function prepareAttendeesList(attendees: Booking["attendees"]) { +export async function prepareAttendeesList(attendees: Booking["attendees"]) { const attendeesListPromises = attendees.map(async (attendee) => { return { name: attendee.name, @@ -288,13 +333,15 @@ async function prepareAttendeesList(attendees: Booking["attendees"]) { return await Promise.all(attendeesListPromises); } -async function buildCalendarEvent( +export async function buildCalendarEvent( booking: Booking, organizer: OrganizerData, attendeesList: Awaited> ): Promise { const tOrganizer = await getTranslation(organizer.locale ?? "en", "common"); - const videoCallReference = booking.references.find((reference) => reference.type.includes("_video")); + const videoCallReference = booking.references.find((reference) => + reference.type.includes("_video") + ); const evt: CalendarEvent = { title: booking.title || "", @@ -317,8 +364,8 @@ async function buildCalendarEvent( destinationCalendar: booking?.destinationCalendar ? [booking?.destinationCalendar] : booking?.user?.destinationCalendar - ? [booking?.user?.destinationCalendar] - : [], + ? [booking?.user?.destinationCalendar] + : [], seatsPerTimeSlot: booking.eventType?.seatsPerTimeSlot, seatsShowAttendees: booking.eventType?.seatsShowAttendees, customReplyToEmail: booking.eventType?.customReplyToEmail, @@ -337,12 +384,20 @@ async function buildCalendarEvent( return evt; } -async function updateCalendarEvent(booking: Booking, evt: CalendarEvent): Promise { +export async function updateCalendarEvent( + booking: Booking, + evt: CalendarEvent +): Promise { if (!booking.user) { - throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Booking user not found" }); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: "Booking user not found", + }); } - const credentials = await getUsersCredentialsIncludeServiceAccountKey(booking.user); + const credentials = await getUsersCredentialsIncludeServiceAccountKey( + booking.user + ); const eventManager = new EventManager({ ...booking.user, @@ -352,7 +407,7 @@ async function updateCalendarEvent(booking: Booking, evt: CalendarEvent): Promis await eventManager.updateCalendarAttendees(evt, booking); } -async function sendGuestNotifications( +export async function sendGuestNotifications( evt: CalendarEvent, booking: Booking, uniqueGuests: string[] @@ -364,7 +419,9 @@ async function sendGuestNotifications( await emailsAndSmsHandler.handleAddGuests({ evt, eventType: { - metadata: eventTypeMetaDataSchemaWithTypedApps.parse(booking?.eventType?.metadata), + metadata: eventTypeMetaDataSchemaWithTypedApps.parse( + booking?.eventType?.metadata + ), schedulingType: booking.eventType?.schedulingType || null, }, newGuests: uniqueGuests,