feat: Add endpoint to add attendees to existing bookings (#24414)
* feat: add endpoint to add attendees to existing bookings - Created POST /v2/bookings/:bookingUid/attendees endpoint - Added AddAttendeesInput_2024_08_13 for input validation - Added AddAttendeesOutput_2024_08_13 for response format - Created BookingAttendeesService_2024_08_13 for business logic - Created BookingAttendeesController_2024_08_13 for API endpoint - Added validation to check for duplicate attendee emails - Integrated with existing booking and event type repositories - Added validateAndTransformAddAttendeesInput method to InputBookingsService - Fixed pre-existing ESLint no-prototype-builtins warnings - Left placeholder for custom booking field validation logic Co-Authored-By: [email protected] <[email protected]> * refactor: move booking attendee operations to dedicated repository * refactor: move repository files into dedicated repositories directory * feat: validate guests field availability before adding attendees to booking * feat: migrate addAttendees API to use existing addGuests handler * refactor: remove unused validateAndTransformAddAttendeesInput method from InputBookingsService * refactor: rename attendees to guests in booking API endpoints and types * refactor: rename booking-attendees to booking-guests for consistency * WIP: add e2e tests for add booking guests endpoint * faet: improve guest booking tests * refactor: extract getHtml method in email templates * feat: add email toggle support for guest invites based on OAuth client settings * refactor: addGuests handler * feat: add SMS notifications when adding guests to existing bookings * refactor: rename add-attendees to add-guests for consistent terminology * refactor: added repository pattern in addGuests.handler * test: add attendee scheduled email spy to booking guests tests * fix: use event type team ID instead of user org ID for booking permission check * Update BookingEmailSmsHandler.ts * Remove comments * refactor: rename booking guests to booking attendees * refactor: rename guest-related methods to use attendees terminology for consistency * update api docs * refactor: restructure addGuests handler to top * refactor: update guest email format to use object structure in booking tests * docs: clarify API version header requirement for booking attendees endpoint * docs: add email notification details to booking attendees API documentation * refactor: rename booking attendees to guests for consistency * refactor: rename attendees to guests in booking API endpoints * feat: add email validation for guest invites * feat: improve error handling for guest booking failures --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Morgan <[email protected]>
This commit is contained in:
34 files changed
+1302
-103
No files matched your search
@@ -653,7 +653,7 @@ export async function getCredentialForCalendarCache({ credentialId }: { credenti
|
||||
/**
|
||||
* It includes in-memory DelegationCredential credentials as well.
|
||||
*/
|
||||
export async function getUsersCredentialsIncludeServiceAccountKey(user: User) {
|
||||
export async function getUsersCredentialsIncludeServiceAccountKey(user: Pick<User, "id" | "email">) {
|
||||
const credentials = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
|
||||
@@ -695,6 +695,48 @@ export const sendAddGuestsEmails = async (calEvent: CalendarEvent, newGuests: st
|
||||
|
||||
await Promise.all(emailsToSend);
|
||||
};
|
||||
|
||||
export const sendAddGuestsEmailsAndSMS = async (args: {
|
||||
calEvent: CalendarEvent;
|
||||
newGuests: string[];
|
||||
eventTypeMetadata?: EventTypeMetadata;
|
||||
}) => {
|
||||
const { calEvent, newGuests, eventTypeMetadata } = args;
|
||||
const calendarEvent = formatCalEvent(calEvent);
|
||||
|
||||
const emailsAndSMSToSend: Promise<unknown>[] = [];
|
||||
|
||||
if (!eventTypeDisableHostEmail(eventTypeMetadata)) {
|
||||
emailsAndSMSToSend.push(sendEmail(() => new OrganizerAddGuestsEmail({ calEvent: calendarEvent })));
|
||||
|
||||
if (calendarEvent.team?.members) {
|
||||
for (const teamMember of calendarEvent.team.members) {
|
||||
emailsAndSMSToSend.push(
|
||||
sendEmail(() => new OrganizerAddGuestsEmail({ calEvent: calendarEvent, teamMember }))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!eventTypeDisableAttendeeEmail(eventTypeMetadata)) {
|
||||
const eventScheduledSMS = new EventSuccessfullyScheduledSMS(calEvent);
|
||||
|
||||
for (const attendee of calendarEvent.attendees) {
|
||||
if (newGuests.includes(attendee.email)) {
|
||||
emailsAndSMSToSend.push(sendEmail(() => new AttendeeScheduledEmail(calendarEvent, attendee)));
|
||||
|
||||
if (attendee.phoneNumber) {
|
||||
emailsAndSMSToSend.push(eventScheduledSMS.sendSMSToAttendee(attendee));
|
||||
}
|
||||
} else {
|
||||
emailsAndSMSToSend.push(sendEmail(() => new AttendeeAddGuestsEmail(calendarEvent, attendee)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(emailsAndSMSToSend);
|
||||
};
|
||||
|
||||
export const sendFeedbackEmail = async (feedback: Feedback) => {
|
||||
await sendEmail(() => new FeedbackEmail(feedback));
|
||||
};
|
||||
|
||||
@@ -5,6 +5,13 @@ import renderEmail from "../src/renderEmail";
|
||||
import AttendeeScheduledEmail from "./attendee-scheduled-email";
|
||||
|
||||
export default class AttendeeAddGuestsEmail extends AttendeeScheduledEmail {
|
||||
async getHtml() {
|
||||
return await renderEmail("AttendeeAddGuestsEmail", {
|
||||
calEvent: this.calEvent,
|
||||
attendee: this.attendee,
|
||||
});
|
||||
}
|
||||
|
||||
protected async getNodeMailerPayload(): Promise<Record<string, unknown>> {
|
||||
return {
|
||||
icalEvent: generateIcsFile({
|
||||
@@ -20,10 +27,7 @@ export default class AttendeeAddGuestsEmail extends AttendeeScheduledEmail {
|
||||
name: this.calEvent.team?.name || this.calEvent.organizer.name,
|
||||
date: this.getFormattedDate(),
|
||||
})}`,
|
||||
html: await renderEmail("AttendeeAddGuestsEmail", {
|
||||
calEvent: this.calEvent,
|
||||
attendee: this.attendee,
|
||||
}),
|
||||
html: await this.getHtml(),
|
||||
text: this.getTextBody("new_guests_added"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,6 +6,13 @@ import renderEmail from "../src/renderEmail";
|
||||
import OrganizerScheduledEmail from "./organizer-scheduled-email";
|
||||
|
||||
export default class OrganizerAddGuestsEmail extends OrganizerScheduledEmail {
|
||||
async getHtml() {
|
||||
return await renderEmail("OrganizerAddGuestsEmail", {
|
||||
attendee: this.calEvent.organizer,
|
||||
calEvent: this.calEvent,
|
||||
});
|
||||
}
|
||||
|
||||
protected async getNodeMailerPayload(): Promise<Record<string, unknown>> {
|
||||
const toAddresses = [this.teamMember?.email || this.calEvent.organizer.email];
|
||||
|
||||
@@ -27,10 +34,7 @@ export default class OrganizerAddGuestsEmail extends OrganizerScheduledEmail {
|
||||
name: this.calEvent.attendees[0].name,
|
||||
date: this.getFormattedDate(),
|
||||
})}`,
|
||||
html: await renderEmail("OrganizerAddGuestsEmail", {
|
||||
attendee: this.calEvent.organizer,
|
||||
calEvent: this.calEvent,
|
||||
}),
|
||||
html: await this.getHtml(),
|
||||
text: this.getTextBody("new_guests_added"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
sendScheduledEmailsAndSMS,
|
||||
sendOrganizerRequestEmail,
|
||||
sendAttendeeRequestEmailAndSMS,
|
||||
sendAddGuestsEmailsAndSMS,
|
||||
} from "@calcom/emails";
|
||||
import type { BookingType } from "@calcom/features/bookings/lib/handleNewBooking/originalRescheduledBookingUtils";
|
||||
import type { EventNameObjectType } from "@calcom/features/eventtypes/lib/eventNaming";
|
||||
@@ -68,6 +69,10 @@ type RequestedEmailAndSmsPayload = EmailAndSmsPayload & {
|
||||
additionalNotes?: string | null;
|
||||
};
|
||||
|
||||
type AddGuestsEmailAndSmsPayload = EmailAndSmsPayload & {
|
||||
newGuests: string[];
|
||||
};
|
||||
|
||||
type RescheduledSideEffectsPayload = {
|
||||
action: typeof BookingActionMap.rescheduled;
|
||||
data: RescheduleEmailAndSmsPayload;
|
||||
@@ -322,4 +327,30 @@ export class BookingEmailSmsHandler {
|
||||
this.log.error("Failed to send requested event related emails", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles notifications when guests are added to an existing booking.
|
||||
*/
|
||||
public async handleAddGuests(data: AddGuestsEmailAndSmsPayload) {
|
||||
const {
|
||||
evt,
|
||||
eventType: { metadata },
|
||||
newGuests,
|
||||
} = data;
|
||||
|
||||
this.log.debug(
|
||||
"Action: ADD_GUESTS. Sending add guests emails and SMS.",
|
||||
safeStringify({ calEvent: getPiiFreeCalendarEvent(evt) })
|
||||
);
|
||||
|
||||
try {
|
||||
await sendAddGuestsEmailsAndSMS({
|
||||
calEvent: evt,
|
||||
newGuests,
|
||||
eventTypeMetadata: metadata,
|
||||
});
|
||||
} catch (err) {
|
||||
this.log.error("Failed to send add guests related emails and SMS", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1172,4 +1172,51 @@ export class BookingRepository {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findByIdIncludeDestinationCalendar(bookingId: number) {
|
||||
return await this.prismaClient.booking.findUnique({
|
||||
where: {
|
||||
id: bookingId,
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
destinationCalendar: true,
|
||||
references: true,
|
||||
user: {
|
||||
include: {
|
||||
destinationCalendar: true,
|
||||
credentials: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateBookingAttendees({
|
||||
bookingId,
|
||||
newAttendees,
|
||||
updatedResponses,
|
||||
}: {
|
||||
bookingId: number;
|
||||
newAttendees: { name: string; email: string; timeZone: string; locale: string | null }[];
|
||||
updatedResponses: Prisma.InputJsonValue;
|
||||
}) {
|
||||
return await this.prismaClient.booking.update({
|
||||
where: {
|
||||
id: bookingId,
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
},
|
||||
data: {
|
||||
attendees: {
|
||||
createMany: {
|
||||
data: newAttendees,
|
||||
},
|
||||
},
|
||||
responses: updatedResponses,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,4 @@ export type {
|
||||
InstantBookingCreateResult,
|
||||
RegularBookingCreateResult,
|
||||
} from "@calcom/features/bookings/lib/dto/types";
|
||||
export { addGuestsHandler } from "@calcom/trpc/server/routers/viewer/bookings/addGuests.handler";
|
||||
@@ -1,3 +1,4 @@
|
||||
import AttendeeAddGuestsEmail from "@calcom/emails/templates/attendee-add-guests-email";
|
||||
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";
|
||||
@@ -5,6 +6,7 @@ import AttendeeRescheduledEmail from "@calcom/emails/templates/attendee-reschedu
|
||||
import AttendeeScheduledEmail from "@calcom/emails/templates/attendee-scheduled-email";
|
||||
import AttendeeUpdatedEmail from "@calcom/emails/templates/attendee-updated-email";
|
||||
import AttendeeVerifyEmail from "@calcom/emails/templates/attendee-verify-email";
|
||||
import OrganizerAddGuestsEmail from "@calcom/emails/templates/organizer-add-guests-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";
|
||||
@@ -16,6 +18,10 @@ import { verifyEmailCodeHandler } from "@calcom/trpc/server/routers/viewer/workf
|
||||
|
||||
export { AttendeeVerifyEmail };
|
||||
|
||||
export { AttendeeAddGuestsEmail };
|
||||
|
||||
export { OrganizerAddGuestsEmail };
|
||||
|
||||
export { AttendeeScheduledEmail };
|
||||
|
||||
export { OrganizerScheduledEmail };
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import {
|
||||
IsArray,
|
||||
IsEmail,
|
||||
ArrayMinSize,
|
||||
IsString,
|
||||
IsOptional,
|
||||
IsTimeZone,
|
||||
IsEnum,
|
||||
Validate,
|
||||
ValidateNested,
|
||||
} from "class-validator";
|
||||
import { isValidPhoneNumber } from "libphonenumber-js";
|
||||
|
||||
import type { BookingLanguageType } from "./language";
|
||||
import { BookingLanguage } from "./language";
|
||||
|
||||
class Guest {
|
||||
@ApiProperty({
|
||||
type: String,
|
||||
description: "The email of the guest.",
|
||||
example: "[email protected]",
|
||||
})
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: String,
|
||||
description: "The name of the guest.",
|
||||
example: "John Doe",
|
||||
})
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: String,
|
||||
description: "The time zone of the guest.",
|
||||
example: "America/New_York",
|
||||
})
|
||||
@IsTimeZone()
|
||||
@IsOptional()
|
||||
timeZone?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
type: String,
|
||||
description: "The phone number of the guest in international format.",
|
||||
example: "+919876543210",
|
||||
})
|
||||
@IsOptional()
|
||||
@Validate((value: string) => !value || isValidPhoneNumber(value), {
|
||||
message: "Invalid phone number format. Please use international format.",
|
||||
})
|
||||
phoneNumber?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
enum: BookingLanguage,
|
||||
description: "The preferred language of the guest. Used for booking confirmation.",
|
||||
example: BookingLanguage.it,
|
||||
default: BookingLanguage.en,
|
||||
})
|
||||
@IsEnum(BookingLanguage)
|
||||
@IsOptional()
|
||||
language?: BookingLanguageType;
|
||||
}
|
||||
|
||||
export class AddGuestsInput_2024_08_13 {
|
||||
@ArrayMinSize(1)
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => Guest)
|
||||
@ApiProperty({
|
||||
type: [Guest],
|
||||
description: "Array of guests to add to the booking",
|
||||
example: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "John Doe",
|
||||
timeZone: "America/New_York",
|
||||
},
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "Jane Smith",
|
||||
},
|
||||
],
|
||||
})
|
||||
guests!: Guest[];
|
||||
}
|
||||
@@ -9,3 +9,4 @@ 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";
|
||||
@@ -3,12 +3,13 @@ import { Type } from "class-transformer";
|
||||
import { IsEnum, ValidateNested } from "class-validator";
|
||||
|
||||
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
|
||||
|
||||
import {
|
||||
BookingOutput_2024_08_13,
|
||||
GetSeatedBookingOutput_2024_08_13,
|
||||
RecurringBookingOutput_2024_08_13,
|
||||
GetRecurringSeatedBookingOutput_2024_08_13,
|
||||
} from "@calcom/platform-types";
|
||||
} from "./booking.output";
|
||||
|
||||
@ApiExtraModels(
|
||||
BookingOutput_2024_08_13,
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { getUsersCredentialsIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential";
|
||||
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { sendAddGuestsEmails } from "@calcom/emails";
|
||||
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 { 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";
|
||||
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
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";
|
||||
@@ -17,36 +21,75 @@ import { TRPCError } from "@trpc/server";
|
||||
import type { TrpcSessionUser } from "../../../types";
|
||||
import type { TAddGuestsInputSchema } from "./addGuests.schema";
|
||||
|
||||
type TUser = Pick<NonNullable<TrpcSessionUser>, "id" | "email" | "organizationId"> &
|
||||
Partial<Pick<NonNullable<TrpcSessionUser>, "profile">>;
|
||||
|
||||
type AddGuestsOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
user: TUser;
|
||||
};
|
||||
input: TAddGuestsInputSchema;
|
||||
emailsEnabled?: boolean;
|
||||
};
|
||||
export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
|
||||
type Booking = NonNullable<Awaited<ReturnType<BookingRepository["findByIdIncludeDestinationCalendar"]>>>;
|
||||
type OrganizerData = Awaited<ReturnType<typeof getOrganizerData>>;
|
||||
|
||||
export const addGuestsHandler = async ({ ctx, input, emailsEnabled = true }: AddGuestsOptions) => {
|
||||
const { user } = ctx;
|
||||
const { bookingId, guests } = input;
|
||||
|
||||
const booking = await prisma.booking.findUnique({
|
||||
where: {
|
||||
id: bookingId,
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
eventType: true,
|
||||
destinationCalendar: true,
|
||||
references: true,
|
||||
user: {
|
||||
include: {
|
||||
destinationCalendar: true,
|
||||
credentials: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const booking = await getBooking(bookingId);
|
||||
|
||||
if (!booking) throw new TRPCError({ code: "NOT_FOUND", message: "booking_not_found" });
|
||||
await validateUserPermissions(booking, user);
|
||||
|
||||
validateGuestsFieldEnabled(booking);
|
||||
|
||||
const organizer = await getOrganizerData(booking.userId);
|
||||
|
||||
const uniqueGuests = await sanitizeAndFilterGuests(guests, booking);
|
||||
|
||||
const newGuestsDetails = uniqueGuests.map((guest) => ({
|
||||
name: guest.name || "",
|
||||
email: guest.email,
|
||||
timeZone: guest.timeZone || organizer.timeZone,
|
||||
locale: guest.language || organizer.locale,
|
||||
}));
|
||||
|
||||
const uniqueGuestEmails = uniqueGuests.map((guest) => guest.email);
|
||||
|
||||
const bookingAttendees = await updateBookingAttendees(
|
||||
bookingId,
|
||||
newGuestsDetails,
|
||||
uniqueGuestEmails,
|
||||
booking
|
||||
);
|
||||
|
||||
const attendeesList = await prepareAttendeesList(bookingAttendees.attendees);
|
||||
|
||||
const evt = await buildCalendarEvent(booking, organizer, attendeesList);
|
||||
|
||||
await updateCalendarEvent(booking, evt);
|
||||
|
||||
if (emailsEnabled) {
|
||||
await sendGuestNotifications(evt, booking, uniqueGuestEmails);
|
||||
}
|
||||
|
||||
return { message: "Guests added" };
|
||||
};
|
||||
|
||||
async function getBooking(bookingId: number) {
|
||||
const bookingRepository = new BookingRepository(prisma);
|
||||
const booking = await bookingRepository.findByIdIncludeDestinationCalendar(bookingId);
|
||||
|
||||
if (!booking || !booking.user) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "booking_not_found" });
|
||||
}
|
||||
|
||||
return booking;
|
||||
}
|
||||
|
||||
async function validateUserPermissions(booking: Booking, user: TUser): Promise<void> {
|
||||
const isOrganizer = booking.userId === user.id;
|
||||
const isAttendee = !!booking.attendees.find((attendee) => attendee.email === user.email);
|
||||
|
||||
@@ -55,7 +98,7 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
const permissionCheckService = new PermissionCheckService();
|
||||
hasBookingUpdatePermission = await permissionCheckService.checkPermission({
|
||||
userId: user.id,
|
||||
teamId: booking.eventType.teamId,
|
||||
teamId: booking.eventType?.teamId,
|
||||
permission: "booking.update",
|
||||
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
});
|
||||
@@ -64,10 +107,30 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
if (!hasBookingUpdatePermission && !isOrganizer && !isAttendee) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "you_do_not_have_permission" });
|
||||
}
|
||||
}
|
||||
|
||||
const organizer = await prisma.user.findUniqueOrThrow({
|
||||
function validateGuestsFieldEnabled(booking: Booking): void {
|
||||
const parsedBookingFields = booking?.eventType?.bookingFields
|
||||
? eventTypeBookingFields.parse(booking.eventType.bookingFields)
|
||||
: [];
|
||||
|
||||
const guestsBookingField = parsedBookingFields.find((field) => field.name === "guests");
|
||||
if (guestsBookingField?.hidden) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Cannot add guests to this booking. The guests field is disabled for event type "${booking?.eventType?.title}" (ID: ${booking?.eventTypeId}). Please contact the event organizer to enable guest additions.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrganizerData(userId: number | null) {
|
||||
if (!userId) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "User not found" });
|
||||
}
|
||||
|
||||
return await prisma.user.findUniqueOrThrow({
|
||||
where: {
|
||||
id: booking.userId || 0,
|
||||
id: userId,
|
||||
},
|
||||
select: {
|
||||
name: true,
|
||||
@@ -76,13 +139,11 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
locale: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const blacklistedGuestEmails = process.env.BLACKLISTED_GUEST_EMAILS
|
||||
? process.env.BLACKLISTED_GUEST_EMAILS.split(",").map((email) => email.toLowerCase())
|
||||
: [];
|
||||
|
||||
function deduplicateGuestEmails(guests: string[]): string[] {
|
||||
const seenBaseEmails = new Set<string>();
|
||||
const deduplicatedGuests = guests.filter((guest) => {
|
||||
return guests.filter((guest) => {
|
||||
const baseEmail = extractBaseEmail(guest).toLowerCase();
|
||||
if (seenBaseEmails.has(baseEmail)) {
|
||||
return false;
|
||||
@@ -90,8 +151,15 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
seenBaseEmails.add(baseEmail);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
const guestEmails = deduplicatedGuests.map((email) => extractBaseEmail(email).toLowerCase());
|
||||
function getBlacklistedEmails(): string[] {
|
||||
return process.env.BLACKLISTED_GUEST_EMAILS
|
||||
? process.env.BLACKLISTED_GUEST_EMAILS.split(",").map((email) => email.toLowerCase())
|
||||
: [];
|
||||
}
|
||||
|
||||
async function getEmailVerificationRequirements(guestEmails: string[]): Promise<Map<string, boolean>> {
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const guestUsers = await userRepo.findManyByEmailsWithEmailVerificationSettings({ emails: guestEmails });
|
||||
|
||||
@@ -101,8 +169,40 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
emailToRequiresVerification.set(matchedBase, user.requiresBookerEmailVerification === true);
|
||||
}
|
||||
|
||||
const uniqueGuests = deduplicatedGuests.filter((guest) => {
|
||||
const baseGuestEmail = extractBaseEmail(guest).toLowerCase();
|
||||
return emailToRequiresVerification;
|
||||
}
|
||||
|
||||
async function sanitizeAndFilterGuests(
|
||||
guests: Array<{
|
||||
email: string;
|
||||
name?: string;
|
||||
timeZone?: string;
|
||||
phoneNumber?: string;
|
||||
language?: string;
|
||||
}>,
|
||||
booking: Booking
|
||||
): Promise<
|
||||
Array<{
|
||||
email: string;
|
||||
name?: string;
|
||||
timeZone?: string;
|
||||
phoneNumber?: string;
|
||||
language?: string;
|
||||
}>
|
||||
> {
|
||||
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);
|
||||
|
||||
// Create a map of email to guest object for easy lookup
|
||||
const emailToGuestMap = new Map(
|
||||
guests.map((guest) => [extractBaseEmail(guest.email).toLowerCase(), guest])
|
||||
);
|
||||
|
||||
const uniqueGuestEmails = deduplicatedGuests.filter((email) => {
|
||||
const baseGuestEmail = extractBaseEmail(email).toLowerCase();
|
||||
return (
|
||||
!booking.attendees.some(
|
||||
(attendee) => extractBaseEmail(attendee.email).toLowerCase() === baseGuestEmail
|
||||
@@ -112,41 +212,37 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
);
|
||||
});
|
||||
|
||||
if (uniqueGuests.length === 0)
|
||||
if (uniqueGuestEmails.length === 0) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "emails_must_be_unique_valid" });
|
||||
}
|
||||
|
||||
const guestsFullDetails = uniqueGuests.map((guest) => {
|
||||
return {
|
||||
name: "",
|
||||
email: guest,
|
||||
timeZone: organizer.timeZone,
|
||||
locale: organizer.locale,
|
||||
};
|
||||
});
|
||||
// Return the full guest objects for unique emails
|
||||
return uniqueGuestEmails
|
||||
.map((email) => emailToGuestMap.get(extractBaseEmail(email).toLowerCase()))
|
||||
.filter((guest): guest is NonNullable<typeof guest> => guest !== undefined);
|
||||
}
|
||||
|
||||
async function updateBookingAttendees(
|
||||
bookingId: number,
|
||||
newAttendees: { name: string; email: string; timeZone: string; locale: string | null }[],
|
||||
uniqueGuestEmails: string[],
|
||||
booking: Booking
|
||||
) {
|
||||
const bookingResponses = booking.responses as BookingResponses;
|
||||
const bookingRepository = new BookingRepository(prisma);
|
||||
|
||||
const bookingAttendees = await prisma.booking.update({
|
||||
where: {
|
||||
id: bookingId,
|
||||
},
|
||||
include: {
|
||||
attendees: true,
|
||||
},
|
||||
data: {
|
||||
attendees: {
|
||||
createMany: {
|
||||
data: guestsFullDetails,
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
...bookingResponses,
|
||||
guests: [...(bookingResponses?.guests || []), ...uniqueGuests],
|
||||
},
|
||||
return await bookingRepository.updateBookingAttendees({
|
||||
bookingId,
|
||||
newAttendees,
|
||||
updatedResponses: {
|
||||
...bookingResponses,
|
||||
guests: [...(bookingResponses?.guests || []), ...uniqueGuestEmails],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const attendeesListPromises = bookingAttendees.attendees.map(async (attendee) => {
|
||||
async function prepareAttendeesList(attendees: Booking["attendees"]) {
|
||||
const attendeesListPromises = attendees.map(async (attendee) => {
|
||||
return {
|
||||
name: attendee.name,
|
||||
email: attendee.email,
|
||||
@@ -158,7 +254,14 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
};
|
||||
});
|
||||
|
||||
const attendeesList = await Promise.all(attendeesListPromises);
|
||||
return await Promise.all(attendeesListPromises);
|
||||
}
|
||||
|
||||
async function buildCalendarEvent(
|
||||
booking: Booking,
|
||||
organizer: OrganizerData,
|
||||
attendeesList: Awaited<ReturnType<typeof prepareAttendeesList>>
|
||||
): Promise<CalendarEvent> {
|
||||
const tOrganizer = await getTranslation(organizer.locale ?? "en", "common");
|
||||
const videoCallReference = booking.references.find((reference) => reference.type.includes("_video"));
|
||||
|
||||
@@ -199,20 +302,39 @@ export const addGuestsHandler = async ({ ctx, input }: AddGuestsOptions) => {
|
||||
};
|
||||
}
|
||||
|
||||
const credentials = await getUsersCredentialsIncludeServiceAccountKey(ctx.user);
|
||||
return evt;
|
||||
}
|
||||
|
||||
async function updateCalendarEvent(booking: Booking, evt: CalendarEvent): Promise<void> {
|
||||
if (!booking.user) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Booking user not found" });
|
||||
}
|
||||
|
||||
const credentials = await getUsersCredentialsIncludeServiceAccountKey(booking.user);
|
||||
|
||||
const eventManager = new EventManager({
|
||||
...user,
|
||||
...booking.user,
|
||||
credentials: [...credentials],
|
||||
});
|
||||
|
||||
await eventManager.updateCalendarAttendees(evt, booking);
|
||||
}
|
||||
|
||||
try {
|
||||
await sendAddGuestsEmails(evt, uniqueGuests);
|
||||
} catch (err) {
|
||||
console.error("Error sending AddGuestsEmails", err);
|
||||
}
|
||||
async function sendGuestNotifications(
|
||||
evt: CalendarEvent,
|
||||
booking: Booking,
|
||||
uniqueGuests: string[]
|
||||
): Promise<void> {
|
||||
const emailsAndSmsHandler = new BookingEmailSmsHandler({
|
||||
logger: logger,
|
||||
});
|
||||
|
||||
return { message: "Guests added" };
|
||||
};
|
||||
await emailsAndSmsHandler.handleAddGuests({
|
||||
evt,
|
||||
eventType: {
|
||||
metadata: eventTypeMetaDataSchemaWithTypedApps.parse(booking?.eventType?.metadata),
|
||||
schedulingType: booking.eventType?.schedulingType || null,
|
||||
},
|
||||
newGuests: uniqueGuests,
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const ZGuestSchema = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().optional(),
|
||||
timeZone: z.string().optional(),
|
||||
phoneNumber: z.string().optional(),
|
||||
language: z.string().optional(),
|
||||
});
|
||||
|
||||
export const ZAddGuestsInputSchema = z.object({
|
||||
bookingId: z.number(),
|
||||
guests: z.array(z.string().email()),
|
||||
guests: z.array(ZGuestSchema),
|
||||
});
|
||||
|
||||
export type TAddGuestsInputSchema = z.infer<typeof ZAddGuestsInputSchema>;
|
||||
Reference in new issue
Block a user