2022-05-05 21:16:25 +00:00
|
|
|
import { BookingStatus, Credential, Prisma, SchedulingType, WebhookTriggerEvents } from "@prisma/client";
|
2021-09-23 09:35:39 +00:00
|
|
|
import async from "async";
|
2022-06-10 18:38:46 +00:00
|
|
|
import type { NextApiRequest } from "next";
|
2022-08-17 17:38:21 +00:00
|
|
|
import { RRule } from "rrule";
|
2021-09-22 19:52:38 +00:00
|
|
|
import short from "short-uuid";
|
|
|
|
import { v5 as uuidv5 } from "uuid";
|
|
|
|
|
2022-08-26 00:48:50 +00:00
|
|
|
import { getLocationValueForDB, LocationObject } from "@calcom/app-store/locations";
|
2022-07-28 19:58:26 +00:00
|
|
|
import { handlePayment } from "@calcom/app-store/stripepayment/lib/server";
|
2022-08-15 20:18:41 +00:00
|
|
|
import { cancelScheduledJobs, scheduleTrigger } from "@calcom/app-store/zapier/lib/nodeScheduler";
|
2022-03-23 22:00:30 +00:00
|
|
|
import EventManager from "@calcom/core/EventManager";
|
2022-08-26 00:48:50 +00:00
|
|
|
import { getEventName } from "@calcom/core/event";
|
2022-06-10 18:38:46 +00:00
|
|
|
import { getUserAvailability } from "@calcom/core/getUserAvailability";
|
2022-06-28 20:40:58 +00:00
|
|
|
import dayjs from "@calcom/dayjs";
|
2022-06-06 17:49:56 +00:00
|
|
|
import {
|
|
|
|
sendAttendeeRequestEmail,
|
|
|
|
sendOrganizerRequestEmail,
|
|
|
|
sendRescheduledEmails,
|
|
|
|
sendScheduledEmails,
|
2022-07-01 19:19:23 +00:00
|
|
|
sendScheduledSeatsEmails,
|
2022-06-06 17:49:56 +00:00
|
|
|
} from "@calcom/emails";
|
2022-07-28 19:58:26 +00:00
|
|
|
import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
|
2022-08-15 19:52:01 +00:00
|
|
|
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
|
2022-05-05 21:16:25 +00:00
|
|
|
import { getDefaultEvent, getGroupName, getUsernameList } from "@calcom/lib/defaultEvents";
|
2022-03-16 23:36:43 +00:00
|
|
|
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
2022-08-15 19:52:01 +00:00
|
|
|
import isOutOfBounds, { BookingDateInPastError } from "@calcom/lib/isOutOfBounds";
|
2022-03-23 22:00:30 +00:00
|
|
|
import logger from "@calcom/lib/logger";
|
2022-08-26 21:58:08 +00:00
|
|
|
import { defaultResponder, getLuckyUser } from "@calcom/lib/server";
|
2022-08-26 21:10:12 +00:00
|
|
|
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
|
2022-08-26 21:58:08 +00:00
|
|
|
import getSubscribers from "@calcom/lib/webhooks/subscriptions";
|
2022-06-10 18:38:46 +00:00
|
|
|
import prisma, { userSelect } from "@calcom/prisma";
|
2022-08-29 13:04:22 +00:00
|
|
|
import { extendedBookingCreateBody, requiredCustomInputSchema } from "@calcom/prisma/zod-utils";
|
2022-03-23 22:00:30 +00:00
|
|
|
import type { BufferedBusyTime } from "@calcom/types/BufferedBusyTime";
|
2022-06-10 00:32:34 +00:00
|
|
|
import type { AdditionalInformation, CalendarEvent } from "@calcom/types/Calendar";
|
2022-03-23 22:00:30 +00:00
|
|
|
import type { EventResult, PartialReference } from "@calcom/types/EventManager";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2022-08-05 17:08:47 +00:00
|
|
|
import { getSession } from "@lib/auth";
|
2022-06-10 18:38:46 +00:00
|
|
|
import { HttpError } from "@lib/core/http/error";
|
2021-10-07 15:14:47 +00:00
|
|
|
import sendPayload from "@lib/webhooks/sendPayload";
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2021-10-25 13:05:21 +00:00
|
|
|
import { getTranslation } from "@server/lib/i18n";
|
|
|
|
|
2021-09-14 08:45:28 +00:00
|
|
|
const translator = short();
|
|
|
|
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
type User = Prisma.UserGetPayload<typeof userSelect>;
|
2021-11-26 11:03:43 +00:00
|
|
|
type BufferedBusyTimes = BufferedBusyTime[];
|
2021-09-23 09:35:39 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Refreshes a Credential with fresh data from the database.
|
|
|
|
*
|
|
|
|
* @param credential
|
|
|
|
*/
|
|
|
|
async function refreshCredential(credential: Credential): Promise<Credential> {
|
|
|
|
const newCredential = await prisma.credential.findUnique({
|
|
|
|
where: {
|
|
|
|
id: credential.id,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!newCredential) {
|
|
|
|
return credential;
|
|
|
|
} else {
|
|
|
|
return newCredential;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Refreshes the given set of credentials.
|
|
|
|
*
|
|
|
|
* @param credentials
|
|
|
|
*/
|
|
|
|
async function refreshCredentials(credentials: Array<Credential>): Promise<Array<Credential>> {
|
|
|
|
return await async.mapLimit(credentials, 5, refreshCredential);
|
|
|
|
}
|
|
|
|
|
2022-05-05 21:16:25 +00:00
|
|
|
function isAvailable(busyTimes: BufferedBusyTimes, time: dayjs.ConfigType, length: number): boolean {
|
2021-09-14 08:45:28 +00:00
|
|
|
// Check for conflicts
|
|
|
|
let t = true;
|
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
// Early return
|
|
|
|
if (!Array.isArray(busyTimes) || busyTimes.length < 1) return t;
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
let i = 0;
|
|
|
|
while (t === true && i < busyTimes.length) {
|
|
|
|
const busyTime = busyTimes[i];
|
|
|
|
i++;
|
|
|
|
const startTime = dayjs(busyTime.start);
|
|
|
|
const endTime = dayjs(busyTime.end);
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
// Check if time is between start and end times
|
|
|
|
if (dayjs(time).isBetween(startTime, endTime, null, "[)")) {
|
|
|
|
t = false;
|
|
|
|
break;
|
|
|
|
}
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
// Check if slot end time is between start and end time
|
|
|
|
if (dayjs(time).add(length, "minutes").isBetween(startTime, endTime)) {
|
|
|
|
t = false;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if startTime is between slot
|
|
|
|
if (startTime.isBetween(dayjs(time), dayjs(time).add(length, "minutes"))) {
|
|
|
|
t = false;
|
|
|
|
break;
|
|
|
|
}
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return t;
|
|
|
|
}
|
|
|
|
|
2022-04-06 17:20:30 +00:00
|
|
|
const getEventTypesFromDB = async (eventTypeId: number) => {
|
2022-08-31 19:44:47 +00:00
|
|
|
const eventType = await prisma.eventType.findUniqueOrThrow({
|
2021-09-14 08:45:28 +00:00
|
|
|
where: {
|
|
|
|
id: eventTypeId,
|
|
|
|
},
|
|
|
|
select: {
|
2022-06-15 20:54:31 +00:00
|
|
|
id: true,
|
2022-08-29 13:04:22 +00:00
|
|
|
customInputs: true,
|
2021-12-03 16:18:31 +00:00
|
|
|
users: userSelect,
|
2021-09-14 08:45:28 +00:00
|
|
|
team: {
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
name: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
title: true,
|
|
|
|
length: true,
|
|
|
|
eventName: true,
|
|
|
|
schedulingType: true,
|
2022-04-07 18:22:11 +00:00
|
|
|
description: true,
|
2021-09-14 08:45:28 +00:00
|
|
|
periodType: true,
|
|
|
|
periodStartDate: true,
|
|
|
|
periodEndDate: true,
|
|
|
|
periodDays: true,
|
|
|
|
periodCountCalendarDays: true,
|
|
|
|
requiresConfirmation: true,
|
|
|
|
userId: true,
|
2021-09-22 18:36:13 +00:00
|
|
|
price: true,
|
|
|
|
currency: true,
|
2022-02-01 21:48:40 +00:00
|
|
|
metadata: true,
|
2022-01-21 21:35:31 +00:00
|
|
|
destinationCalendar: true,
|
2022-03-28 18:07:13 +00:00
|
|
|
hideCalendarNotes: true,
|
2022-05-24 13:19:12 +00:00
|
|
|
seatsPerTimeSlot: true,
|
2022-05-05 21:16:25 +00:00
|
|
|
recurringEvent: true,
|
2022-07-14 00:10:45 +00:00
|
|
|
workflows: {
|
|
|
|
include: {
|
|
|
|
workflow: {
|
|
|
|
include: {
|
|
|
|
steps: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
2022-06-06 12:48:13 +00:00
|
|
|
locations: true,
|
2022-06-10 18:38:46 +00:00
|
|
|
timeZone: true,
|
|
|
|
schedule: {
|
|
|
|
select: {
|
|
|
|
availability: true,
|
|
|
|
timeZone: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
availability: {
|
|
|
|
select: {
|
|
|
|
startTime: true,
|
|
|
|
endTime: true,
|
|
|
|
days: true,
|
|
|
|
},
|
|
|
|
},
|
2021-09-14 08:45:28 +00:00
|
|
|
},
|
|
|
|
});
|
2022-05-05 21:16:25 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
...eventType,
|
2022-06-10 00:32:34 +00:00
|
|
|
recurringEvent: parseRecurringEvent(eventType.recurringEvent),
|
2022-08-26 00:48:50 +00:00
|
|
|
locations: (eventType.locations ?? []) as LocationObject[],
|
2022-05-05 21:16:25 +00:00
|
|
|
};
|
2022-04-06 17:20:30 +00:00
|
|
|
};
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
async function ensureAvailableUsers(
|
|
|
|
eventType: Awaited<ReturnType<typeof getEventTypesFromDB>> & {
|
|
|
|
users: User[];
|
|
|
|
},
|
|
|
|
input: { dateFrom: string; dateTo: string }
|
|
|
|
) {
|
|
|
|
const availableUsers: typeof eventType.users = [];
|
|
|
|
/** Let's start checking for availability */
|
|
|
|
for (const user of eventType.users) {
|
|
|
|
const { busy: bufferedBusyTimes } = await getUserAvailability(
|
|
|
|
{
|
|
|
|
userId: user.id,
|
|
|
|
eventTypeId: eventType.id,
|
|
|
|
...input,
|
|
|
|
},
|
|
|
|
{ user, eventType }
|
|
|
|
);
|
|
|
|
|
|
|
|
console.log("calendarBusyTimes==>>>", bufferedBusyTimes);
|
|
|
|
|
|
|
|
let isAvailableToBeBooked = true;
|
|
|
|
try {
|
|
|
|
if (eventType.recurringEvent) {
|
|
|
|
const recurringEvent = parseRecurringEvent(eventType.recurringEvent);
|
2022-08-17 17:38:21 +00:00
|
|
|
const allBookingDates = new RRule({ dtstart: new Date(input.dateFrom), ...recurringEvent }).all();
|
2022-08-15 19:52:01 +00:00
|
|
|
// Go through each date for the recurring event and check if each one's availability
|
|
|
|
// DONE: Decreased computational complexity from O(2^n) to O(n) by refactoring this loop to stop
|
|
|
|
// running at the first unavailable time.
|
|
|
|
let i = 0;
|
|
|
|
while (isAvailableToBeBooked === true && i < allBookingDates.length) {
|
|
|
|
const aDate = allBookingDates[i];
|
|
|
|
i++;
|
|
|
|
isAvailableToBeBooked = isAvailable(bufferedBusyTimes, aDate, eventType.length);
|
|
|
|
// We bail at the first false, we don't need to keep checking
|
|
|
|
if (!isAvailableToBeBooked) break;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
isAvailableToBeBooked = isAvailable(bufferedBusyTimes, input.dateFrom, eventType.length);
|
|
|
|
}
|
|
|
|
} catch {
|
|
|
|
log.debug({
|
|
|
|
message: "Unable set isAvailableToBeBooked. Using true. ",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isAvailableToBeBooked) {
|
|
|
|
availableUsers.push(user);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!availableUsers.length) {
|
|
|
|
throw new Error("No available users found.");
|
|
|
|
}
|
|
|
|
return availableUsers;
|
|
|
|
}
|
2022-04-06 17:20:30 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
async function handler(req: NextApiRequest) {
|
2022-08-05 17:08:47 +00:00
|
|
|
const session = await getSession({ req });
|
|
|
|
const currentUser = session?.user;
|
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
const { recurringCount, noEmail, eventTypeSlug, eventTypeId, hasHashedBookingLink, language, ...reqBody } =
|
|
|
|
extendedBookingCreateBody.parse(req.body);
|
2022-04-06 17:20:30 +00:00
|
|
|
|
|
|
|
// handle dynamic user
|
2022-04-14 21:25:24 +00:00
|
|
|
const dynamicUserList = Array.isArray(reqBody.user)
|
2022-06-10 18:38:46 +00:00
|
|
|
? getGroupName(reqBody.user)
|
|
|
|
: getUsernameList(reqBody.user);
|
|
|
|
const tAttendees = await getTranslation(language ?? "en", "common");
|
2022-04-06 17:20:30 +00:00
|
|
|
const tGuests = await getTranslation("en", "common");
|
|
|
|
log.debug(`Booking eventType ${eventTypeId} started`);
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
const eventType =
|
|
|
|
!eventTypeId && !!eventTypeSlug ? getDefaultEvent(eventTypeSlug) : await getEventTypesFromDB(eventTypeId);
|
2022-08-29 13:04:22 +00:00
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
if (!eventType) throw new HttpError({ statusCode: 404, message: "eventType.notFound" });
|
2022-04-06 17:20:30 +00:00
|
|
|
|
2022-08-29 13:04:22 +00:00
|
|
|
// Check if required custom inputs exist
|
|
|
|
if (eventType.customInputs) {
|
|
|
|
eventType.customInputs.forEach((customInput) => {
|
|
|
|
if (customInput.required) {
|
|
|
|
requiredCustomInputSchema.parse(
|
|
|
|
reqBody.customInputs.find((userInput) => userInput.label === customInput.label)?.value
|
|
|
|
);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
let timeOutOfBounds = false;
|
|
|
|
try {
|
|
|
|
timeOutOfBounds = isOutOfBounds(reqBody.start, {
|
|
|
|
periodType: eventType.periodType,
|
|
|
|
periodDays: eventType.periodDays,
|
|
|
|
periodEndDate: eventType.periodEndDate,
|
|
|
|
periodStartDate: eventType.periodStartDate,
|
|
|
|
periodCountCalendarDays: eventType.periodCountCalendarDays,
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
if (error instanceof BookingDateInPastError) {
|
|
|
|
// TODO: HttpError should not bleed through to the console.
|
|
|
|
log.info(`Booking eventType ${eventTypeId} failed`, error);
|
|
|
|
throw new HttpError({ statusCode: 400, message: error.message });
|
|
|
|
}
|
|
|
|
log.debug({
|
|
|
|
message: "Unable set timeOutOfBounds. Using false. ",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (timeOutOfBounds) {
|
2022-04-06 17:20:30 +00:00
|
|
|
const error = {
|
2022-08-15 19:52:01 +00:00
|
|
|
errorCode: "BookingTimeOutOfBounds",
|
|
|
|
message: `EventType '${eventType.eventName}' cannot be booked at this time.`,
|
2022-04-06 17:20:30 +00:00
|
|
|
};
|
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
throw new HttpError({ statusCode: 400, message: error.message });
|
2022-04-06 17:20:30 +00:00
|
|
|
}
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-04-06 17:20:30 +00:00
|
|
|
let users = !eventTypeId
|
|
|
|
? await prisma.user.findMany({
|
|
|
|
where: {
|
|
|
|
username: {
|
|
|
|
in: dynamicUserList,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
...userSelect,
|
|
|
|
})
|
|
|
|
: eventType.users;
|
2022-08-12 19:29:29 +00:00
|
|
|
const isDynamicAllowed = !users.some((user) => !user.allowDynamicBooking);
|
2022-08-16 22:07:44 +00:00
|
|
|
if (!isDynamicAllowed && !eventTypeId) {
|
2022-08-12 19:29:29 +00:00
|
|
|
throw new HttpError({
|
|
|
|
message: "Some of the users in this group do not allow dynamic booking",
|
|
|
|
statusCode: 400,
|
|
|
|
});
|
|
|
|
}
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
// If this event was pre-relationship migration
|
|
|
|
// TODO: Establish whether this is dead code.
|
2021-09-22 18:36:13 +00:00
|
|
|
if (!users.length && eventType.userId) {
|
2021-09-23 09:35:39 +00:00
|
|
|
const eventTypeUser = await prisma.user.findUnique({
|
2021-09-22 18:36:13 +00:00
|
|
|
where: {
|
|
|
|
id: eventType.userId,
|
|
|
|
},
|
2021-12-03 16:18:31 +00:00
|
|
|
...userSelect,
|
2021-09-22 18:36:13 +00:00
|
|
|
});
|
2022-06-10 18:38:46 +00:00
|
|
|
if (!eventTypeUser) throw new HttpError({ statusCode: 404, message: "eventTypeUser.notFound" });
|
2021-09-23 09:35:39 +00:00
|
|
|
users.push(eventTypeUser);
|
2021-09-22 18:36:13 +00:00
|
|
|
}
|
2022-08-12 19:29:29 +00:00
|
|
|
|
|
|
|
if (!users) throw new HttpError({ statusCode: 404, message: "eventTypeUser.notFound" });
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
const availableUsers = await ensureAvailableUsers(
|
|
|
|
{
|
|
|
|
...eventType,
|
|
|
|
users,
|
2022-01-27 20:32:53 +00:00
|
|
|
},
|
2022-08-15 19:52:01 +00:00
|
|
|
{
|
|
|
|
dateFrom: reqBody.start,
|
|
|
|
dateTo: reqBody.end,
|
|
|
|
}
|
|
|
|
);
|
2022-01-27 20:32:53 +00:00
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
// Assign to only one user when ROUND_ROBIN
|
2021-09-14 08:45:28 +00:00
|
|
|
if (eventType.schedulingType === SchedulingType.ROUND_ROBIN) {
|
2022-08-15 19:52:01 +00:00
|
|
|
users = [await getLuckyUser("MAXIMIZE_AVAILABILITY", { availableUsers, eventTypeId: eventType.id })];
|
|
|
|
} else {
|
|
|
|
// excluding ROUND_ROBIN, all users have availability required.
|
|
|
|
if (availableUsers.length !== users.length) {
|
|
|
|
throw new Error("Some users are unavailable for booking.");
|
|
|
|
}
|
|
|
|
users = availableUsers;
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
console.log("available users", users);
|
|
|
|
|
|
|
|
const [organizerUser] = users;
|
|
|
|
const tOrganizer = await getTranslation(organizerUser.locale ?? "en", "common");
|
|
|
|
|
2022-01-27 20:32:53 +00:00
|
|
|
const invitee = [
|
|
|
|
{
|
|
|
|
email: reqBody.email,
|
|
|
|
name: reqBody.name,
|
|
|
|
timeZone: reqBody.timeZone,
|
2022-06-10 18:38:46 +00:00
|
|
|
language: { translate: tAttendees, locale: language ?? "en" },
|
2022-01-27 20:32:53 +00:00
|
|
|
},
|
|
|
|
];
|
2022-06-10 18:38:46 +00:00
|
|
|
const guests = (reqBody.guests || []).map((guest) => ({
|
|
|
|
email: guest,
|
|
|
|
name: "",
|
|
|
|
timeZone: reqBody.timeZone,
|
|
|
|
language: { translate: tGuests, locale: "en" },
|
|
|
|
}));
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-07-01 19:19:23 +00:00
|
|
|
const seed = `${organizerUser.username}:${dayjs(reqBody.start).utc().format()}:${new Date().getTime()}`;
|
|
|
|
const uid = translator.fromUUID(uuidv5(seed, uuidv5.URL));
|
2022-05-24 13:19:12 +00:00
|
|
|
|
2022-08-26 00:48:50 +00:00
|
|
|
const bookingLocation = getLocationValueForDB(reqBody.location, eventType.locations);
|
|
|
|
console.log(bookingLocation, reqBody.location, eventType.locations);
|
2022-07-01 19:19:23 +00:00
|
|
|
const customInputs = {} as NonNullable<CalendarEvent["customInputs"]>;
|
2022-05-24 13:19:12 +00:00
|
|
|
|
2022-01-27 20:32:53 +00:00
|
|
|
const teamMemberPromises =
|
2021-09-14 08:45:28 +00:00
|
|
|
eventType.schedulingType === SchedulingType.COLLECTIVE
|
2022-01-27 20:32:53 +00:00
|
|
|
? users.slice(1).map(async function (user) {
|
|
|
|
return {
|
|
|
|
email: user.email || "",
|
|
|
|
name: user.name || "",
|
|
|
|
timeZone: user.timeZone,
|
|
|
|
language: {
|
|
|
|
translate: await getTranslation(user.locale ?? "en", "common"),
|
|
|
|
locale: user.locale ?? "en",
|
|
|
|
},
|
|
|
|
};
|
|
|
|
})
|
2021-09-14 08:45:28 +00:00
|
|
|
: [];
|
|
|
|
|
2022-01-27 20:32:53 +00:00
|
|
|
const teamMembers = await Promise.all(teamMemberPromises);
|
|
|
|
|
2021-09-14 08:45:28 +00:00
|
|
|
const attendeesList = [...invitee, ...guests, ...teamMembers];
|
|
|
|
|
2021-11-08 11:04:12 +00:00
|
|
|
const eventNameObject = {
|
|
|
|
attendeeName: reqBody.name || "Nameless",
|
|
|
|
eventType: eventType.title,
|
|
|
|
eventName: eventType.eventName,
|
2022-06-06 12:48:13 +00:00
|
|
|
host: organizerUser.name || "Nameless",
|
2022-08-26 00:48:50 +00:00
|
|
|
location: bookingLocation,
|
2022-01-27 20:32:53 +00:00
|
|
|
t: tOrganizer,
|
2021-11-08 11:04:12 +00:00
|
|
|
};
|
|
|
|
|
2022-05-18 21:05:49 +00:00
|
|
|
const additionalNotes = reqBody.notes;
|
|
|
|
|
2022-07-01 19:19:23 +00:00
|
|
|
let evt: CalendarEvent = {
|
2021-09-14 08:45:28 +00:00
|
|
|
type: eventType.title,
|
2022-01-27 20:32:53 +00:00
|
|
|
title: getEventName(eventNameObject), //this needs to be either forced in english, or fetched for each attendee and organizer separately
|
2022-04-07 18:22:11 +00:00
|
|
|
description: eventType.description,
|
|
|
|
additionalNotes,
|
2022-05-18 21:05:49 +00:00
|
|
|
customInputs,
|
2022-07-07 01:08:38 +00:00
|
|
|
startTime: dayjs(reqBody.start).utc().format(),
|
|
|
|
endTime: dayjs(reqBody.end).utc().format(),
|
2021-09-14 08:45:28 +00:00
|
|
|
organizer: {
|
2022-06-06 12:48:13 +00:00
|
|
|
name: organizerUser.name || "Nameless",
|
|
|
|
email: organizerUser.email || "Email-less",
|
|
|
|
timeZone: organizerUser.timeZone,
|
2022-08-15 19:52:01 +00:00
|
|
|
language: { translate: tOrganizer, locale: organizerUser.locale ?? "en" },
|
2021-09-14 08:45:28 +00:00
|
|
|
},
|
|
|
|
attendees: attendeesList,
|
2022-08-26 00:48:50 +00:00
|
|
|
location: bookingLocation, // Will be processed by the EventManager later.
|
2022-04-06 17:20:30 +00:00
|
|
|
/** For team events & dynamic collective events, we will need to handle each member destinationCalendar eventually */
|
2022-06-06 12:48:13 +00:00
|
|
|
destinationCalendar: eventType.destinationCalendar || organizerUser.destinationCalendar,
|
2022-03-28 18:07:13 +00:00
|
|
|
hideCalendarNotes: eventType.hideCalendarNotes,
|
2022-06-17 09:02:29 +00:00
|
|
|
requiresConfirmation: eventType.requiresConfirmation ?? false,
|
2022-06-25 05:16:20 +00:00
|
|
|
eventTypeId: eventType.id,
|
2021-09-14 08:45:28 +00:00
|
|
|
};
|
|
|
|
|
2022-07-01 19:19:23 +00:00
|
|
|
// For seats, if the booking already exists then we want to add the new attendee to the existing booking
|
|
|
|
if (reqBody.bookingUid) {
|
|
|
|
if (!eventType.seatsPerTimeSlot)
|
|
|
|
throw new HttpError({ statusCode: 404, message: "Event type does not have seats" });
|
|
|
|
|
|
|
|
const booking = await prisma.booking.findUnique({
|
|
|
|
where: {
|
|
|
|
uid: reqBody.bookingUid,
|
|
|
|
},
|
2022-07-12 13:16:34 +00:00
|
|
|
select: {
|
|
|
|
id: true,
|
2022-07-01 19:19:23 +00:00
|
|
|
attendees: true,
|
2022-07-18 15:37:47 +00:00
|
|
|
userId: true,
|
2022-07-12 13:16:34 +00:00
|
|
|
references: {
|
|
|
|
select: {
|
|
|
|
type: true,
|
|
|
|
uid: true,
|
|
|
|
meetingId: true,
|
|
|
|
meetingPassword: true,
|
|
|
|
meetingUrl: true,
|
|
|
|
externalCalendarId: true,
|
|
|
|
},
|
|
|
|
},
|
2022-07-01 19:19:23 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
if (!booking) throw new HttpError({ statusCode: 404, message: "Booking not found" });
|
|
|
|
|
|
|
|
// Need to add translation for attendees to pass type checks. Since these values are never written to the db we can just use the new attendee language
|
|
|
|
const bookingAttendees = booking.attendees.map((attendee) => {
|
|
|
|
return { ...attendee, language: { translate: tAttendees, locale: language ?? "en" } };
|
|
|
|
});
|
|
|
|
|
|
|
|
evt = { ...evt, attendees: [...bookingAttendees, invitee[0]] };
|
|
|
|
|
|
|
|
if (eventType.seatsPerTimeSlot <= booking.attendees.length)
|
|
|
|
throw new HttpError({ statusCode: 409, message: "Booking seats are full" });
|
|
|
|
|
|
|
|
if (booking.attendees.some((attendee) => attendee.email === invitee[0].email))
|
|
|
|
throw new HttpError({ statusCode: 409, message: "Already signed up for time slot" });
|
|
|
|
|
|
|
|
await prisma.booking.update({
|
|
|
|
where: {
|
|
|
|
uid: reqBody.bookingUid,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
attendees: {
|
|
|
|
create: {
|
|
|
|
email: invitee[0].email,
|
|
|
|
name: invitee[0].name,
|
|
|
|
timeZone: invitee[0].timeZone,
|
|
|
|
locale: invitee[0].language.locale,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const newSeat = booking.attendees.length !== 0;
|
|
|
|
|
|
|
|
await sendScheduledSeatsEmails(evt, invitee[0], newSeat);
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
const credentials = await refreshCredentials(organizerUser.credentials);
|
|
|
|
const eventManager = new EventManager({ ...organizerUser, credentials });
|
2022-07-12 13:16:34 +00:00
|
|
|
await eventManager.updateCalendarAttendees(evt, booking);
|
|
|
|
|
2022-07-01 19:19:23 +00:00
|
|
|
req.statusCode = 201;
|
|
|
|
return booking;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (reqBody.customInputs.length > 0) {
|
|
|
|
reqBody.customInputs.forEach(({ label, value }) => {
|
|
|
|
customInputs[label] = value;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-09-14 08:45:28 +00:00
|
|
|
if (eventType.schedulingType === SchedulingType.COLLECTIVE) {
|
|
|
|
evt.team = {
|
2021-09-22 18:36:13 +00:00
|
|
|
members: users.map((user) => user.name || user.username || "Nameless"),
|
|
|
|
name: eventType.team?.name || "Nameless",
|
2021-09-14 08:45:28 +00:00
|
|
|
}; // used for invitee emails
|
|
|
|
}
|
|
|
|
|
2022-05-05 21:16:25 +00:00
|
|
|
if (reqBody.recurringEventId && eventType.recurringEvent) {
|
|
|
|
// Overriding the recurring event configuration count to be the actual number of events booked for
|
|
|
|
// the recurring event (equal or less than recurring event configuration count)
|
|
|
|
eventType.recurringEvent = Object.assign({}, eventType.recurringEvent, { count: recurringCount });
|
2022-06-28 21:04:44 +00:00
|
|
|
evt.recurringEvent = eventType.recurringEvent;
|
2022-05-05 21:16:25 +00:00
|
|
|
}
|
|
|
|
|
2021-09-17 21:31:44 +00:00
|
|
|
// Initialize EventManager with credentials
|
2021-09-22 18:36:13 +00:00
|
|
|
const rescheduleUid = reqBody.rescheduleUid;
|
2022-04-14 21:25:24 +00:00
|
|
|
async function getOriginalRescheduledBooking(uid: string) {
|
|
|
|
return prisma.booking.findFirst({
|
|
|
|
where: {
|
|
|
|
uid,
|
|
|
|
status: {
|
2022-08-05 17:08:47 +00:00
|
|
|
in: [BookingStatus.ACCEPTED, BookingStatus.CANCELLED, BookingStatus.PENDING],
|
2022-04-14 21:25:24 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
include: {
|
|
|
|
attendees: {
|
|
|
|
select: {
|
|
|
|
name: true,
|
|
|
|
email: true,
|
|
|
|
locale: true,
|
|
|
|
timeZone: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
user: {
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
name: true,
|
|
|
|
email: true,
|
|
|
|
locale: true,
|
|
|
|
timeZone: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
payment: true,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
type BookingType = Prisma.PromiseReturnType<typeof getOriginalRescheduledBooking>;
|
|
|
|
let originalRescheduledBooking: BookingType = null;
|
|
|
|
if (rescheduleUid) {
|
|
|
|
originalRescheduledBooking = await getOriginalRescheduledBooking(rescheduleUid);
|
|
|
|
}
|
2021-09-22 18:36:13 +00:00
|
|
|
|
2022-02-01 21:48:40 +00:00
|
|
|
async function createBooking() {
|
2022-04-14 21:25:24 +00:00
|
|
|
if (originalRescheduledBooking) {
|
|
|
|
evt.title = originalRescheduledBooking?.title || evt.title;
|
|
|
|
evt.description = originalRescheduledBooking?.description || evt.additionalNotes;
|
|
|
|
evt.location = originalRescheduledBooking?.location;
|
|
|
|
}
|
|
|
|
|
2022-04-06 17:20:30 +00:00
|
|
|
const eventTypeRel = !eventTypeId
|
|
|
|
? {}
|
|
|
|
: {
|
|
|
|
connect: {
|
|
|
|
id: eventTypeId,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
const dynamicEventSlugRef = !eventTypeId ? eventTypeSlug : null;
|
|
|
|
const dynamicGroupSlugRef = !eventTypeId ? (reqBody.user as string).toLowerCase() : null;
|
2022-08-05 17:08:47 +00:00
|
|
|
|
|
|
|
// If the user is not the owner of the event, new booking should be always pending.
|
|
|
|
// Otherwise, an owner rescheduling should be always accepted.
|
|
|
|
const userReschedulingIsOwner = currentUser
|
|
|
|
? originalRescheduledBooking?.user?.id === currentUser.id
|
|
|
|
: false;
|
|
|
|
const isConfirmedByDefault =
|
|
|
|
(!eventType.requiresConfirmation && !eventType.price) || userReschedulingIsOwner;
|
2022-04-14 21:25:24 +00:00
|
|
|
const newBookingData: Prisma.BookingCreateInput = {
|
|
|
|
uid,
|
|
|
|
title: evt.title,
|
2022-07-07 01:08:38 +00:00
|
|
|
startTime: dayjs.utc(evt.startTime).toDate(),
|
|
|
|
endTime: dayjs.utc(evt.endTime).toDate(),
|
2022-04-14 21:25:24 +00:00
|
|
|
description: evt.additionalNotes,
|
2022-05-18 21:05:49 +00:00
|
|
|
customInputs: isPrismaObjOrUndefined(evt.customInputs),
|
2022-06-06 16:54:47 +00:00
|
|
|
status: isConfirmedByDefault ? BookingStatus.ACCEPTED : BookingStatus.PENDING,
|
2022-04-14 21:25:24 +00:00
|
|
|
location: evt.location,
|
|
|
|
eventType: eventTypeRel,
|
2022-07-14 00:10:45 +00:00
|
|
|
smsReminderNumber: reqBody.smsReminderNumber,
|
2022-04-14 21:25:24 +00:00
|
|
|
attendees: {
|
|
|
|
createMany: {
|
|
|
|
data: evt.attendees.map((attendee) => {
|
|
|
|
//if attendee is team member, it should fetch their locale not booker's locale
|
|
|
|
//perhaps make email fetch request to see if his locale is stored, else
|
|
|
|
const retObj = {
|
|
|
|
name: attendee.name,
|
|
|
|
email: attendee.email,
|
|
|
|
timeZone: attendee.timeZone,
|
|
|
|
locale: attendee.language.locale,
|
|
|
|
};
|
|
|
|
return retObj;
|
|
|
|
}),
|
2021-09-22 18:36:13 +00:00
|
|
|
},
|
2021-09-14 08:45:28 +00:00
|
|
|
},
|
2022-04-14 21:25:24 +00:00
|
|
|
dynamicEventSlugRef,
|
|
|
|
dynamicGroupSlugRef,
|
|
|
|
user: {
|
|
|
|
connect: {
|
2022-06-06 12:48:13 +00:00
|
|
|
id: organizerUser.id,
|
2021-09-22 18:36:13 +00:00
|
|
|
},
|
2022-04-14 21:25:24 +00:00
|
|
|
},
|
|
|
|
destinationCalendar: evt.destinationCalendar
|
|
|
|
? {
|
|
|
|
connect: { id: evt.destinationCalendar.id },
|
|
|
|
}
|
|
|
|
: undefined,
|
|
|
|
};
|
2022-05-05 21:16:25 +00:00
|
|
|
if (reqBody.recurringEventId) {
|
|
|
|
newBookingData.recurringEventId = reqBody.recurringEventId;
|
|
|
|
}
|
2022-04-14 21:25:24 +00:00
|
|
|
if (originalRescheduledBooking) {
|
|
|
|
newBookingData["paid"] = originalRescheduledBooking.paid;
|
|
|
|
newBookingData["fromReschedule"] = originalRescheduledBooking.uid;
|
|
|
|
if (newBookingData.attendees?.createMany?.data) {
|
|
|
|
newBookingData.attendees.createMany.data = originalRescheduledBooking.attendees;
|
|
|
|
}
|
2022-08-25 15:18:03 +00:00
|
|
|
if (originalRescheduledBooking.recurringEventId) {
|
|
|
|
newBookingData.recurringEventId = originalRescheduledBooking.recurringEventId;
|
|
|
|
}
|
2022-04-14 21:25:24 +00:00
|
|
|
}
|
|
|
|
const createBookingObj = {
|
|
|
|
include: {
|
2021-09-22 18:36:13 +00:00
|
|
|
user: {
|
2022-04-14 21:25:24 +00:00
|
|
|
select: { email: true, name: true, timeZone: true },
|
2021-09-22 18:36:13 +00:00
|
|
|
},
|
2022-04-14 21:25:24 +00:00
|
|
|
attendees: true,
|
|
|
|
payment: true,
|
2021-09-14 08:45:28 +00:00
|
|
|
},
|
2022-04-14 21:25:24 +00:00
|
|
|
data: newBookingData,
|
|
|
|
};
|
|
|
|
|
|
|
|
if (originalRescheduledBooking?.paid && originalRescheduledBooking?.payment) {
|
|
|
|
const bookingPayment = originalRescheduledBooking?.payment?.find((payment) => payment.success);
|
|
|
|
|
|
|
|
if (bookingPayment) {
|
|
|
|
createBookingObj.data.payment = {
|
|
|
|
connect: { id: bookingPayment.id },
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
if (typeof eventType.price === "number" && eventType.price > 0) {
|
|
|
|
/* Validate if there is any stripe_payment credential for this user */
|
2022-08-31 19:44:47 +00:00
|
|
|
/* note: removes custom error message about stripe */
|
|
|
|
await prisma.credential.findFirstOrThrow({
|
2022-06-10 18:38:46 +00:00
|
|
|
where: {
|
|
|
|
type: "stripe_payment",
|
|
|
|
userId: organizerUser.id,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
},
|
|
|
|
});
|
2022-05-16 16:27:36 +00:00
|
|
|
}
|
2022-06-10 18:38:46 +00:00
|
|
|
|
|
|
|
return prisma.booking.create(createBookingObj);
|
2021-09-22 18:36:13 +00:00
|
|
|
}
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-06-17 18:34:41 +00:00
|
|
|
let results: EventResult<AdditionalInformation>[] = [];
|
2021-09-22 18:36:13 +00:00
|
|
|
let referencesToCreate: PartialReference[] = [];
|
2021-10-05 22:46:48 +00:00
|
|
|
|
2022-03-07 17:55:24 +00:00
|
|
|
type Booking = Prisma.PromiseReturnType<typeof createBooking>;
|
|
|
|
let booking: Booking | null = null;
|
|
|
|
try {
|
|
|
|
booking = await createBooking();
|
2022-08-26 21:10:12 +00:00
|
|
|
// Sync Services
|
|
|
|
await syncServicesUpdateWebUser(
|
|
|
|
currentUser &&
|
|
|
|
(await prisma.user.findFirst({
|
|
|
|
where: { id: currentUser.id },
|
|
|
|
select: { id: true, email: true, name: true, plan: true, username: true, createdDate: true },
|
|
|
|
}))
|
|
|
|
);
|
2022-05-16 16:27:36 +00:00
|
|
|
evt.uid = booking?.uid ?? null;
|
2022-03-07 17:55:24 +00:00
|
|
|
} catch (_err) {
|
|
|
|
const err = getErrorFromUnknown(_err);
|
|
|
|
log.error(`Booking ${eventTypeId} failed`, "Error when saving booking to db", err.message);
|
|
|
|
if (err.code === "P2002") {
|
2022-06-10 18:38:46 +00:00
|
|
|
throw new HttpError({ statusCode: 409, message: "booking.conflict" });
|
2022-03-07 17:55:24 +00:00
|
|
|
}
|
2022-06-10 18:38:46 +00:00
|
|
|
throw err;
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
2021-10-05 22:46:48 +00:00
|
|
|
|
2021-09-23 09:35:39 +00:00
|
|
|
// After polling videoBusyTimes, credentials might have been changed due to refreshment, so query them again.
|
2022-08-15 19:52:01 +00:00
|
|
|
const credentials = await refreshCredentials(organizerUser.credentials);
|
|
|
|
const eventManager = new EventManager({ ...organizerUser, credentials });
|
2021-09-17 21:31:44 +00:00
|
|
|
|
2022-04-14 21:25:24 +00:00
|
|
|
if (originalRescheduledBooking?.uid) {
|
2021-09-14 08:45:28 +00:00
|
|
|
// Use EventManager to conditionally use all needed integrations.
|
2022-07-12 13:16:34 +00:00
|
|
|
const updateManager = await eventManager.reschedule(
|
2022-05-30 19:40:29 +00:00
|
|
|
evt,
|
|
|
|
originalRescheduledBooking.uid,
|
|
|
|
booking?.id,
|
|
|
|
reqBody.rescheduleReason
|
|
|
|
);
|
2022-04-03 17:59:40 +00:00
|
|
|
// 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.
|
2022-04-07 18:22:11 +00:00
|
|
|
evt.description = eventType.description;
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2021-11-26 11:03:43 +00:00
|
|
|
results = updateManager.results;
|
|
|
|
referencesToCreate = updateManager.referencesToCreate;
|
2022-05-12 09:33:15 +00:00
|
|
|
if (results.length > 0 && results.some((res) => !res.success)) {
|
2021-09-14 08:45:28 +00:00
|
|
|
const error = {
|
|
|
|
errorCode: "BookingReschedulingMeetingFailed",
|
|
|
|
message: "Booking Rescheduling failed",
|
|
|
|
};
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
log.error(`Booking ${organizerUser.name} failed`, error, results);
|
2021-11-26 11:03:43 +00:00
|
|
|
} else {
|
2022-06-06 19:49:00 +00:00
|
|
|
const metadata: AdditionalInformation = {};
|
2021-11-26 11:03:43 +00:00
|
|
|
|
|
|
|
if (results.length) {
|
|
|
|
// TODO: Handle created event metadata more elegantly
|
2022-02-10 10:44:46 +00:00
|
|
|
const [updatedEvent] = Array.isArray(results[0].updatedEvent)
|
|
|
|
? results[0].updatedEvent
|
|
|
|
: [results[0].updatedEvent];
|
|
|
|
if (updatedEvent) {
|
|
|
|
metadata.hangoutLink = updatedEvent.hangoutLink;
|
|
|
|
metadata.conferenceData = updatedEvent.conferenceData;
|
|
|
|
metadata.entryPoints = updatedEvent.entryPoints;
|
|
|
|
}
|
2021-11-26 11:03:43 +00:00
|
|
|
}
|
|
|
|
|
2022-05-05 21:16:25 +00:00
|
|
|
if (noEmail !== true) {
|
2022-06-10 00:32:34 +00:00
|
|
|
await sendRescheduledEmails({
|
|
|
|
...evt,
|
|
|
|
additionalInformation: metadata,
|
|
|
|
additionalNotes, // Resets back to the additionalNote input and not the override value
|
|
|
|
cancellationReason: reqBody.rescheduleReason,
|
|
|
|
});
|
2022-05-05 21:16:25 +00:00
|
|
|
}
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
2021-10-26 16:17:24 +00:00
|
|
|
// If it's not a reschedule, doesn't require confirmation and there's no price,
|
|
|
|
// Create a booking
|
2021-09-22 18:36:13 +00:00
|
|
|
} else if (!eventType.requiresConfirmation && !eventType.price) {
|
2021-09-14 08:45:28 +00:00
|
|
|
// Use EventManager to conditionally use all needed integrations.
|
2021-11-26 11:03:43 +00:00
|
|
|
const createManager = await eventManager.create(evt);
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-04-03 17:59:40 +00:00
|
|
|
// 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.
|
2022-04-07 18:22:11 +00:00
|
|
|
evt.description = eventType.description;
|
2022-04-03 17:59:40 +00:00
|
|
|
|
2021-11-26 11:03:43 +00:00
|
|
|
results = createManager.results;
|
|
|
|
referencesToCreate = createManager.referencesToCreate;
|
2021-09-14 08:45:28 +00:00
|
|
|
if (results.length > 0 && results.every((res) => !res.success)) {
|
|
|
|
const error = {
|
|
|
|
errorCode: "BookingCreatingMeetingFailed",
|
|
|
|
message: "Booking failed",
|
|
|
|
};
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
log.error(`Booking ${organizerUser.username} failed`, error, results);
|
2021-11-26 11:03:43 +00:00
|
|
|
} else {
|
2022-06-06 19:49:00 +00:00
|
|
|
const metadata: AdditionalInformation = {};
|
2021-11-26 11:03:43 +00:00
|
|
|
|
|
|
|
if (results.length) {
|
|
|
|
// TODO: Handle created event metadata more elegantly
|
|
|
|
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
|
|
|
|
metadata.conferenceData = results[0].createdEvent?.conferenceData;
|
|
|
|
metadata.entryPoints = results[0].createdEvent?.entryPoints;
|
|
|
|
}
|
2022-05-05 21:16:25 +00:00
|
|
|
if (noEmail !== true) {
|
2022-06-10 00:32:34 +00:00
|
|
|
await sendScheduledEmails({
|
|
|
|
...evt,
|
|
|
|
additionalInformation: metadata,
|
|
|
|
additionalNotes,
|
|
|
|
customInputs,
|
|
|
|
});
|
2022-05-05 21:16:25 +00:00
|
|
|
}
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-05 21:16:25 +00:00
|
|
|
if (eventType.requiresConfirmation && !rescheduleUid && noEmail !== true) {
|
2022-06-10 00:32:34 +00:00
|
|
|
await sendOrganizerRequestEmail({ ...evt, additionalNotes });
|
|
|
|
await sendAttendeeRequestEmail({ ...evt, additionalNotes }, attendeesList[0]);
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
|
|
|
|
2022-05-16 16:27:36 +00:00
|
|
|
if (
|
|
|
|
!Number.isNaN(eventType.price) &&
|
|
|
|
eventType.price > 0 &&
|
|
|
|
!originalRescheduledBooking?.paid &&
|
|
|
|
!!booking
|
|
|
|
) {
|
2022-08-15 19:52:01 +00:00
|
|
|
const [firstStripeCredential] = organizerUser.credentials.filter((cred) => cred.type == "stripe_payment");
|
2022-04-14 21:25:24 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
if (!firstStripeCredential)
|
|
|
|
throw new HttpError({ statusCode: 400, message: "Missing payment credentials" });
|
2022-05-11 20:36:38 +00:00
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
if (!booking.user) booking.user = organizerUser;
|
2022-06-10 18:38:46 +00:00
|
|
|
const payment = await handlePayment(evt, eventType, firstStripeCredential, booking);
|
2021-09-22 18:36:13 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
req.statusCode = 201;
|
|
|
|
return { ...booking, message: "Payment required", paymentUid: payment.uid };
|
2021-09-22 18:36:13 +00:00
|
|
|
}
|
|
|
|
|
2022-08-15 19:52:01 +00:00
|
|
|
log.debug(`Booking ${organizerUser.username} completed`);
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-08-15 20:18:41 +00:00
|
|
|
const eventTrigger: WebhookTriggerEvents = rescheduleUid
|
|
|
|
? WebhookTriggerEvents.BOOKING_RESCHEDULED
|
|
|
|
: WebhookTriggerEvents.BOOKING_CREATED;
|
2022-03-02 16:24:57 +00:00
|
|
|
const subscriberOptions = {
|
2022-08-15 19:52:01 +00:00
|
|
|
userId: organizerUser.id,
|
2022-03-02 16:24:57 +00:00
|
|
|
eventTypeId,
|
|
|
|
triggerEvent: eventTrigger,
|
|
|
|
};
|
|
|
|
|
2022-08-15 20:18:41 +00:00
|
|
|
const subscriberOptionsMeetingEnded = {
|
|
|
|
userId: organizerUser.id,
|
|
|
|
eventTypeId,
|
|
|
|
triggerEvent: WebhookTriggerEvents.MEETING_ENDED,
|
|
|
|
};
|
|
|
|
|
|
|
|
const subscribersMeetingEnded = await getSubscribers(subscriberOptionsMeetingEnded);
|
|
|
|
|
|
|
|
subscribersMeetingEnded.forEach((subscriber) => {
|
|
|
|
if (rescheduleUid && originalRescheduledBooking) {
|
|
|
|
cancelScheduledJobs(originalRescheduledBooking);
|
|
|
|
}
|
|
|
|
if (booking && booking.status === BookingStatus.ACCEPTED) {
|
|
|
|
scheduleTrigger(booking, subscriber.subscriberUrl, subscriber);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2021-10-07 15:14:47 +00:00
|
|
|
// Send Webhook call if hooked to BOOKING_CREATED & BOOKING_RESCHEDULED
|
2022-03-02 16:24:57 +00:00
|
|
|
const subscribers = await getSubscribers(subscriberOptions);
|
2021-12-03 10:15:20 +00:00
|
|
|
console.log("evt:", {
|
|
|
|
...evt,
|
|
|
|
metadata: reqBody.metadata,
|
|
|
|
});
|
2022-06-16 16:21:48 +00:00
|
|
|
const bookingId = booking?.id;
|
2021-11-22 11:37:07 +00:00
|
|
|
const promises = subscribers.map((sub) =>
|
2022-06-16 16:21:48 +00:00
|
|
|
sendPayload(sub.secret, eventTrigger, new Date().toISOString(), sub, {
|
2022-05-03 23:16:59 +00:00
|
|
|
...evt,
|
2022-06-16 16:21:48 +00:00
|
|
|
bookingId,
|
2022-05-03 23:16:59 +00:00
|
|
|
rescheduleUid,
|
|
|
|
metadata: reqBody.metadata,
|
2022-06-25 05:16:20 +00:00
|
|
|
eventTypeId,
|
2022-05-03 23:16:59 +00:00
|
|
|
}).catch((e) => {
|
2021-12-03 10:15:20 +00:00
|
|
|
console.error(`Error executing webhook for event: ${eventTrigger}, URL: ${sub.subscriberUrl}`, e);
|
|
|
|
})
|
2021-10-07 15:14:47 +00:00
|
|
|
);
|
|
|
|
await Promise.all(promises);
|
2022-03-24 23:29:32 +00:00
|
|
|
// Avoid passing referencesToCreate with id unique constrain values
|
2022-04-28 15:44:26 +00:00
|
|
|
// refresh hashed link if used
|
2022-06-10 18:38:46 +00:00
|
|
|
const urlSeed = `${organizerUser.username}:${dayjs(reqBody.start).utc().format()}`;
|
2022-04-28 15:44:26 +00:00
|
|
|
const hashedUid = translator.fromUUID(uuidv5(urlSeed, uuidv5.URL));
|
|
|
|
|
|
|
|
if (hasHashedBookingLink) {
|
|
|
|
await prisma.hashedLink.update({
|
|
|
|
where: {
|
|
|
|
link: reqBody.hashedLink as string,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
link: hashedUid,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
2022-06-10 18:38:46 +00:00
|
|
|
if (!booking) throw new HttpError({ statusCode: 400, message: "Booking failed" });
|
|
|
|
await prisma.booking.update({
|
|
|
|
where: {
|
|
|
|
uid: booking.uid,
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
references: {
|
|
|
|
createMany: {
|
|
|
|
data: referencesToCreate,
|
2022-05-16 16:27:36 +00:00
|
|
|
},
|
|
|
|
},
|
2022-06-10 18:38:46 +00:00
|
|
|
},
|
|
|
|
});
|
2022-07-14 00:10:45 +00:00
|
|
|
|
|
|
|
await scheduleWorkflowReminders(
|
|
|
|
eventType.workflows,
|
|
|
|
reqBody.smsReminderNumber as string | null,
|
|
|
|
evt,
|
2022-08-31 23:09:34 +00:00
|
|
|
evt.requiresConfirmation || false,
|
|
|
|
rescheduleUid ? true : false
|
2022-07-14 00:10:45 +00:00
|
|
|
);
|
2022-06-10 18:38:46 +00:00
|
|
|
// booking successful
|
|
|
|
req.statusCode = 201;
|
|
|
|
return booking;
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
2021-12-03 16:18:31 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
export default defaultResponder(handler);
|