fix: rescheduling round robin events (emails and calendar events) (#12469)
* send the correct booking email for round robin rescheduling * fixing originalBookingMemberEmails * fix calendar event (needs some code refactoring) * refactor rescheduling code * code clean up * add comment * fix event name if host changes * add tests for rr rescheduling emails * fix videoCallUrl of google meet * code clean up * fix destinationCalendar for new booking --------- Co-authored-by: CarinaWolli <wollencarina@gmail.com>
This commit is contained in:
co-authored by
CarinaWolli
parent
c9b50ffb78
commit
230b82d3bf
@@ -547,6 +547,45 @@ export function expectCalendarEventCreationFailureEmails({
|
||||
);
|
||||
}
|
||||
|
||||
export function expectSuccessfulRoudRobinReschedulingEmails({
|
||||
emails,
|
||||
newOrganizer,
|
||||
prevOrganizer,
|
||||
}: {
|
||||
emails: Fixtures["emails"];
|
||||
newOrganizer: { email: string; name: string };
|
||||
prevOrganizer: { email: string; name: string };
|
||||
}) {
|
||||
if (newOrganizer !== prevOrganizer) {
|
||||
// new organizer should recieve scheduling emails
|
||||
expect(emails).toHaveEmail(
|
||||
{
|
||||
heading: "new_event_scheduled",
|
||||
to: `${newOrganizer.email}`,
|
||||
},
|
||||
`${newOrganizer.email}`
|
||||
);
|
||||
|
||||
// old organizer should recieve cancelled emails
|
||||
expect(emails).toHaveEmail(
|
||||
{
|
||||
heading: "event_request_cancelled",
|
||||
to: `${prevOrganizer.email}`,
|
||||
},
|
||||
`${prevOrganizer.email}`
|
||||
);
|
||||
} else {
|
||||
// organizer should recieve rescheduled emails
|
||||
expect(emails).toHaveEmail(
|
||||
{
|
||||
heading: "event_has_been_rescheduled",
|
||||
to: `${newOrganizer.email}`,
|
||||
},
|
||||
`${newOrganizer.email}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function expectSuccessfulBookingRescheduledEmails({
|
||||
emails,
|
||||
organizer,
|
||||
|
||||
@@ -323,7 +323,8 @@ export default class EventManager {
|
||||
public async reschedule(
|
||||
event: CalendarEvent,
|
||||
rescheduleUid: string,
|
||||
newBookingId?: number
|
||||
newBookingId?: number,
|
||||
changedOrganizer?: boolean
|
||||
): Promise<CreateUpdateResult> {
|
||||
const originalEvt = processLocation(event);
|
||||
const evt = cloneDeep(originalEvt);
|
||||
@@ -376,32 +377,37 @@ export default class EventManager {
|
||||
// As the reschedule requires confirmation, we can't update the events and meetings to new time yet. So, just delete them and let it be handled when organizer confirms the booking.
|
||||
await this.deleteEventsAndMeetings({ booking, event });
|
||||
} else {
|
||||
// If the reschedule doesn't require confirmation, we can "update" the events and meetings to new time.
|
||||
const isDedicated = evt.location ? isDedicatedIntegration(evt.location) : null;
|
||||
// If and only if event type is a dedicated meeting, update the dedicated video meeting.
|
||||
if (isDedicated) {
|
||||
const result = await this.updateVideoEvent(evt, booking);
|
||||
const [updatedEvent] = Array.isArray(result.updatedEvent)
|
||||
? result.updatedEvent
|
||||
: [result.updatedEvent];
|
||||
if (changedOrganizer) {
|
||||
log.debug("RescheduleOrganizerChanged: Deleting Event and Meeting for previous booking");
|
||||
await this.deleteEventsAndMeetings({ booking, event });
|
||||
// New event is created in handleNewBooking
|
||||
} else {
|
||||
// If the reschedule doesn't require confirmation, we can "update" the events and meetings to new time.
|
||||
const isDedicated = evt.location ? isDedicatedIntegration(evt.location) : null;
|
||||
// If and only if event type is a dedicated meeting, update the dedicated video meeting.
|
||||
if (isDedicated) {
|
||||
const result = await this.updateVideoEvent(evt, booking);
|
||||
const [updatedEvent] = Array.isArray(result.updatedEvent)
|
||||
? result.updatedEvent
|
||||
: [result.updatedEvent];
|
||||
|
||||
if (updatedEvent) {
|
||||
evt.videoCallData = updatedEvent;
|
||||
evt.location = updatedEvent.url;
|
||||
if (updatedEvent) {
|
||||
evt.videoCallData = updatedEvent;
|
||||
evt.location = updatedEvent.url;
|
||||
}
|
||||
results.push(result);
|
||||
}
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
const bookingCalendarReference = booking.references.find((reference) =>
|
||||
reference.type.includes("_calendar")
|
||||
);
|
||||
// There was a case that booking didn't had any reference and we don't want to throw error on function
|
||||
if (bookingCalendarReference) {
|
||||
// Update all calendar events.
|
||||
results.push(...(await this.updateAllCalendarEvents(evt, booking, newBookingId)));
|
||||
const bookingCalendarReference = booking.references.find((reference) =>
|
||||
reference.type.includes("_calendar")
|
||||
);
|
||||
// There was a case that booking didn't had any reference and we don't want to throw error on function
|
||||
if (bookingCalendarReference) {
|
||||
// Update all calendar events.
|
||||
results.push(...(await this.updateAllCalendarEvents(evt, booking, newBookingId)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const bookingPayment = booking?.payment;
|
||||
|
||||
// Updating all payment to new
|
||||
|
||||
@@ -102,6 +102,37 @@ export const sendScheduledEmails = async (
|
||||
await Promise.all(emailsToSend);
|
||||
};
|
||||
|
||||
// for rescheduled round robin booking that assigned new members
|
||||
export const sendRoundRobinScheduledEmails = async (calEvent: CalendarEvent, members: Person[]) => {
|
||||
const emailsToSend: Promise<unknown>[] = [];
|
||||
|
||||
for (const teamMember of members) {
|
||||
emailsToSend.push(sendEmail(() => new OrganizerScheduledEmail({ calEvent, teamMember })));
|
||||
}
|
||||
|
||||
await Promise.all(emailsToSend);
|
||||
};
|
||||
|
||||
export const sendRoundRobinRescheduledEmails = async (calEvent: CalendarEvent, members: Person[]) => {
|
||||
const emailsToSend: Promise<unknown>[] = [];
|
||||
|
||||
for (const teamMember of members) {
|
||||
emailsToSend.push(sendEmail(() => new OrganizerRescheduledEmail({ calEvent, teamMember })));
|
||||
}
|
||||
|
||||
await Promise.all(emailsToSend);
|
||||
};
|
||||
|
||||
export const sendRoundRobinCancelledEmails = async (calEvent: CalendarEvent, members: Person[]) => {
|
||||
const emailsToSend: Promise<unknown>[] = [];
|
||||
|
||||
for (const teamMember of members) {
|
||||
emailsToSend.push(sendEmail(() => new OrganizerCancelledEmail({ calEvent, teamMember })));
|
||||
}
|
||||
|
||||
await Promise.all(emailsToSend);
|
||||
};
|
||||
|
||||
export const sendRescheduledEmails = async (calEvent: CalendarEvent) => {
|
||||
const emailsToSend: Promise<unknown>[] = [];
|
||||
|
||||
|
||||
@@ -30,6 +30,9 @@ import {
|
||||
sendOrganizerRequestEmail,
|
||||
sendRescheduledEmails,
|
||||
sendRescheduledSeatEmail,
|
||||
sendRoundRobinCancelledEmails,
|
||||
sendRoundRobinRescheduledEmails,
|
||||
sendRoundRobinScheduledEmails,
|
||||
sendScheduledEmails,
|
||||
sendScheduledSeatsEmails,
|
||||
} from "@calcom/emails";
|
||||
@@ -467,8 +470,26 @@ async function getOriginalRescheduledBooking(uid: string, seatsEventType?: boole
|
||||
email: true,
|
||||
locale: true,
|
||||
timeZone: true,
|
||||
destinationCalendar: true,
|
||||
credentials: {
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
key: true,
|
||||
type: true,
|
||||
teamId: true,
|
||||
appId: true,
|
||||
invalid: true,
|
||||
user: {
|
||||
select: {
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
destinationCalendar: true,
|
||||
payment: true,
|
||||
references: true,
|
||||
workflowReminders: true,
|
||||
@@ -663,8 +684,6 @@ async function handler(
|
||||
};
|
||||
const {
|
||||
recurringCount,
|
||||
allRecurringDates,
|
||||
currentRecurringIndex,
|
||||
noEmail,
|
||||
eventTypeId,
|
||||
eventTypeSlug,
|
||||
@@ -900,6 +919,7 @@ async function handler(
|
||||
|
||||
let originalRescheduledBooking: BookingType = null;
|
||||
|
||||
//this gets the orginal rescheduled booking
|
||||
if (rescheduleUid) {
|
||||
// rescheduleUid can be bookingUid and bookingSeatUid
|
||||
bookingSeat = await prisma.bookingSeat.findUnique({
|
||||
@@ -923,6 +943,7 @@ async function handler(
|
||||
}
|
||||
}
|
||||
|
||||
//checks what users are available
|
||||
if (!eventType.seatsPerTimeSlot && !skipAvailabilityCheck) {
|
||||
const availableUsers = await ensureAvailableUsers(
|
||||
{
|
||||
@@ -1897,11 +1918,16 @@ async function handler(
|
||||
evt.recurringEvent = eventType.recurringEvent;
|
||||
}
|
||||
|
||||
const changedOrganizer =
|
||||
!!originalRescheduledBooking &&
|
||||
eventType.schedulingType === SchedulingType.ROUND_ROBIN &&
|
||||
originalRescheduledBooking.userId !== evt.organizer.id;
|
||||
|
||||
async function createBooking() {
|
||||
if (originalRescheduledBooking) {
|
||||
evt.title = originalRescheduledBooking?.title || evt.title;
|
||||
evt.description = originalRescheduledBooking?.description || evt.description;
|
||||
evt.location = originalRescheduledBooking?.location || evt.location;
|
||||
evt.location = changedOrganizer ? evt.location : originalRescheduledBooking?.location || evt.location;
|
||||
}
|
||||
|
||||
const eventTypeRel = !eventTypeId
|
||||
@@ -2146,6 +2172,7 @@ async function handler(
|
||||
|
||||
let videoCallUrl;
|
||||
|
||||
//this is the actual rescheduling logic
|
||||
if (originalRescheduledBooking?.uid) {
|
||||
log.silly("Rescheduling booking", originalRescheduledBooking.uid);
|
||||
try {
|
||||
@@ -2158,9 +2185,7 @@ async function handler(
|
||||
);
|
||||
}
|
||||
|
||||
// Use EventManager to conditionally use all needed integrations.
|
||||
addVideoCallDataToEvt(originalRescheduledBooking.references);
|
||||
const updateManager = await eventManager.reschedule(evt, originalRescheduledBooking.uid);
|
||||
|
||||
//update original rescheduled booking (no seats event)
|
||||
if (!eventType.seatsPerTimeSlot) {
|
||||
@@ -2175,6 +2200,21 @@ async function handler(
|
||||
});
|
||||
}
|
||||
|
||||
const newDesinationCalendar = evt.destinationCalendar;
|
||||
|
||||
evt.destinationCalendar = originalRescheduledBooking?.destinationCalendar
|
||||
? [originalRescheduledBooking?.destinationCalendar]
|
||||
: originalRescheduledBooking?.user?.destinationCalendar
|
||||
? [originalRescheduledBooking?.user.destinationCalendar]
|
||||
: evt.destinationCalendar;
|
||||
|
||||
const updateManager = await eventManager.reschedule(
|
||||
evt,
|
||||
originalRescheduledBooking.uid,
|
||||
undefined,
|
||||
changedOrganizer
|
||||
);
|
||||
|
||||
// This gets overridden when updating the event - to check if notes have been hidden or not. We just reset this back
|
||||
// to the default description when we are sending the emails.
|
||||
evt.description = eventType.description;
|
||||
@@ -2200,23 +2240,179 @@ async function handler(
|
||||
: calendarResult?.updatedEvent?.iCalUID || undefined;
|
||||
}
|
||||
|
||||
const { metadata, videoCallUrl: _videoCallUrl } = getVideoCallDetails({
|
||||
const { metadata: videoMetadata, videoCallUrl: _videoCallUrl } = getVideoCallDetails({
|
||||
results,
|
||||
});
|
||||
|
||||
let metadata: AdditionalInformation = {};
|
||||
metadata = videoMetadata;
|
||||
videoCallUrl = _videoCallUrl;
|
||||
|
||||
//if organizer changed we need to create a new booking (reschedule only cancels the old one)
|
||||
if (changedOrganizer) {
|
||||
evt.destinationCalendar = newDesinationCalendar;
|
||||
evt.title = getEventName(eventNameObject);
|
||||
|
||||
// location might changed and will be new created in eventManager.create (organizer default location)
|
||||
evt.videoCallData = undefined;
|
||||
const createManager = await eventManager.create(evt);
|
||||
|
||||
// This gets overridden when creating the event - to check if notes have been hidden or not. We just reset this back
|
||||
// to the default description when we are sending the emails.
|
||||
evt.description = eventType.description;
|
||||
|
||||
results = createManager.results;
|
||||
referencesToCreate = createManager.referencesToCreate;
|
||||
videoCallUrl = evt.videoCallData && evt.videoCallData.url ? evt.videoCallData.url : null;
|
||||
|
||||
if (results.length > 0 && results.every((res) => !res.success)) {
|
||||
const error = {
|
||||
errorCode: "BookingCreatingMeetingFailed",
|
||||
message: "Booking rescheduling failed",
|
||||
};
|
||||
|
||||
loggerWithEventDetails.error(
|
||||
`EventManager.create failure in some of the integrations ${organizerUser.username}`,
|
||||
safeStringify({ error, results })
|
||||
);
|
||||
} else {
|
||||
if (results.length) {
|
||||
// Handle Google Meet results
|
||||
// We use the original booking location since the evt location changes to daily
|
||||
if (bookingLocation === MeetLocationType) {
|
||||
const googleMeetResult = {
|
||||
appName: GoogleMeetMetadata.name,
|
||||
type: "conferencing",
|
||||
uid: results[0].uid,
|
||||
originalEvent: results[0].originalEvent,
|
||||
};
|
||||
|
||||
// Find index of google_calendar inside createManager.referencesToCreate
|
||||
const googleCalIndex = createManager.referencesToCreate.findIndex(
|
||||
(ref) => ref.type === "google_calendar"
|
||||
);
|
||||
const googleCalResult = results[googleCalIndex];
|
||||
|
||||
if (!googleCalResult) {
|
||||
loggerWithEventDetails.warn("Google Calendar not installed but using Google Meet as location");
|
||||
results.push({
|
||||
...googleMeetResult,
|
||||
success: false,
|
||||
calWarnings: [tOrganizer("google_meet_warning")],
|
||||
});
|
||||
}
|
||||
|
||||
if (googleCalResult?.createdEvent?.hangoutLink) {
|
||||
results.push({
|
||||
...googleMeetResult,
|
||||
success: true,
|
||||
});
|
||||
|
||||
// Add google_meet to referencesToCreate in the same index as google_calendar
|
||||
createManager.referencesToCreate[googleCalIndex] = {
|
||||
...createManager.referencesToCreate[googleCalIndex],
|
||||
meetingUrl: googleCalResult.createdEvent.hangoutLink,
|
||||
};
|
||||
|
||||
// Also create a new referenceToCreate with type video for google_meet
|
||||
createManager.referencesToCreate.push({
|
||||
type: "google_meet_video",
|
||||
meetingUrl: googleCalResult.createdEvent.hangoutLink,
|
||||
uid: googleCalResult.uid,
|
||||
credentialId: createManager.referencesToCreate[googleCalIndex].credentialId,
|
||||
});
|
||||
} else if (googleCalResult && !googleCalResult.createdEvent?.hangoutLink) {
|
||||
results.push({
|
||||
...googleMeetResult,
|
||||
success: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
|
||||
metadata.conferenceData = results[0].createdEvent?.conferenceData;
|
||||
metadata.entryPoints = results[0].createdEvent?.entryPoints;
|
||||
evt.appsStatus = handleAppsStatus(results, booking);
|
||||
videoCallUrl =
|
||||
metadata.hangoutLink ||
|
||||
results[0].createdEvent?.url ||
|
||||
organizerOrFirstDynamicGroupMemberDefaultLocationUrl ||
|
||||
videoCallUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
evt.appsStatus = handleAppsStatus(results, booking);
|
||||
|
||||
// If there is an integration error, we don't send successful rescheduling email, instead broken integration email should be sent that are handled by either CalendarManager or videoClient
|
||||
if (noEmail !== true && isConfirmedByDefault && !isThereAnIntegrationError) {
|
||||
const copyEvent = cloneDeep(evt);
|
||||
loggerWithEventDetails.debug("Emails: Sending rescheduled emails for booking confirmation");
|
||||
await sendRescheduledEmails({
|
||||
const copyEventAdditionalInfo = {
|
||||
...copyEvent,
|
||||
additionalInformation: metadata,
|
||||
additionalNotes, // Resets back to the additionalNote input and not the override value
|
||||
cancellationReason: `$RCH$${rescheduleReason ? rescheduleReason : ""}`, // Removable code prefix to differentiate cancellation from rescheduling for email
|
||||
});
|
||||
};
|
||||
loggerWithEventDetails.debug("Emails: Sending rescheduled emails for booking confirmation");
|
||||
|
||||
/*
|
||||
handle emails for round robin
|
||||
- if booked rr host is the same, then rescheduling email
|
||||
- if new rr host is booked, then cancellation email to old host and confirmation email to new host
|
||||
*/
|
||||
if (eventType.schedulingType === SchedulingType.ROUND_ROBIN) {
|
||||
const originalBookingMemberEmails: Person[] = [];
|
||||
|
||||
for (const user of originalRescheduledBooking.attendees) {
|
||||
const translate = await getTranslation(user.locale ?? "en", "common");
|
||||
originalBookingMemberEmails.push({
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
timeZone: user.timeZone,
|
||||
language: { translate, locale: user.locale ?? "en" },
|
||||
});
|
||||
}
|
||||
if (originalRescheduledBooking.user) {
|
||||
const translate = await getTranslation(originalRescheduledBooking.user.locale ?? "en", "common");
|
||||
originalBookingMemberEmails.push({
|
||||
...originalRescheduledBooking.user,
|
||||
name: originalRescheduledBooking.user.name || "",
|
||||
language: { translate, locale: originalRescheduledBooking.user.locale ?? "en" },
|
||||
});
|
||||
}
|
||||
|
||||
const newBookingMemberEmails: Person[] =
|
||||
copyEvent.team?.members
|
||||
.map((member) => member)
|
||||
.concat(copyEvent.organizer)
|
||||
.concat(copyEvent.attendees) || [];
|
||||
|
||||
// scheduled Emails
|
||||
const newBookedMembers = newBookingMemberEmails.filter(
|
||||
(member) =>
|
||||
!originalBookingMemberEmails.find((originalMember) => originalMember.email === member.email)
|
||||
);
|
||||
// cancelled Emails
|
||||
const cancelledMembers = originalBookingMemberEmails.filter(
|
||||
(member) => !newBookingMemberEmails.find((newMember) => newMember.email === member.email)
|
||||
);
|
||||
// rescheduled Emails
|
||||
const rescheduledMembers = newBookingMemberEmails.filter((member) =>
|
||||
originalBookingMemberEmails.find((orignalMember) => orignalMember.email === member.email)
|
||||
);
|
||||
|
||||
sendRoundRobinRescheduledEmails(copyEventAdditionalInfo, rescheduledMembers);
|
||||
sendRoundRobinScheduledEmails(copyEventAdditionalInfo, newBookedMembers);
|
||||
sendRoundRobinCancelledEmails(copyEventAdditionalInfo, cancelledMembers);
|
||||
} else {
|
||||
// send normal rescheduled emails (non round robin event, where organizers stay the same)
|
||||
await sendRescheduledEmails({
|
||||
...copyEvent,
|
||||
additionalInformation: metadata,
|
||||
additionalNotes, // Resets back to the additionalNote input and not the override value
|
||||
cancellationReason: `$RCH$${rescheduleReason ? rescheduleReason : ""}`, // Removable code prefix to differentiate cancellation from rescheduling for email
|
||||
});
|
||||
}
|
||||
}
|
||||
// If it's not a reschedule, doesn't require confirmation and there's no price,
|
||||
// Create a booking
|
||||
@@ -2376,7 +2572,7 @@ async function handler(
|
||||
|
||||
const metadata = videoCallUrl
|
||||
? {
|
||||
videoCallUrl: getVideoCallUrlFromCalEvent(evt),
|
||||
videoCallUrl: getVideoCallUrlFromCalEvent(evt) || videoCallUrl,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user