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-05-05 21:16:25 +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-03-23 22:00:30 +00:00
|
|
|
import EventManager from "@calcom/core/EventManager";
|
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-06-10 18:38:46 +00:00
|
|
|
import { getLuckyUsers, 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-07-22 17:27:06 +00:00
|
|
|
import isOutOfBounds from "@calcom/lib/isOutOfBounds";
|
2022-03-23 22:00:30 +00:00
|
|
|
import logger from "@calcom/lib/logger";
|
2022-06-10 18:38:46 +00:00
|
|
|
import { defaultResponder } from "@calcom/lib/server";
|
|
|
|
import prisma, { userSelect } from "@calcom/prisma";
|
|
|
|
import { extendedBookingCreateBody } from "@calcom/prisma/zod-utils";
|
2022-07-22 17:27:06 +00:00
|
|
|
import { handlePayment } from "@calcom/stripe/server";
|
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";
|
2022-07-14 00:10:45 +00:00
|
|
|
import { scheduleWorkflowReminders } from "@ee/lib/workflows/reminders/reminderScheduler";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
import { HttpError } from "@lib/core/http/error";
|
2021-12-03 16:18:31 +00:00
|
|
|
import { ensureArray } from "@lib/ensureArray";
|
2021-09-22 19:52:38 +00:00
|
|
|
import { getEventName } from "@lib/event";
|
2021-10-07 15:14:47 +00:00
|
|
|
import sendPayload from "@lib/webhooks/sendPayload";
|
2021-11-22 11:37:07 +00:00
|
|
|
import getSubscribers from "@lib/webhooks/subscriptions";
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2021-10-25 13:05:21 +00:00
|
|
|
import { getTranslation } from "@server/lib/i18n";
|
|
|
|
|
2022-02-02 11:07:13 +00:00
|
|
|
import verifyAccount from "../../../web3/utils/verifyAccount";
|
|
|
|
|
2021-09-14 08:45:28 +00:00
|
|
|
const translator = short();
|
|
|
|
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2021-12-03 16:18:31 +00:00
|
|
|
const getUserNameWithBookingCounts = async (eventTypeId: number, selectedUserNames: string[]) => {
|
|
|
|
const users = await prisma.user.findMany({
|
|
|
|
where: {
|
|
|
|
username: { in: selectedUserNames },
|
2021-12-09 12:25:38 +00:00
|
|
|
eventTypes: {
|
2021-12-03 16:18:31 +00:00
|
|
|
some: {
|
2021-12-09 12:25:38 +00:00
|
|
|
id: eventTypeId,
|
2021-12-03 16:18:31 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
id: true,
|
|
|
|
username: true,
|
2022-01-27 20:32:53 +00:00
|
|
|
locale: true,
|
2021-12-03 16:18:31 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const userNamesWithBookingCounts = await Promise.all(
|
|
|
|
users.map(async (user) => ({
|
|
|
|
username: user.username,
|
|
|
|
bookingCount: await prisma.booking.count({
|
|
|
|
where: {
|
|
|
|
user: {
|
|
|
|
id: user.id,
|
|
|
|
},
|
|
|
|
startTime: {
|
|
|
|
gt: new Date(),
|
|
|
|
},
|
|
|
|
eventTypeId,
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
}))
|
|
|
|
);
|
|
|
|
|
|
|
|
return userNamesWithBookingCounts;
|
|
|
|
};
|
|
|
|
|
2022-04-06 17:20:30 +00:00
|
|
|
const getEventTypesFromDB = async (eventTypeId: number) => {
|
2022-05-05 21:16:25 +00:00
|
|
|
const eventType = await prisma.eventType.findUnique({
|
2021-12-17 16:58:23 +00:00
|
|
|
rejectOnNotFound: true,
|
2021-09-14 08:45:28 +00:00
|
|
|
where: {
|
|
|
|
id: eventTypeId,
|
|
|
|
},
|
|
|
|
select: {
|
2022-06-15 20:54:31 +00:00
|
|
|
id: 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-05-05 21:16:25 +00:00
|
|
|
};
|
2022-04-06 17:20:30 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
type User = Prisma.UserGetPayload<typeof userSelect>;
|
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
async function handler(req: NextApiRequest) {
|
|
|
|
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`);
|
|
|
|
|
|
|
|
const isTimeInPast = (time: string): boolean => {
|
|
|
|
return dayjs(time).isBefore(new Date(), "day");
|
|
|
|
};
|
|
|
|
|
|
|
|
if (isTimeInPast(reqBody.start)) {
|
|
|
|
const error = {
|
|
|
|
errorCode: "BookingDateInPast",
|
|
|
|
message: "Attempting to create a meeting in the past.",
|
|
|
|
};
|
|
|
|
|
|
|
|
log.error(`Booking ${eventTypeId} failed`, error);
|
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-06-11 21:30:52 +00:00
|
|
|
const eventType =
|
|
|
|
!eventTypeId && !!eventTypeSlug ? getDefaultEvent(eventTypeSlug) : await getEventTypesFromDB(eventTypeId);
|
2022-06-10 18:38:46 +00:00
|
|
|
if (!eventType) throw new HttpError({ statusCode: 404, message: "eventType.notFound" });
|
2021-09-22 18:36:13 +00:00
|
|
|
|
2022-07-12 13:16:34 +00:00
|
|
|
let user: User | null = null;
|
2022-04-06 17:20:30 +00:00
|
|
|
let users = !eventTypeId
|
|
|
|
? await prisma.user.findMany({
|
|
|
|
where: {
|
|
|
|
username: {
|
|
|
|
in: dynamicUserList,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
...userSelect,
|
|
|
|
})
|
|
|
|
: eventType.users;
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2021-09-22 18:36:13 +00:00
|
|
|
/* If this event was pre-relationship migration */
|
|
|
|
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-06-06 12:48:13 +00:00
|
|
|
const [organizerUser] = users;
|
2022-01-27 20:32:53 +00:00
|
|
|
const organizer = await prisma.user.findUnique({
|
|
|
|
where: {
|
2022-06-06 12:48:13 +00:00
|
|
|
id: organizerUser.id,
|
2022-01-27 20:32:53 +00:00
|
|
|
},
|
|
|
|
select: {
|
|
|
|
locale: true,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const tOrganizer = await getTranslation(organizer?.locale ?? "en", "common");
|
|
|
|
|
2021-09-14 08:45:28 +00:00
|
|
|
if (eventType.schedulingType === SchedulingType.ROUND_ROBIN) {
|
2021-12-03 16:18:31 +00:00
|
|
|
const bookingCounts = await getUserNameWithBookingCounts(
|
|
|
|
eventTypeId,
|
|
|
|
ensureArray(reqBody.user) || users.map((user) => user.username)
|
|
|
|
);
|
2021-09-22 18:36:13 +00:00
|
|
|
|
2021-12-03 16:18:31 +00:00
|
|
|
users = getLuckyUsers(users, bookingCounts);
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
|
|
|
|
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-07-01 19:19:23 +00:00
|
|
|
const location = !!eventType.locations ? (eventType.locations as Array<{ type: string }>)[0] : "";
|
|
|
|
const locationType = !!location && location.type ? location.type : "";
|
2022-05-24 13:19:12 +00:00
|
|
|
|
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",
|
|
|
|
location: locationType,
|
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-01-27 20:32:53 +00:00
|
|
|
language: { translate: tOrganizer, locale: organizer?.locale ?? "en" },
|
2021-09-14 08:45:28 +00:00
|
|
|
},
|
|
|
|
attendees: attendeesList,
|
2021-09-22 18:36:13 +00:00
|
|
|
location: reqBody.location, // 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-07-12 13:16:34 +00:00
|
|
|
user = users[0];
|
|
|
|
const credentials = await refreshCredentials(user.credentials);
|
|
|
|
const eventManager = new EventManager({ ...user, credentials });
|
|
|
|
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: {
|
|
|
|
in: [BookingStatus.ACCEPTED, BookingStatus.CANCELLED],
|
|
|
|
},
|
|
|
|
},
|
|
|
|
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() {
|
|
|
|
// @TODO: check as metadata
|
2022-06-10 18:38:46 +00:00
|
|
|
if (reqBody.web3Details) {
|
|
|
|
const { web3Details } = reqBody;
|
2022-02-01 21:48:40 +00:00
|
|
|
await verifyAccount(web3Details.userSignature, web3Details.userWallet);
|
|
|
|
}
|
|
|
|
|
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-06-06 16:54:47 +00:00
|
|
|
const isConfirmedByDefault = (!eventType.requiresConfirmation && !eventType.price) || !!rescheduleUid;
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
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 */
|
|
|
|
await prisma.credential.findFirst({
|
|
|
|
rejectOnNotFound(err) {
|
|
|
|
throw new HttpError({ statusCode: 400, message: "Missing stripe credentials", cause: err });
|
|
|
|
},
|
|
|
|
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
|
|
|
/** Let's start checking for availability */
|
2021-09-22 18:36:13 +00:00
|
|
|
for (const currentUser of users) {
|
|
|
|
if (!currentUser) {
|
|
|
|
console.error(`currentUser not found`);
|
2022-06-10 18:38:46 +00:00
|
|
|
continue;
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
2021-09-22 18:36:13 +00:00
|
|
|
if (!user) user = currentUser;
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
const { busy: bufferedBusyTimes } = await getUserAvailability(
|
|
|
|
{
|
2021-09-14 08:45:28 +00:00
|
|
|
userId: currentUser.id,
|
2022-06-10 18:38:46 +00:00
|
|
|
dateFrom: reqBody.start,
|
|
|
|
dateTo: reqBody.end,
|
|
|
|
eventTypeId,
|
2021-09-14 08:45:28 +00:00
|
|
|
},
|
2022-06-10 18:38:46 +00:00
|
|
|
{ user, eventType }
|
|
|
|
);
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
console.log("calendarBusyTimes==>>>", bufferedBusyTimes);
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-03-07 17:55:24 +00:00
|
|
|
let isAvailableToBeBooked = true;
|
|
|
|
try {
|
2022-05-05 21:16:25 +00:00
|
|
|
if (eventType.recurringEvent) {
|
2022-06-10 00:32:34 +00:00
|
|
|
const recurringEvent = parseRecurringEvent(eventType.recurringEvent);
|
|
|
|
const allBookingDates = new rrule({ dtstart: new Date(reqBody.start), ...recurringEvent }).all();
|
2022-05-05 21:16:25 +00:00
|
|
|
// Go through each date for the recurring event and check if each one's availability
|
2022-06-10 18:38:46 +00:00
|
|
|
// 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;
|
|
|
|
}
|
2022-05-05 21:16:25 +00:00
|
|
|
} else {
|
|
|
|
isAvailableToBeBooked = isAvailable(bufferedBusyTimes, reqBody.start, eventType.length);
|
|
|
|
}
|
2022-03-07 17:55:24 +00:00
|
|
|
} catch {
|
|
|
|
log.debug({
|
|
|
|
message: "Unable set isAvailableToBeBooked. Using true. ",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!isAvailableToBeBooked) {
|
|
|
|
const error = {
|
|
|
|
errorCode: "BookingUserUnAvailable",
|
|
|
|
message: `${currentUser.name} is unavailable at this time.`,
|
|
|
|
};
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-03-07 17:55:24 +00:00
|
|
|
log.debug(`Booking ${currentUser.name} failed`, error);
|
2022-06-10 18:38:46 +00:00
|
|
|
throw new HttpError({ statusCode: 409, message: error.message });
|
2022-03-07 17:55:24 +00:00
|
|
|
}
|
2021-09-14 08:45:28 +00:00
|
|
|
|
2022-03-07 17:55:24 +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 {
|
|
|
|
log.debug({
|
|
|
|
message: "Unable set timeOutOfBounds. Using false. ",
|
|
|
|
});
|
2021-09-14 08:45:28 +00:00
|
|
|
}
|
2022-03-07 17:55:24 +00:00
|
|
|
|
|
|
|
if (timeOutOfBounds) {
|
|
|
|
const error = {
|
|
|
|
errorCode: "BookingUserUnAvailable",
|
|
|
|
message: `${currentUser.name} is unavailable at this time.`,
|
|
|
|
};
|
|
|
|
|
|
|
|
log.debug(`Booking ${currentUser.name} failed`, error);
|
2022-06-10 18:38:46 +00:00
|
|
|
throw new HttpError({ statusCode: 409, message: error.message });
|
2022-03-07 17:55:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type Booking = Prisma.PromiseReturnType<typeof createBooking>;
|
|
|
|
let booking: Booking | null = null;
|
|
|
|
try {
|
|
|
|
booking = await createBooking();
|
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
|
|
|
|
2022-06-10 18:38:46 +00:00
|
|
|
if (!user) throw new HttpError({ statusCode: 404, message: "Can't continue, user not found." });
|
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.
|
2021-12-09 15:51:37 +00:00
|
|
|
const credentials = await refreshCredentials(user.credentials);
|
|
|
|
const eventManager = new EventManager({ ...user, 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",
|
|
|
|
};
|
|
|
|
|
|
|
|
log.error(`Booking ${user.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",
|
|
|
|
};
|
|
|
|
|
|
|
|
log.error(`Booking ${user.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-06-10 18:38:46 +00:00
|
|
|
const [firstStripeCredential] = user.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-06-10 18:38:46 +00:00
|
|
|
if (!booking.user) booking.user = user;
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-09-14 08:45:28 +00:00
|
|
|
log.debug(`Booking ${user.username} completed`);
|
|
|
|
|
2022-03-02 16:24:57 +00:00
|
|
|
const eventTrigger: WebhookTriggerEvents = rescheduleUid ? "BOOKING_RESCHEDULED" : "BOOKING_CREATED";
|
|
|
|
const subscriberOptions = {
|
|
|
|
userId: user.id,
|
|
|
|
eventTypeId,
|
|
|
|
triggerEvent: eventTrigger,
|
|
|
|
};
|
|
|
|
|
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,
|
|
|
|
evt.requiresConfirmation || false
|
|
|
|
);
|
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);
|