Seated booking rescheduling. (#5427)

* WIP-already-reschedule-success-emails-missing

* WIP now saving bookingSeatsReferences and identifyin on reschedule/book page

* Remove logs and created test

* WIP saving progress

* Select second slot to pass test

* Delete attendee from event

* Clean up

* Update with main changes

* Fix emails not being sent

* Changed test end url from success to booking

* Remove unused pkg

* Fix new booking reschedule

* remove log

* Renable test

* remove unused pkg

* rename table name

* review changes

* Fix and and other test to reschedule with seats

* Fix api for cancel booking

* Typings

* Update [uid].tsx

* Abstracted common pattern

into maybeGetBookingUidFromSeat

* Reverts

* Nitpicks

* Update handleCancelBooking.ts

* Adds missing cascades

* Improve booking seats changes (#6858)

* Create sendCancelledSeatEmails

* Draft attendee cancelled seat email

* Send no longer attendee email to attendee

* Send email to organizer when attendee cancels

* Pass cloned event data to emails

* Send booked email for first seat

* Add seat reference uid from email link

* Query for seatReferenceUId and add to cancel & reschedule links

* WIP

* Display proper attendee when rescheduling seats

* Remove console.logs

* Only check for already invited when not rescheduling

* WIP sending reschedule email to just single attendee and owner

* Merge branch 'main' into send-email-on-seats-attendee-changes

* Remove console.logs

* Add cloned event to seat emails

* Do not show manage link for calendar event

* First seat, have both attendees on calendar

* WIP refactor booking seats reschedule logic

* WIP Refactor handleSeats

* Change relation of attendee & seat reference to a one-to-one

* Migration with relationship change

* Booking page handling unique seat references

* Abstract to handleSeats

* Remove console.logs and clean up

* New migration file, delete on cascade

* Check if attendee is already a part of the booking

* Move deleting booking logic to `handleSeats`

* When owner reschedule, move whole booking

* Prevent owner from rescheduling if not enough seats

* Add owner reschedule

* Send reschedule email when moving to new timeslot

* Add event data to reschedule email for seats

* Remove DB changes from event manager

* When a booking has no attendees then delete

* Update calendar when merging bookings

* Move both attendees and seat references when merging

* Remove guest list from seats booking page

* Update original booking when moving an attendee

* Delete calendar and video events if no more attendees

* Update or delete integrations when attendees cancel

* Show no longer attendee if a single attendee cancels

* Change booking to accepted if an attendee books on an empty booking

* If booking in same slot then just return the booking

* Clean up

* Clean up

* Remove booking select

* Typos

---------

Co-authored-by: zomars <[email protected]>

* Fix migration table name

* Add missing trpc import

* Rename bookingSeatReferences to bookingSeat

* Change relationship between Attendee & BookingSeat to one to one

* Fix some merge conflicts

* Minor merge artifact fixup

* Add the right 'Person' type

* Check on email, less (although still) editable than name

* Removed calEvent.attendeeUniqueId

* rename referenceUId -> referenceUid

* Squashes migrations

* Run cached installs

Should still be faster. Ensures prisma client is up to date.

* Solve attendee form on booking page

* Remove unused code

* Some type fixes

* Squash migrations

* Type fixes

* Fix for reschedule/[uid] redirect

* Fix e2e test

* Solve double declaration of host

* Solve lint errors

* Drop constraint only if exists

* Renamed UId to Uid

* Explicit vs. implicit

* Attempt to work around text flakiness by adding a little break between animations

* Various bugfixes

* Persistently apply seatReferenceUid (#7545)

* Persistently apply seatReferenceUid

* Small ts fix

* Setup guards correctly

* Type fixes

* Fix render 0 in conditional

* Test refactoring

* Fix type on handleSeats

* Fix handle seats conditional

* Fix type inference

* Update packages/features/bookings/lib/handleNewBooking.ts

* Update apps/web/components/booking/pages/BookingPage.tsx

* Fix type and missing logic for reschedule

* Fix delete of calendar event and booking

* Add handleSeats return type

* Fix seats booking creation

* Fall through normal booking for initial booking, handleSeats for secondary/reschedule

* Simplification of fetching booking

* Enable seats for round-robin events

* A lot harder than I expected

* ignore-owner-if-seat-reference-given

* Return seatReferenceUid when second seat

* negate userIsOwner

* Fix booking seats with a link without bookingUid

* Needed a time check otherwise the attendee will be in the older booking

* Can't open dialog twice in test..

* Allow passing the booking ID from the server

* Fixed isCancelled check, fixed test

* Delete through cascade instead of multiple deletes

---------

Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: zomars <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Efraín Rochín <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
44 files changed
+1898 -462

No files matched your search

@@ -71,6 +71,10 @@ export default class GoogleCalendarService implements Calendar {
};
async createEvent(calEventRaw: CalendarEvent): Promise<NewCalendarEventType> {
const eventAttendees = calEventRaw.attendees.map(({ id, ...rest }) => ({
...rest,
responseStatus: "accepted",
}));
return new Promise(async (resolve, reject) => {
const myGoogleAuth = await this.auth.getToken();
const payload: calendar_v3.Schema$Event = {
@@ -94,11 +98,7 @@ export default class GoogleCalendarService implements Calendar {
? calEventRaw.destinationCalendar.externalId
: calEventRaw.organizer.email,
},
// eslint-disable-next-line
...calEventRaw.attendees.map(({ id, ...rest }) => ({
...rest,
responseStatus: "accepted",
})),
...eventAttendees,
],
reminders: {
useDefault: true,
+1 -1
View File
@@ -236,7 +236,7 @@ export const createEvent = async (
calEvent.additionalNotes = "Notes have been hidden by the organiser"; // TODO: i18n this string?
}
// TODO: Surfice success/error messages coming from apps to improve end user visibility
// TODO: Surface success/error messages coming from apps to improve end user visibility
const creationResult = calendar
? await calendar.createEvent(calEvent).catch(async (error) => {
success = false;
+75 -43
View File
@@ -1,8 +1,10 @@
import type { DestinationCalendar } from "@prisma/client";
import type { DestinationCalendar, Booking } from "@prisma/client";
import { cloneDeep } from "lodash";
import merge from "lodash/merge";
import { v5 as uuidv5 } from "uuid";
import type { z } from "zod";
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { FAKE_DAILY_CREDENTIAL } from "@calcom/app-store/dailyvideo/lib/VideoApiAdapter";
import { getEventLocationTypeFromApp } from "@calcom/app-store/locations";
import { MeetLocationType } from "@calcom/app-store/locations";
@@ -119,8 +121,10 @@ export default class EventManager {
results.push(result);
}
// Some calendar libraries may edit the original event so let's clone it
const clonedCalEvent = cloneDeep(event);
// Create the calendar event with the proper video call data
results.push(...(await this.createAllCalendarEvents(evt)));
results.push(...(await this.createAllCalendarEvents(clonedCalEvent)));
const referencesToCreate = results.map((result) => {
let createdEventObj: createdEventSchema | null = null;
@@ -193,11 +197,10 @@ export default class EventManager {
public async reschedule(
event: CalendarEvent,
rescheduleUid: string,
newBookingId?: number,
rescheduleReason?: string
newBookingId?: number
): Promise<CreateUpdateResult> {
const evt = processLocation(event);
const originalEvt = processLocation(event);
const evt = cloneDeep(originalEvt);
if (!rescheduleUid) {
throw new Error("You called eventManager.update without an `rescheduleUid`. This should never happen.");
}
@@ -210,6 +213,7 @@ export default class EventManager {
select: {
id: true,
userId: true,
attendees: true,
references: {
// NOTE: id field removed from select as we don't require for deletingMany
// but was giving error on recreate for reschedule, probably because promise.all() didn't finished
@@ -225,6 +229,12 @@ export default class EventManager {
},
destinationCalendar: true,
payment: true,
eventType: {
select: {
seatsPerTimeSlot: true,
seatsShowAttendees: true,
},
},
},
});
@@ -232,22 +242,13 @@ export default class EventManager {
throw new Error("booking not found");
}
// Add reschedule reason to new booking
await prisma.booking.update({
where: {
id: newBookingId,
},
data: {
cancellationReason: rescheduleReason,
},
});
const isDedicated = evt.location ? isDedicatedIntegration(evt.location) : null;
const results: Array<EventResult<Event>> = [];
// 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;
@@ -255,7 +256,11 @@ export default class EventManager {
results.push(result);
}
results.push(...(await this.updateAllCalendarEvents(evt, booking)));
// There was a case that booking didn't had any reference and we don't want to throw error on function
if (booking.references.find((reference) => reference.type.includes("_calendar"))) {
// Update all calendar events.
results.push(...(await this.updateAllCalendarEvents(evt, booking, newBookingId)));
}
const bookingPayment = booking?.payment;
@@ -274,27 +279,6 @@ export default class EventManager {
});
}
// Now we can delete the old booking and its references.
const bookingReferenceDeletes = prisma.bookingReference.deleteMany({
where: {
bookingId: booking.id,
},
});
const attendeeDeletes = prisma.attendee.deleteMany({
where: {
bookingId: booking.id,
},
});
const bookingDeletes = prisma.booking.delete({
where: {
id: booking.id,
},
});
// Wait for all deletions to be applied.
await Promise.all([bookingReferenceDeletes, attendeeDeletes, bookingDeletes]);
return {
results,
referencesToCreate: [...booking.references],
@@ -302,7 +286,10 @@ export default class EventManager {
}
public async updateCalendarAttendees(event: CalendarEvent, booking: PartialBooking) {
// @NOTE: This function is only used for updating attendees on a calendar event. Can we remove this?
if (booking.references.length === 0) {
console.error("Tried to update references but there wasn't any.");
return;
}
await this.updateAllCalendarEvents(event, booking);
}
@@ -386,7 +373,7 @@ export default class EventManager {
let videoCredential = this.videoCredentials
// Whenever a new video connection is added, latest credentials are added with the highest ID.
// Because you can't rely on having them in the higgest first order here, ensure this by sorting in DESC order
// Because you can't rely on having them in the highest first order here, ensure this by sorting in DESC order
.sort((a, b) => {
return b.id - a.id;
})
@@ -433,13 +420,32 @@ export default class EventManager {
*/
private async updateAllCalendarEvents(
event: CalendarEvent,
booking: PartialBooking
booking: PartialBooking,
newBookingId?: number
): Promise<Array<EventResult<NewCalendarEventType>>> {
let calendarReference: PartialReference | undefined = undefined,
credential;
try {
// Bookings should only have one calendar reference
calendarReference = booking.references.filter((reference) => reference.type.includes("_calendar"))[0];
// If a newBookingId is given, update that calendar event
let newBooking;
if (newBookingId) {
newBooking = await prisma.booking.findUnique({
where: {
id: newBookingId,
},
select: {
references: true,
},
});
}
if (newBooking) {
calendarReference = newBooking.references.find((reference) => reference.type.includes("_calendar"));
} else {
// Bookings should only have one calendar reference
calendarReference = booking.references.find((reference) => reference.type.includes("_calendar"));
}
if (!calendarReference) {
return [];
}
@@ -464,6 +470,22 @@ export default class EventManager {
}
}
// If we are merging two calendar events we should delete the old calendar event
if (newBookingId) {
const oldCalendarEvent = booking.references.find((reference) => reference.type.includes("_calendar"));
if (oldCalendarEvent?.credentialId) {
const calendarCredential = await prisma.credential.findUnique({
where: {
id: oldCalendarEvent.credentialId,
},
});
const calendar = getCalendar(calendarCredential);
await calendar?.deleteEvent(oldCalendarEvent.uid, event, oldCalendarEvent.externalCalendarId);
}
}
// Taking care of non-traditional calendar integrations
result = result.concat(
this.calendarCredentials
@@ -536,4 +558,14 @@ export default class EventManager {
public async updateAndSetCancelledPlaceholder(event: CalendarEvent, booking: PartialBooking) {
await this.updateAllCalendarEvents(event, booking);
}
public async rescheduleBookingWithSeats(
originalBooking: Booking,
newTimeSlotBooking?: Booking,
owner?: boolean
) {
// Get originalBooking
// If originalBooking has only one attendee we should do normal reschedule
// Change current event attendees in everyone calendar
}
}
+21 -1
View File
@@ -1,3 +1,4 @@
import { cloneDeep } from "lodash";
import type { TFunction } from "next-i18next";
import type { EventNameObjectType } from "@calcom/core/event";
@@ -7,6 +8,7 @@ import type { CalendarEvent, Person } from "@calcom/types/Calendar";
import AttendeeAwaitingPaymentEmail from "./templates/attendee-awaiting-payment-email";
import AttendeeCancelledEmail from "./templates/attendee-cancelled-email";
import AttendeeCancelledSeatEmail from "./templates/attendee-cancelled-seat-email";
import AttendeeDeclinedEmail from "./templates/attendee-declined-email";
import AttendeeLocationChangeEmail from "./templates/attendee-location-change-email";
import AttendeeRequestEmail from "./templates/attendee-request-email";
@@ -19,6 +21,7 @@ import type { Feedback } from "./templates/feedback-email";
import FeedbackEmail from "./templates/feedback-email";
import type { PasswordReset } from "./templates/forgot-password-email";
import ForgotPasswordEmail from "./templates/forgot-password-email";
import OrganizerAttendeeCancelledSeatEmail from "./templates/organizer-attendee-cancelled-seat-email";
import OrganizerCancelledEmail from "./templates/organizer-cancelled-email";
import OrganizerLocationChangeEmail from "./templates/organizer-location-change-email";
import OrganizerPaymentRefundFailedEmail from "./templates/organizer-payment-refund-failed-email";
@@ -83,7 +86,6 @@ export const sendRescheduledEmails = async (calEvent: CalendarEvent) => {
}
}
// @TODO: we should obtain who is rescheduling the event and send them a different email
emailsToSend.push(
...calEvent.attendees.map((attendee) => {
return sendEmail(() => new AttendeeRescheduledEmail(calEvent, attendee));
@@ -93,6 +95,16 @@ export const sendRescheduledEmails = async (calEvent: CalendarEvent) => {
await Promise.all(emailsToSend);
};
export const sendRescheduledSeatEmail = async (calEvent: CalendarEvent, attendee: Person) => {
const clonedCalEvent = cloneDeep(calEvent);
const emailsToSend: Promise<unknown>[] = [
sendEmail(() => new AttendeeRescheduledEmail(clonedCalEvent, attendee)),
sendEmail(() => new OrganizerRescheduledEmail({ calEvent })),
];
await Promise.all(emailsToSend);
};
export const sendScheduledSeatsEmails = async (
calEvent: CalendarEvent,
invitee: Person,
@@ -114,6 +126,14 @@ export const sendScheduledSeatsEmails = async (
await Promise.all(emailsToSend);
};
export const sendCancelledSeatEmails = async (calEvent: CalendarEvent, cancelledAttendee: Person) => {
const clonedCalEvent = cloneDeep(calEvent);
await Promise.all([
sendEmail(() => new AttendeeCancelledSeatEmail(clonedCalEvent, cancelledAttendee)),
sendEmail(() => new OrganizerAttendeeCancelledSeatEmail({ calEvent })),
]);
};
export const sendOrganizerRequestEmail = async (calEvent: CalendarEvent) => {
const emailsToSend: Promise<unknown>[] = [];
@@ -6,7 +6,7 @@ export function ManageLink(props: { calEvent: CalendarEvent; attendee: Person })
// Guests cannot
const t = props.attendee.language.translate;
if (
props.attendee.email === props.calEvent.attendees[0].email ||
props.attendee.email === props.calEvent.attendees[0]?.email ||
props.calEvent.organizer.email === props.attendee.email
) {
return (
@@ -0,0 +1,12 @@
import { AttendeeScheduledEmail } from "./AttendeeScheduledEmail";
export const AttendeeCancelledSeatEmail = (props: React.ComponentProps<typeof AttendeeScheduledEmail>) => (
<AttendeeScheduledEmail
title="no_longer_attending"
headerType="xCircle"
subject="event_no_longer_attending_subject"
subtitle=""
callToAction={null}
{...props}
/>
);
@@ -58,13 +58,15 @@ export const BaseScheduledEmail = (
: props.callToAction || <ManageLink attendee={props.attendee} calEvent={props.calEvent} />
}
subtitle={props.subtitle || <>{t("emailed_you_and_any_other_attendees")}</>}>
<Info
label={t("cancellation_reason")}
description={
props.calEvent.cancellationReason && props.calEvent.cancellationReason.replace("$RCH$", "")
} // Removing flag to distinguish reschedule from cancellation
withSpacer
/>
{props.calEvent.cancellationReason && (
<Info
label={t("cancellation_reason")}
description={
!!props.calEvent.cancellationReason && props.calEvent.cancellationReason.replace("$RCH$", "")
} // Removing flag to distinguish reschedule from cancellation
withSpacer
/>
)}
<Info label={t("rejection_reason")} description={props.calEvent.rejectionReason} withSpacer />
<Info label={t("what")} description={props.calEvent.title} withSpacer />
<WhenInfo calEvent={props.calEvent} t={t} timeZone={timeZone} />
@@ -0,0 +1,14 @@
import { OrganizerScheduledEmail } from "./OrganizerScheduledEmail";
export const OrganizerAttendeeCancelledSeatEmail = (
props: React.ComponentProps<typeof OrganizerScheduledEmail>
) => (
<OrganizerScheduledEmail
title="attendee_no_longer_attending"
headerType="xCircle"
subject="event_cancelled_subject"
callToAction={null}
attendeeCancelled
{...props}
/>
);
@@ -7,6 +7,7 @@ export const OrganizerScheduledEmail = (
calEvent: CalendarEvent;
attendee: Person;
newSeat?: boolean;
attendeeCancelled?: boolean;
teamMember?: Person;
} & Partial<React.ComponentProps<typeof BaseScheduledEmail>>
) => {
@@ -35,6 +36,13 @@ export const OrganizerScheduledEmail = (
subject={t(subject)}
title={t(title)}
includeAppsStatus
subtitle={
<>
{props.attendeeCancelled
? t("attendee_no_longer_attending_subtitle", { name: props.attendee.name })
: ""}
</>
}
{...props}
/>
);
+2
View File
@@ -1,5 +1,6 @@
export { AttendeeAwaitingPaymentEmail } from "./AttendeeAwaitingPaymentEmail";
export { AttendeeCancelledEmail } from "./AttendeeCancelledEmail";
export { AttendeeCancelledSeatEmail } from "./AttendeeCancelledSeatEmail";
export { AttendeeDeclinedEmail } from "./AttendeeDeclinedEmail";
export { AttendeeLocationChangeEmail } from "./AttendeeLocationChangeEmail";
export { AttendeeRequestEmail } from "./AttendeeRequestEmail";
@@ -19,4 +20,5 @@ export { OrganizerRescheduledEmail } from "./OrganizerRescheduledEmail";
export { OrganizerScheduledEmail } from "./OrganizerScheduledEmail";
export { TeamInviteEmail } from "./TeamInviteEmail";
export { BrokenIntegrationEmail } from "./BrokenIntegrationEmail";
export { OrganizerAttendeeCancelledSeatEmail } from "./OrganizerAttendeeCancelledSeatEmail";
export * from "@calcom/app-store/routing-forms/emails/components";
@@ -0,0 +1,21 @@
import { renderEmail } from "../";
import AttendeeScheduledEmail from "./attendee-scheduled-email";
export default class AttendeeCancelledSeatEmail extends AttendeeScheduledEmail {
protected getNodeMailerPayload(): Record<string, unknown> {
return {
to: `${this.attendee.name} <${this.attendee.email}>`,
from: `${this.calEvent.organizer.name} <${this.getMailerOptions().from}>`,
replyTo: this.calEvent.organizer.email,
subject: `${this.t("event_no_longer_attending_subject", {
title: this.calEvent.title,
date: this.getFormattedDate(),
})}`,
html: renderEmail("AttendeeCancelledSeatEmail", {
calEvent: this.calEvent,
attendee: this.attendee,
}),
text: this.getTextBody("event_request_cancelled", "emailed_you_and_any_other_attendees"),
};
}
}
@@ -1,5 +1,6 @@
import type { DateArray, ParticipationStatus, ParticipationRole } from "ics";
import { createEvent } from "ics";
import { cloneDeep } from "lodash";
import type { TFunction } from "next-i18next";
import { RRule } from "rrule";
@@ -15,6 +16,7 @@ export default class AttendeeScheduledEmail extends BaseEmail {
attendee: Person;
showAttendees: boolean | undefined;
t: TFunction;
attendees: Person[];
constructor(calEvent: CalendarEvent, attendee: Person, showAttendees?: boolean | undefined) {
super();
@@ -23,8 +25,9 @@ export default class AttendeeScheduledEmail extends BaseEmail {
this.attendee = attendee;
this.showAttendees = showAttendees;
this.t = attendee.language.translate;
if (!this.showAttendees) {
this.attendees = [...this.calEvent.attendees];
if (!this.showAttendees && this.calEvent.seatsPerTimeSlot) {
this.attendees = [this.attendee];
this.calEvent.attendees = [this.attendee];
}
}
@@ -50,6 +53,7 @@ export default class AttendeeScheduledEmail extends BaseEmail {
description: this.getTextBody(),
duration: { minutes: dayjs(this.calEvent.endTime).diff(dayjs(this.calEvent.startTime), "minute") },
organizer: { name: this.calEvent.organizer.name, email: this.calEvent.organizer.email },
attendees: [
...this.calEvent.attendees.map((attendee: Person) => ({
name: attendee.name,
@@ -79,6 +83,10 @@ export default class AttendeeScheduledEmail extends BaseEmail {
}
protected getNodeMailerPayload(): Record<string, unknown> {
const clonedCalEvent = cloneDeep(this.calEvent);
this.getiCalEventAsString();
return {
icalEvent: {
filename: "event.ics",
@@ -90,7 +98,7 @@ export default class AttendeeScheduledEmail extends BaseEmail {
replyTo: [...this.calEvent.attendees.map(({ email }) => email), this.calEvent.organizer.email],
subject: `${this.calEvent.title}`,
html: renderEmail("AttendeeScheduledEmail", {
calEvent: this.calEvent,
calEvent: clonedCalEvent,
attendee: this.attendee,
}),
text: this.getTextBody(),
@@ -0,0 +1,32 @@
import { APP_NAME } from "@calcom/lib/constants";
import { renderEmail } from "../";
import OrganizerScheduledEmail from "./organizer-scheduled-email";
export default class OrganizerCancelledEmail extends OrganizerScheduledEmail {
protected getNodeMailerPayload(): Record<string, unknown> {
const toAddresses = [this.calEvent.organizer.email];
if (this.calEvent.team) {
this.calEvent.team.members.forEach((member) => {
const memberAttendee = this.calEvent.attendees.find((attendee) => attendee.email === member.email);
if (memberAttendee) {
toAddresses.push(memberAttendee.email);
}
});
}
return {
from: `${APP_NAME} <${this.getMailerOptions().from}>`,
to: toAddresses.join(","),
subject: `${this.t("event_cancelled_subject", {
title: this.calEvent.title,
date: this.getFormattedDate(),
})}`,
html: renderEmail("OrganizerAttendeeCancelledSeatEmail", {
attendee: this.calEvent.organizer,
calEvent: this.calEvent,
}),
text: this.getTextBody("event_request_cancelled"),
};
}
}
@@ -25,7 +25,7 @@ export default class OrganizerRescheduledEmail extends OrganizerScheduledEmail {
)} ${this.getOrganizerStart("D")}, ${this.getOrganizerStart("YYYY")}`,
})}`,
html: renderEmail("OrganizerRescheduledEmail", {
calEvent: this.calEvent,
calEvent: { ...this.calEvent, attendeeSeatId: undefined },
attendee: this.calEvent.organizer,
}),
text: this.getTextBody("event_has_been_rescheduled"),
@@ -1,5 +1,6 @@
import type { DateArray } from "ics";
import { createEvent } from "ics";
import { cloneDeep } from "lodash";
import type { TFunction } from "next-i18next";
import { RRule } from "rrule";
@@ -67,7 +68,17 @@ export default class OrganizerScheduledEmail extends BaseEmail {
}
protected getNodeMailerPayload(): Record<string, unknown> {
const toAddresses = [this.teamMember?.email || this.calEvent.organizer.email];
const clonedCalEvent = cloneDeep(this.calEvent);
const toAddresses = [this.calEvent.organizer.email];
if (this.calEvent.team) {
this.calEvent.team.members.forEach((member) => {
const memberAttendee = this.calEvent.attendees.find((attendee) => attendee.email === member.email);
if (memberAttendee) {
toAddresses.push(memberAttendee.email);
}
});
}
return {
icalEvent: {
@@ -78,7 +89,7 @@ export default class OrganizerScheduledEmail extends BaseEmail {
to: toAddresses.join(","),
subject: `${this.newSeat ? this.t("new_attendee") + ":" : ""} ${this.calEvent.title}`,
html: renderEmail("OrganizerScheduledEmail", {
calEvent: this.calEvent,
calEvent: clonedCalEvent,
attendee: this.calEvent.organizer,
teamMember: this.teamMember,
newSeat: this.newSeat,
@@ -7,9 +7,9 @@ import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { FAKE_DAILY_CREDENTIAL } from "@calcom/app-store/dailyvideo/lib/VideoApiAdapter";
import { DailyLocationType } from "@calcom/app-store/locations";
import { cancelScheduledJobs } from "@calcom/app-store/zapier/lib/nodeScheduler";
import { deleteMeeting } from "@calcom/core/videoClient";
import { deleteMeeting, updateMeeting } from "@calcom/core/videoClient";
import dayjs from "@calcom/dayjs";
import { sendCancelledEmails } from "@calcom/emails";
import { sendCancelledEmails, sendCancelledSeatEmails } from "@calcom/emails";
import { deleteScheduledEmailReminder } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";
import { sendCancelledReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
import { deleteScheduledSMSReminder } from "@calcom/features/ee/workflows/lib/reminders/smsReminderManager";
@@ -24,12 +24,8 @@ import prisma, { bookingMinimalSelect } from "@calcom/prisma";
import { schemaBookingCancelParams } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
async function handler(req: NextApiRequest & { userId?: number }) {
const { userId } = req;
const { id, uid, allRemainingBookings, cancellationReason } = schemaBookingCancelParams.parse(req.body);
const bookingToDelete = await prisma.booking.findUnique({
async function getBookingToDelete(id: number | undefined, uid: string | undefined) {
return await prisma.booking.findUnique({
where: {
id,
uid,
@@ -70,6 +66,7 @@ async function handler(req: NextApiRequest & { userId?: number }) {
price: true,
currency: true,
length: true,
seatsPerTimeSlot: true,
hosts: {
select: {
user: true,
@@ -92,8 +89,21 @@ async function handler(req: NextApiRequest & { userId?: number }) {
smsReminderNumber: true,
workflowReminders: true,
scheduledJobs: true,
seatsReferences: true,
},
});
}
type CustomRequest = NextApiRequest & {
userId?: number;
bookingToDelete?: Awaited<ReturnType<typeof getBookingToDelete>>;
};
async function handler(req: CustomRequest) {
const { id, uid, allRemainingBookings, cancellationReason, seatReferenceUid } =
schemaBookingCancelParams.parse(req.body);
req.bookingToDelete = await getBookingToDelete(id, uid);
const { bookingToDelete, userId } = req;
if (!bookingToDelete || !bookingToDelete.user) {
throw new HttpError({ statusCode: 400, message: "Booking not found" });
@@ -107,6 +117,10 @@ async function handler(req: NextApiRequest & { userId?: number }) {
throw new HttpError({ statusCode: 400, message: "User not found" });
}
// If it's just an attendee of a booking then just remove them from that booking
const result = await handleSeatedEventCancellation(req);
if (result) return { success: true };
const organizer = await prisma.user.findFirstOrThrow({
where: {
id: bookingToDelete.userId,
@@ -178,6 +192,99 @@ async function handler(req: NextApiRequest & { userId?: number }) {
...(teamMembers && { team: { name: "", members: teamMembers } }),
};
// If it's just an attendee of a booking then just remove them from that booking
if (seatReferenceUid && bookingToDelete.attendees.length > 1) {
const seatReference = bookingToDelete.seatsReferences.find(
(reference) => reference.referenceUid === seatReferenceUid
);
const attendee = bookingToDelete.attendees.find((attendee) => attendee.id === seatReference?.attendeeId);
if (!seatReference || !attendee)
throw new HttpError({ statusCode: 400, message: "User not a part of this booking" });
await prisma.attendee.delete({
where: {
id: seatReference.attendeeId,
},
});
/* If there are references then we should update them as well */
const lastAttendee =
bookingToDelete.attendees.filter((bookingAttendee) => attendee.email !== bookingAttendee.email).length <
0;
const integrationsToDelete = [];
for (const reference of bookingToDelete.references) {
if (reference.credentialId) {
const credential = await prisma.credential.findUnique({
where: {
id: reference.credentialId,
},
});
if (credential) {
if (lastAttendee) {
if (reference.type.includes("_video")) {
integrationsToDelete.push(deleteMeeting(credential, reference.uid));
}
if (reference.type.includes("_calendar")) {
const calendar = getCalendar(credential);
if (calendar) {
integrationsToDelete.push(
calendar?.deleteEvent(reference.uid, evt, reference.externalCalendarId)
);
}
}
} else {
const updatedEvt = {
...evt,
attendees: evt.attendees.filter((evtAttendee) => attendee.email !== evtAttendee.email),
};
if (reference.type.includes("_video")) {
integrationsToDelete.push(
updateMeeting(
{ ...credential, appName: evt.location?.replace("integrations:", "") || "" },
updatedEvt,
reference
)
);
}
if (reference.type.includes("_calendar")) {
const calendar = getCalendar(credential);
if (calendar) {
integrationsToDelete.push(
calendar?.updateEvent(reference.uid, updatedEvt, reference.externalCalendarId)
);
}
}
}
}
}
}
await Promise.all(integrationsToDelete).then(async () => {
if (lastAttendee) {
await prisma.booking.delete({
where: {
id: bookingToDelete.id,
},
});
}
});
const tAttendees = await getTranslation(attendee.locale ?? "en", "common");
await sendCancelledSeatEmails(evt, {
...attendee,
language: { translate: tAttendees, locale: attendee.locale ?? "en" },
});
req.statusCode = 200;
return { message: "No longer attending event" };
}
// Hook up the webhook logic here
const eventTrigger: WebhookTriggerEvents = "BOOKING_CANCELLED";
// Send Webhook call if hooked to BOOKING.CANCELLED
@@ -274,6 +381,13 @@ async function handler(req: NextApiRequest & { userId?: number }) {
});
updatedBookings = updatedBookings.concat(allUpdatedBookings);
} else {
if (bookingToDelete?.eventType?.seatsPerTimeSlot) {
await prisma.attendee.deleteMany({
where: {
bookingId: bookingToDelete.id,
},
});
}
const updatedBooking = await prisma.booking.update({
where: {
id,
@@ -524,4 +638,31 @@ async function handler(req: NextApiRequest & { userId?: number }) {
return { message: "Booking successfully cancelled." };
}
async function handleSeatedEventCancellation(req: CustomRequest) {
const { seatReferenceUid } = schemaBookingCancelParams.parse(req.body);
if (!seatReferenceUid) return;
if (!req.bookingToDelete?.attendees.length || req.bookingToDelete.attendees.length < 2) return;
const seatReference = req.bookingToDelete.seatsReferences.find(
(reference) => reference.referenceUid === seatReferenceUid
);
if (!seatReference) throw new HttpError({ statusCode: 400, message: "User not a part of this booking" });
await Promise.all([
prisma.bookingSeat.delete({
where: {
referenceUid: seatReferenceUid,
},
}),
prisma.attendee.delete({
where: {
id: seatReference.attendeeId,
},
}),
]);
req.statusCode = 200;
return { success: true };
}
export default handler;
File diff suppressed because it is too large. Load diff
+18 -6
View File
@@ -30,10 +30,11 @@ ${calEvent.attendees[0].timeZone}
};
export const getWho = (calEvent: CalendarEvent) => {
let attendeesFromCalEvent = [...calEvent.attendees];
if (calEvent.seatsPerTimeSlot && !calEvent.seatsShowAttendees) {
calEvent.attendees = [];
attendeesFromCalEvent = [];
}
const attendees = calEvent.attendees
const attendees = attendeesFromCalEvent
.map((attendee) => {
return `
${attendee?.name || calEvent.organizer.language.translate("guest")}
@@ -144,7 +145,12 @@ export const getProviderName = (calEvent: CalendarEvent): string => {
};
export const getUid = (calEvent: CalendarEvent): string => {
return calEvent.uid ?? translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
const uid = calEvent.uid;
return uid ?? translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
};
const getSeatReferenceId = (calEvent: CalendarEvent): string => {
return calEvent.attendeeSeatId ? `seatReferenceUid=${calEvent.attendeeSeatId}` : "";
};
export const getManageLink = (calEvent: CalendarEvent) => {
@@ -156,12 +162,18 @@ ${WEBAPP_URL + "/booking/" + getUid(calEvent) + "?changes=true"}
export const getCancelLink = (calEvent: CalendarEvent): string => {
return (
WEBAPP_URL + `/booking/${getUid(calEvent)}?cancel=true&allRemainingBookings=${!!calEvent.recurringEvent}`
WEBAPP_URL +
`/booking/${getUid(
calEvent
)}?cancel=true&allRemainingBookings=${!!calEvent.recurringEvent}&${getSeatReferenceId}`
);
};
export const getRescheduleLink = (calEvent: CalendarEvent): string => {
return WEBAPP_URL + "/reschedule/" + getUid(calEvent);
const Uid = getUid(calEvent);
const seatUid = getSeatReferenceId(calEvent);
return `${WEBAPP_URL}/reschedule/${seatUid ? seatUid : Uid}`;
};
export const getRichDescription = (calEvent: CalendarEvent /*, attendee?: Person*/) => {
@@ -179,7 +191,7 @@ ${getAppsStatus(calEvent)}
${
// TODO: Only the original attendee can make changes to the event
// Guests cannot
getManageLink(calEvent)
!calEvent.seatsPerTimeSlot && getManageLink(calEvent)
}
${
calEvent.paymentInfo
@@ -0,0 +1,20 @@
import type { PrismaClient } from "@prisma/client";
export async function maybeGetBookingUidFromSeat(prisma: PrismaClient, uid: string) {
// Look bookingUid in bookingSeat
const bookingSeat = await prisma.bookingSeat.findUnique({
where: {
referenceUid: uid,
},
select: {
booking: {
select: {
id: true,
uid: true,
},
},
},
});
if (bookingSeat) return bookingSeat.booking.uid;
return uid;
}
@@ -0,0 +1,34 @@
-- DropForeignKey
ALTER TABLE "Attendee" DROP CONSTRAINT IF EXISTS "Attendee_bookingId_fkey";
-- DropForeignKey
ALTER TABLE "Booking" DROP CONSTRAINT IF EXISTS "Booking_userId_fkey";
-- CreateTable
CREATE TABLE "BookingSeat" (
"id" SERIAL NOT NULL,
"referenceUid" TEXT NOT NULL,
"bookingId" INTEGER NOT NULL,
"attendeeId" INTEGER NOT NULL,
"data" JSONB,
CONSTRAINT "BookingSeat_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "BookingSeat_referenceUid_key" ON "BookingSeat"("referenceUid");
-- CreateIndex
CREATE UNIQUE INDEX "BookingSeat_attendeeId_key" ON "BookingSeat"("attendeeId");
-- AddForeignKey
ALTER TABLE "Attendee" ADD CONSTRAINT "Attendee_bookingId_fkey" FOREIGN KEY ("bookingId") REFERENCES "Booking"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Booking" ADD CONSTRAINT "Booking_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingSeat" ADD CONSTRAINT "BookingSeat_bookingId_fkey" FOREIGN KEY ("bookingId") REFERENCES "Booking"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingSeat" ADD CONSTRAINT "BookingSeat_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+20 -8
View File
@@ -275,13 +275,14 @@ model BookingReference {
}
model Attendee {
id Int @id @default(autoincrement())
email String
name String
timeZone String
locale String? @default("en")
booking Booking? @relation(fields: [bookingId], references: [id])
bookingId Int?
id Int @id @default(autoincrement())
email String
name String
timeZone String
locale String? @default("en")
booking Booking? @relation(fields: [bookingId], references: [id], onDelete: Cascade)
bookingId Int?
bookingSeat BookingSeat?
}
enum BookingStatus {
@@ -294,7 +295,7 @@ enum BookingStatus {
model Booking {
id Int @id @default(autoincrement())
uid String @unique
user User? @relation(fields: [userId], references: [id])
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int?
references BookingReference[]
eventType EventType? @relation(fields: [eventTypeId], references: [id])
@@ -325,6 +326,7 @@ model Booking {
smsReminderNumber String?
workflowReminders WorkflowReminder[]
scheduledJobs String[]
seatsReferences BookingSeat[]
/// @zod.custom(imports.bookingMetadataSchema)
metadata Json?
}
@@ -665,6 +667,16 @@ enum WorkflowMethods {
SMS
}
model BookingSeat {
id Int @id @default(autoincrement())
referenceUid String @unique
bookingId Int
booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
attendeeId Int @unique
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
data Json?
}
model VerifiedNumber {
id Int @id @default(autoincrement())
userId Int?
+2
View File
@@ -158,6 +158,7 @@ export const bookingCreateBodySchema = z.object({
hasHashedBookingLink: z.boolean().optional(),
hashedLink: z.string().nullish(),
ethSignature: z.string().optional(),
seatReferenceUid: z.string().optional(),
});
export const requiredCustomInputSchema = z.union([
@@ -220,6 +221,7 @@ export const schemaBookingCancelParams = z.object({
uid: z.string().optional(),
allRemainingBookings: z.boolean().optional(),
cancellationReason: z.string().optional(),
seatReferenceUid: z.string().optional(),
});
export const vitalSettingsUpdateSchema = z.object({
@@ -234,6 +234,15 @@ export const bookingsRouter = router({
},
},
},
{
seatsReferences: {
some: {
attendee: {
email: user.email,
},
},
},
},
],
AND: [passedBookingsStatusFilter, ...(filtersCombined ?? [])],
},
@@ -267,6 +276,21 @@ export const bookingsRouter = router({
},
rescheduled: true,
references: true,
seatsReferences: {
where: {
attendee: {
email: user.email,
},
},
select: {
referenceUid: true,
attendee: {
select: {
email: true,
},
},
},
},
},
orderBy,
take: take + 1,
@@ -956,4 +980,29 @@ export const bookingsRouter = router({
return { message, status };
}),
getBookingAttendees: authedProcedure
.input(z.object({ seatReferenceUid: z.string().uuid() }))
.query(async ({ ctx, input }) => {
const bookingSeat = await ctx.prisma.bookingSeat.findUniqueOrThrow({
where: {
referenceUid: input.seatReferenceUid,
},
select: {
booking: {
select: {
_count: {
select: {
seatsReferences: true,
},
},
},
},
},
});
if (!bookingSeat) {
throw new Error("Booking not found");
}
return bookingSeat.booking._count.seatsReferences;
}),
});
+5 -3
View File
@@ -1,4 +1,4 @@
import type { Prisma, DestinationCalendar, SelectedCalendar } from "@prisma/client";
import type { Prisma, DestinationCalendar, SelectedCalendar, BookingSeat } from "@prisma/client";
import type { Dayjs } from "dayjs";
import type { calendar_v3 } from "googleapis";
import type { Time } from "ical.js";
@@ -25,9 +25,10 @@ export type Person = {
language: { translate: TFunction; locale: string };
username?: string;
id?: number;
bookingId?: number;
locale?: string;
bookingId?: number | null;
locale?: string | null;
timeFormat?: TimeFormat;
bookingSeat?: BookingSeat | null;
};
export type TeamMember = {
@@ -165,6 +166,7 @@ export interface CalendarEvent {
eventTypeId?: number | null;
appsStatus?: AppsStatus[];
seatsShowAttendees?: boolean | null;
attendeeSeatId?: string;
seatsPerTimeSlot?: number | null;
// It has responses to all the fields(system + user)