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 <[email protected]>
This commit is contained in:
Carina WollendorferandCarinaWolli authored and GitHub committed 2023-11-27 13:09:33 -05:00
1 parent c9b50ffb78
commit 230b82d3bf
5 files changed
+1912 -1333

No files matched your search

@@ -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