2022-06-16 16:21:48 +00:00
|
|
|
import {
|
|
|
|
Attendee,
|
2022-06-19 15:02:00 +00:00
|
|
|
Booking,
|
2022-06-16 16:21:48 +00:00
|
|
|
BookingReference,
|
2022-06-19 15:02:00 +00:00
|
|
|
BookingStatus,
|
2022-06-16 16:21:48 +00:00
|
|
|
EventType,
|
2022-06-19 15:02:00 +00:00
|
|
|
User,
|
2022-06-16 16:21:48 +00:00
|
|
|
WebhookTriggerEvents,
|
|
|
|
} from "@prisma/client";
|
2022-04-14 21:25:24 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
import { getSession } from "next-auth/react";
|
|
|
|
import type { TFunction } from "next-i18next";
|
|
|
|
import { z, ZodError } from "zod";
|
|
|
|
|
2022-06-19 15:02:00 +00:00
|
|
|
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
2022-04-14 21:25:24 +00:00
|
|
|
import { CalendarEventBuilder } from "@calcom/core/builders/CalendarEvent/builder";
|
|
|
|
import { CalendarEventDirector } from "@calcom/core/builders/CalendarEvent/director";
|
|
|
|
import { deleteMeeting } from "@calcom/core/videoClient";
|
2022-06-28 20:40:58 +00:00
|
|
|
import dayjs from "@calcom/dayjs";
|
2022-06-06 17:49:56 +00:00
|
|
|
import { sendRequestRescheduleEmail } from "@calcom/emails";
|
2022-06-16 16:21:48 +00:00
|
|
|
import { isPrismaObjOrUndefined } from "@calcom/lib";
|
2022-04-14 21:25:24 +00:00
|
|
|
import { getTranslation } from "@calcom/lib/server/i18n";
|
2022-07-28 19:58:26 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
|
|
|
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
|
2022-04-14 21:25:24 +00:00
|
|
|
|
2022-06-16 16:21:48 +00:00
|
|
|
import sendPayload from "@lib/webhooks/sendPayload";
|
|
|
|
import getWebhooks from "@lib/webhooks/subscriptions";
|
2022-04-14 21:25:24 +00:00
|
|
|
|
|
|
|
export type RescheduleResponse = Booking & {
|
|
|
|
attendees: Attendee[];
|
|
|
|
};
|
|
|
|
export type PersonAttendeeCommonFields = Pick<
|
|
|
|
User,
|
|
|
|
"id" | "email" | "name" | "locale" | "timeZone" | "username"
|
|
|
|
>;
|
|
|
|
|
|
|
|
const rescheduleSchema = z.object({
|
|
|
|
bookingId: z.string(),
|
|
|
|
rescheduleReason: z.string().optional(),
|
|
|
|
});
|
|
|
|
|
2022-05-05 01:03:36 +00:00
|
|
|
const findUserDataByUserId = async (userId: number) => {
|
2022-08-31 19:44:47 +00:00
|
|
|
return await prisma.user.findUniqueOrThrow({
|
2022-04-14 21:25:24 +00:00
|
|
|
where: {
|
|
|
|
id: userId,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
name: true,
|
|
|
|
username: true,
|
|
|
|
email: true,
|
|
|
|
timeZone: true,
|
|
|
|
locale: true,
|
|
|
|
credentials: true,
|
|
|
|
destinationCalendar: true,
|
2022-08-09 17:23:12 +00:00
|
|
|
teams: true,
|
2022-04-14 21:25:24 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
const handler = async (
|
|
|
|
req: NextApiRequest,
|
|
|
|
res: NextApiResponse
|
|
|
|
): Promise<RescheduleResponse | NextApiResponse | void> => {
|
|
|
|
const session = await getSession({ req });
|
|
|
|
const {
|
|
|
|
bookingId,
|
|
|
|
rescheduleReason: cancellationReason,
|
|
|
|
}: { bookingId: string; rescheduleReason: string; cancellationReason: string } = req.body;
|
2022-08-09 17:23:12 +00:00
|
|
|
let user: Awaited<ReturnType<typeof findUserDataByUserId>>;
|
2022-04-14 21:25:24 +00:00
|
|
|
try {
|
|
|
|
if (session?.user?.id) {
|
2022-08-09 17:23:12 +00:00
|
|
|
user = await findUserDataByUserId(session?.user.id);
|
2022-04-14 21:25:24 +00:00
|
|
|
} else {
|
2022-06-10 19:16:10 +00:00
|
|
|
return res.status(501).end();
|
2022-04-14 21:25:24 +00:00
|
|
|
}
|
|
|
|
|
2022-08-31 19:44:47 +00:00
|
|
|
const bookingToReschedule = await prisma.booking.findFirstOrThrow({
|
2022-04-14 21:25:24 +00:00
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
uid: true,
|
2022-08-09 17:23:12 +00:00
|
|
|
userId: true,
|
2022-04-14 21:25:24 +00:00
|
|
|
title: true,
|
2022-06-16 16:21:48 +00:00
|
|
|
description: true,
|
2022-04-14 21:25:24 +00:00
|
|
|
startTime: true,
|
|
|
|
endTime: true,
|
|
|
|
eventTypeId: true,
|
2022-08-09 17:23:12 +00:00
|
|
|
eventType: true,
|
2022-04-14 21:25:24 +00:00
|
|
|
location: true,
|
|
|
|
attendees: true,
|
|
|
|
references: true,
|
2022-06-16 16:21:48 +00:00
|
|
|
customInputs: true,
|
2022-05-05 01:03:36 +00:00
|
|
|
dynamicEventSlugRef: true,
|
|
|
|
dynamicGroupSlugRef: true,
|
|
|
|
destinationCalendar: true,
|
2022-04-14 21:25:24 +00:00
|
|
|
},
|
|
|
|
where: {
|
|
|
|
uid: bookingId,
|
|
|
|
NOT: {
|
|
|
|
status: {
|
|
|
|
in: [BookingStatus.CANCELLED, BookingStatus.REJECTED],
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2022-08-09 17:23:12 +00:00
|
|
|
if (!bookingToReschedule.userId) {
|
|
|
|
throw new Error("Booking to reschedule doesn't have an owner.");
|
|
|
|
}
|
|
|
|
if (!bookingToReschedule.eventType) {
|
|
|
|
throw new Error("EventType not found for current booking.");
|
|
|
|
}
|
2022-05-23 11:29:29 +00:00
|
|
|
|
2022-08-09 17:23:12 +00:00
|
|
|
const bookingBelongsToTeam = !!bookingToReschedule.eventType?.teamId;
|
|
|
|
if (bookingBelongsToTeam && bookingToReschedule.eventType?.teamId) {
|
|
|
|
const userTeamIds = user.teams.map((item) => item.teamId);
|
|
|
|
if (userTeamIds.indexOf(bookingToReschedule?.eventType?.teamId) === -1) {
|
|
|
|
throw new Error("User isn't a member on the team");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!bookingBelongsToTeam && bookingToReschedule.userId !== user.id) {
|
|
|
|
throw new Error("User isn't owner of the current booking");
|
|
|
|
}
|
|
|
|
|
|
|
|
if (bookingToReschedule && user) {
|
2022-05-05 01:03:36 +00:00
|
|
|
let event: Partial<EventType> = {};
|
|
|
|
if (bookingToReschedule.eventTypeId) {
|
2022-08-31 19:44:47 +00:00
|
|
|
event = await prisma.eventType.findFirstOrThrow({
|
2022-05-05 01:03:36 +00:00
|
|
|
select: {
|
|
|
|
title: true,
|
|
|
|
users: true,
|
|
|
|
schedulingType: true,
|
2022-05-05 21:16:25 +00:00
|
|
|
recurringEvent: true,
|
2022-05-05 01:03:36 +00:00
|
|
|
},
|
|
|
|
where: {
|
|
|
|
id: bookingToReschedule.eventTypeId,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
2022-04-14 21:25:24 +00:00
|
|
|
await prisma.booking.update({
|
|
|
|
where: {
|
|
|
|
id: bookingToReschedule.id,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
rescheduled: true,
|
|
|
|
cancellationReason,
|
|
|
|
status: BookingStatus.CANCELLED,
|
|
|
|
updatedAt: dayjs().toISOString(),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const [mainAttendee] = bookingToReschedule.attendees;
|
|
|
|
// @NOTE: Should we assume attendees language?
|
|
|
|
const tAttendees = await getTranslation(mainAttendee.locale ?? "en", "common");
|
|
|
|
const usersToPeopleType = (
|
|
|
|
users: PersonAttendeeCommonFields[],
|
|
|
|
selectedLanguage: TFunction
|
|
|
|
): Person[] => {
|
|
|
|
return users?.map((user) => {
|
|
|
|
return {
|
|
|
|
email: user.email || "",
|
|
|
|
name: user.name || "",
|
|
|
|
username: user?.username || "",
|
|
|
|
language: { translate: selectedLanguage, locale: user.locale || "en" },
|
|
|
|
timeZone: user?.timeZone,
|
|
|
|
};
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2022-08-09 17:23:12 +00:00
|
|
|
const userTranslation = await getTranslation(user.locale ?? "en", "common");
|
|
|
|
const [userAsPeopleType] = usersToPeopleType([user], userTranslation);
|
2022-04-14 21:25:24 +00:00
|
|
|
|
|
|
|
const builder = new CalendarEventBuilder();
|
|
|
|
builder.init({
|
|
|
|
title: bookingToReschedule.title,
|
2022-05-05 01:03:36 +00:00
|
|
|
type: event && event.title ? event.title : bookingToReschedule.title,
|
2022-04-14 21:25:24 +00:00
|
|
|
startTime: bookingToReschedule.startTime.toISOString(),
|
|
|
|
endTime: bookingToReschedule.endTime.toISOString(),
|
|
|
|
attendees: usersToPeopleType(
|
|
|
|
// username field doesn't exists on attendee but could be in the future
|
|
|
|
bookingToReschedule.attendees as unknown as PersonAttendeeCommonFields[],
|
|
|
|
tAttendees
|
|
|
|
),
|
2022-08-09 17:23:12 +00:00
|
|
|
organizer: userAsPeopleType,
|
2022-04-14 21:25:24 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const director = new CalendarEventDirector();
|
|
|
|
director.setBuilder(builder);
|
2022-05-05 01:03:36 +00:00
|
|
|
director.setExistingBooking(bookingToReschedule);
|
2022-04-14 21:25:24 +00:00
|
|
|
director.setCancellationReason(cancellationReason);
|
2022-07-07 22:25:05 +00:00
|
|
|
if (event) {
|
2022-05-05 01:03:36 +00:00
|
|
|
await director.buildForRescheduleEmail();
|
2022-07-07 22:25:05 +00:00
|
|
|
} else {
|
|
|
|
await director.buildWithoutEventTypeForRescheduleEmail();
|
2022-05-05 01:03:36 +00:00
|
|
|
}
|
2022-04-14 21:25:24 +00:00
|
|
|
|
|
|
|
// Handling calendar and videos cancellation
|
|
|
|
// This can set previous time as available, until virtual calendar is done
|
|
|
|
const credentialsMap = new Map();
|
2022-08-09 17:23:12 +00:00
|
|
|
user.credentials.forEach((credential) => {
|
2022-04-14 21:25:24 +00:00
|
|
|
credentialsMap.set(credential.type, credential);
|
|
|
|
});
|
|
|
|
const bookingRefsFiltered: BookingReference[] = bookingToReschedule.references.filter(
|
|
|
|
(ref) => !!credentialsMap.get(ref.type)
|
|
|
|
);
|
|
|
|
bookingRefsFiltered.forEach((bookingRef) => {
|
|
|
|
if (bookingRef.uid) {
|
|
|
|
if (bookingRef.type.endsWith("_calendar")) {
|
|
|
|
const calendar = getCalendar(credentialsMap.get(bookingRef.type));
|
|
|
|
|
2022-06-27 14:52:42 +00:00
|
|
|
return calendar?.deleteEvent(
|
|
|
|
bookingRef.uid,
|
|
|
|
builder.calendarEvent,
|
|
|
|
bookingRef.externalCalendarId
|
|
|
|
);
|
2022-04-14 21:25:24 +00:00
|
|
|
} else if (bookingRef.type.endsWith("_video")) {
|
|
|
|
return deleteMeeting(credentialsMap.get(bookingRef.type), bookingRef.uid);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Send emails
|
|
|
|
await sendRequestRescheduleEmail(builder.calendarEvent, {
|
|
|
|
rescheduleLink: builder.rescheduleLink,
|
|
|
|
});
|
2022-06-16 16:21:48 +00:00
|
|
|
|
|
|
|
const evt: CalendarEvent = {
|
|
|
|
title: bookingToReschedule?.title,
|
|
|
|
type: event && event.title ? event.title : bookingToReschedule.title,
|
|
|
|
description: bookingToReschedule?.description || "",
|
|
|
|
customInputs: isPrismaObjOrUndefined(bookingToReschedule.customInputs),
|
|
|
|
startTime: bookingToReschedule?.startTime ? dayjs(bookingToReschedule.startTime).format() : "",
|
|
|
|
endTime: bookingToReschedule?.endTime ? dayjs(bookingToReschedule.endTime).format() : "",
|
2022-08-09 17:23:12 +00:00
|
|
|
organizer: userAsPeopleType,
|
2022-06-16 16:21:48 +00:00
|
|
|
attendees: usersToPeopleType(
|
|
|
|
// username field doesn't exists on attendee but could be in the future
|
|
|
|
bookingToReschedule.attendees as unknown as PersonAttendeeCommonFields[],
|
|
|
|
tAttendees
|
|
|
|
),
|
|
|
|
uid: bookingToReschedule?.uid,
|
|
|
|
location: bookingToReschedule?.location,
|
|
|
|
destinationCalendar:
|
|
|
|
bookingToReschedule?.destinationCalendar || bookingToReschedule?.destinationCalendar,
|
|
|
|
cancellationReason: `Please reschedule. ${cancellationReason}`, // TODO::Add i18-next for this
|
|
|
|
};
|
|
|
|
|
|
|
|
// Send webhook
|
|
|
|
const eventTrigger: WebhookTriggerEvents = "BOOKING_CANCELLED";
|
|
|
|
// Send Webhook call if hooked to BOOKING.CANCELLED
|
|
|
|
const subscriberOptions = {
|
|
|
|
userId: bookingToReschedule.userId,
|
|
|
|
eventTypeId: (bookingToReschedule.eventTypeId as number) || 0,
|
|
|
|
triggerEvent: eventTrigger,
|
|
|
|
};
|
|
|
|
const webhooks = await getWebhooks(subscriberOptions);
|
|
|
|
const promises = webhooks.map((webhook) =>
|
|
|
|
sendPayload(webhook.secret, eventTrigger, new Date().toISOString(), webhook, evt).catch((e) => {
|
|
|
|
console.error(
|
|
|
|
`Error executing webhook for event: ${eventTrigger}, URL: ${webhook.subscriberUrl}`,
|
|
|
|
e
|
|
|
|
);
|
|
|
|
})
|
|
|
|
);
|
|
|
|
await Promise.all(promises);
|
2022-04-14 21:25:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return res.status(200).json(bookingToReschedule);
|
|
|
|
} catch (error) {
|
2022-08-09 17:23:12 +00:00
|
|
|
if (error instanceof Error) {
|
|
|
|
throw new Error("Error.request.reschedule " + error?.message);
|
|
|
|
}
|
2022-04-14 21:25:24 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
function validate(
|
|
|
|
handler: (req: NextApiRequest, res: NextApiResponse) => Promise<RescheduleResponse | NextApiResponse | void>
|
|
|
|
) {
|
|
|
|
return async (req: NextApiRequest, res: NextApiResponse) => {
|
|
|
|
if (req.method === "POST") {
|
|
|
|
try {
|
|
|
|
rescheduleSchema.parse(req.body);
|
|
|
|
} catch (error) {
|
|
|
|
if (error instanceof ZodError && error?.name === "ZodError") {
|
|
|
|
return res.status(400).json(error?.issues);
|
|
|
|
}
|
2022-06-10 19:16:10 +00:00
|
|
|
return res.status(402).end();
|
2022-04-14 21:25:24 +00:00
|
|
|
}
|
|
|
|
} else {
|
2022-06-10 19:16:10 +00:00
|
|
|
return res.status(405).end();
|
2022-04-14 21:25:24 +00:00
|
|
|
}
|
|
|
|
await handler(req, res);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export default validate(handler);
|