Merge branch 'main' into bugfix/eventType-merge-artifacts

This commit is contained in:
Alex van Andel committed 2021-08-14 14:56:34 +00:00
commit 92d3f08f70
71 files changed
+3079 -1983

No files matched your search

+8 -24
View File
@@ -1,7 +1,7 @@
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../../lib/prisma";
import { getBusyCalendarTimes } from "../../../lib/calendarClient";
import { getBusyVideoTimes } from "../../../lib/videoClient";
import prisma from "@lib/prisma";
import { getBusyCalendarTimes } from "@lib/calendarClient";
import { getBusyVideoTimes } from "@lib/videoClient";
import dayjs from "dayjs";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
@@ -25,39 +25,23 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
const hasCalendarIntegrations =
currentUser.credentials.filter((cred) => cred.type.endsWith("_calendar")).length > 0;
const hasVideoIntegrations =
currentUser.credentials.filter((cred) => cred.type.endsWith("_video")).length > 0;
const calendarAvailability = await getBusyCalendarTimes(
const calendarBusyTimes = await getBusyCalendarTimes(
currentUser.credentials,
req.query.dateFrom,
req.query.dateTo,
selectedCalendars
);
const videoAvailability = await getBusyVideoTimes(
const videoBusyTimes = await getBusyVideoTimes(
currentUser.credentials,
req.query.dateFrom,
req.query.dateTo
);
calendarBusyTimes.push(...videoBusyTimes);
let commonAvailability = [];
if (hasCalendarIntegrations && hasVideoIntegrations) {
commonAvailability = calendarAvailability.filter((availability) =>
videoAvailability.includes(availability)
);
} else if (hasVideoIntegrations) {
commonAvailability = videoAvailability;
} else if (hasCalendarIntegrations) {
commonAvailability = calendarAvailability;
}
commonAvailability = commonAvailability.map((a) => ({
const bufferedBusyTimes = calendarBusyTimes.map((a) => ({
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toString(),
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toString(),
}));
res.status(200).json(commonAvailability);
res.status(200).json(bufferedBusyTimes);
}
+56 -229
View File
@@ -1,17 +1,15 @@
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@lib/prisma";
import { EventType } from "@prisma/client";
import { CalendarEvent, createEvent, getBusyCalendarTimes, updateEvent } from "../../../lib/calendarClient";
import async from "async";
import { EventType, User } from "@prisma/client";
import { CalendarEvent, getBusyCalendarTimes } from "@lib/calendarClient";
import { v5 as uuidv5 } from "uuid";
import short from "short-uuid";
import { createMeeting, getBusyVideoTimes, updateMeeting } from "../../../lib/videoClient";
import { getBusyVideoTimes } from "@lib/videoClient";
import EventAttendeeMail from "../../../lib/emails/EventAttendeeMail";
import { getEventName } from "../../../lib/event";
import { LocationType } from "../../../lib/location";
import merge from "lodash.merge";
import { getEventName } from "@lib/event";
import dayjs from "dayjs";
import logger from "../../../lib/logger";
import EventManager, { CreateUpdateResult, EventResult } from "@lib/events/EventManager";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
@@ -37,11 +35,6 @@ function isAvailable(busyTimes, time, length) {
const startTime = dayjs(busyTime.start);
const endTime = dayjs(busyTime.end);
// Check if start times are the same
if (dayjs(time).format("HH:mm") == startTime.format("HH:mm")) {
t = false;
}
// Check if time is between start and end times
if (dayjs(time).isBetween(startTime, endTime)) {
t = false;
@@ -88,167 +81,8 @@ function isOutOfBounds(
}
}
interface GetLocationRequestFromIntegrationRequest {
location: string;
}
const getLocationRequestFromIntegration = ({ location }: GetLocationRequestFromIntegrationRequest) => {
if (location === LocationType.GoogleMeet.valueOf()) {
const requestId = uuidv5(location, uuidv5.URL);
return {
conferenceData: {
createRequest: {
requestId: requestId,
},
},
};
}
return null;
};
async function rescheduleEvent(
rescheduleUid: string | string[],
results: unknown[],
calendarCredentials: unknown[],
evt: CalendarEvent,
videoCredentials: unknown[],
referencesToCreate: { type: string; uid: string }[]
): Promise<{
referencesToCreate: { type: string; uid: string }[];
results: unknown[];
error: { errorCode: string; message: string } | null;
}> {
// Reschedule event
const booking = await prisma.booking.findFirst({
where: {
uid: rescheduleUid,
},
select: {
id: true,
references: {
select: {
id: true,
type: true,
uid: true,
},
},
},
});
// Use all integrations
results = results.concat(
await async.mapLimit(calendarCredentials, 5, async (credential) => {
const bookingRefUid = booking.references.filter((ref) => ref.type === credential.type)[0].uid;
return updateEvent(credential, bookingRefUid, evt)
.then((response) => ({ type: credential.type, success: true, response }))
.catch((e) => {
log.error("updateEvent failed", e, evt);
return { type: credential.type, success: false };
});
})
);
results = results.concat(
await async.mapLimit(videoCredentials, 5, async (credential) => {
const bookingRefUid = booking.references.filter((ref) => ref.type === credential.type)[0].uid;
return updateMeeting(credential, bookingRefUid, evt)
.then((response) => ({ type: credential.type, success: true, response }))
.catch((e) => {
log.error("updateMeeting failed", e, evt);
return { type: credential.type, success: false };
});
})
);
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingReschedulingMeetingFailed",
message: "Booking Rescheduling failed",
};
return { referencesToCreate: [], results: [], error: error };
}
// Clone elements
referencesToCreate = [...booking.references];
// Now we can delete the old booking and its references.
const bookingReferenceDeletes = prisma.bookingReference.deleteMany({
where: {
bookingId: booking.id,
},
});
const attendeeDeletes = prisma.attendee.deleteMany({
where: {
bookingId: booking.id,
},
});
const bookingDeletes = prisma.booking.delete({
where: {
uid: rescheduleUid,
},
});
await Promise.all([bookingReferenceDeletes, attendeeDeletes, bookingDeletes]);
return { error: undefined, results, referencesToCreate };
}
export async function scheduleEvent(
results: unknown[],
calendarCredentials: unknown[],
evt: CalendarEvent,
videoCredentials: unknown[],
referencesToCreate: { type: string; uid: string }[]
): Promise<{
referencesToCreate: { type: string; uid: string }[];
results: unknown[];
error: { errorCode: string; message: string } | null;
}> {
// Schedule event
results = results.concat(
await async.mapLimit(calendarCredentials, 5, async (credential) => {
return createEvent(credential, evt)
.then((response) => ({ type: credential.type, success: true, response }))
.catch((e) => {
log.error("createEvent failed", e, evt);
return { type: credential.type, success: false };
});
})
);
results = results.concat(
await async.mapLimit(videoCredentials, 5, async (credential) => {
return createMeeting(credential, evt)
.then((response) => ({ type: credential.type, success: true, response }))
.catch((e) => {
log.error("createMeeting failed", e, evt);
return { type: credential.type, success: false };
});
})
);
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingCreatingMeetingFailed",
message: "Booking failed",
};
return { referencesToCreate: [], results: [], error: error };
}
referencesToCreate = results.map((result) => {
return {
type: result.type,
uid: result.response.createdEvent.id.toString(),
};
});
return { error: undefined, results, referencesToCreate };
}
export async function handleLegacyConfirmationMail(
results: unknown[],
results: Array<EventResult>,
eventType: EventType,
evt: CalendarEvent,
hashUID: string
@@ -285,7 +119,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return res.status(400).json(error);
}
let currentUser = await prisma.user.findFirst({
let currentUser: User = await prisma.user.findFirst({
where: {
username: user,
},
@@ -315,11 +149,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
dayjs(req.body.end).endOf("day").utc().format("YYYY-MM-DDTHH:mm:ss[Z]"),
selectedCalendars
);
const videoAvailability = await getBusyVideoTimes(
currentUser.credentials,
dayjs(req.body.start).startOf("day").utc().format(),
dayjs(req.body.end).endOf("day").utc().format()
);
const videoAvailability = await getBusyVideoTimes(currentUser.credentials);
let commonAvailability = [];
if (hasCalendarIntegrations && hasVideoIntegrations) {
@@ -346,8 +176,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
const calendarCredentials = currentUser.credentials.filter((cred) => cred.type.endsWith("_calendar"));
const videoCredentials = currentUser.credentials.filter((cred) => cred.type.endsWith("_video"));
// Initialize EventManager with credentials
const eventManager = new EventManager(currentUser.credentials);
const rescheduleUid = req.body.rescheduleUid;
const eventType: EventType = await prisma.eventType.findFirst({
@@ -369,35 +199,28 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
const rawLocation = req.body.location;
const invitee = [{ email: req.body.email, name: req.body.name, timeZone: req.body.timeZone }];
const guests = req.body.guests.map((guest) => {
const g = {
email: guest,
name: "",
timeZone: req.body.timeZone,
};
return g;
});
const attendeesList = [...invitee, ...guests];
let evt: CalendarEvent = {
const evt: CalendarEvent = {
type: eventType.title,
title: getEventName(req.body.name, eventType.title, eventType.eventName),
description: req.body.notes,
startTime: req.body.start,
endTime: req.body.end,
organizer: { email: currentUser.email, name: currentUser.name, timeZone: currentUser.timeZone },
attendees: [{ email: req.body.email, name: req.body.name, timeZone: req.body.timeZone }],
attendees: attendeesList,
location: req.body.location, // Will be processed by the EventManager later.
};
// If phone or inPerson use raw location
// set evt.location to req.body.location
if (!rawLocation?.includes("integration")) {
evt.location = rawLocation;
}
// If location is set to an integration location
// Build proper transforms for evt object
// Extend evt object with those transformations
if (rawLocation?.includes("integration")) {
const maybeLocationRequestObject = getLocationRequestFromIntegration({
location: rawLocation,
});
evt = merge(evt, maybeLocationRequestObject);
}
let isAvailableToBeBooked = true;
try {
@@ -445,44 +268,47 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return res.status(400).json(error);
}
let results = [];
let results: Array<EventResult> = [];
let referencesToCreate = [];
if (rescheduleUid) {
const __ret = await rescheduleEvent(
rescheduleUid,
results,
calendarCredentials,
evt,
videoCredentials,
referencesToCreate
);
if (__ret.error) {
log.error(`Booking ${user} failed`, __ret.error, results);
return res.status(500).json(__ret.error);
// Use EventManager to conditionally use all needed integrations.
const updateResults: CreateUpdateResult = await eventManager.update(evt, rescheduleUid);
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingReschedulingMeetingFailed",
message: "Booking Rescheduling failed",
};
log.error(`Booking ${user} failed`, error, results);
return res.status(500).json(error);
}
results = __ret.results;
referencesToCreate = __ret.referencesToCreate;
// Forward results
results = updateResults.results;
referencesToCreate = updateResults.referencesToCreate;
} else if (!eventType.requiresConfirmation) {
const __ret = await scheduleEvent(
results,
calendarCredentials,
evt,
videoCredentials,
referencesToCreate
);
if (__ret.error) {
log.error(`Booking ${user} failed`, __ret.error, results);
return res.status(500).json(__ret.error);
// Use EventManager to conditionally use all needed integrations.
const createResults: CreateUpdateResult = await eventManager.create(evt);
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingCreatingMeetingFailed",
message: "Booking failed",
};
log.error(`Booking ${user} failed`, error, results);
return res.status(500).json(error);
}
results = __ret.results;
referencesToCreate = __ret.referencesToCreate;
// Forward results
results = createResults.results;
referencesToCreate = createResults.referencesToCreate;
}
const hashUID =
results.length > 0
? results[0].response.uid
: translator.fromUUID(uuidv5(JSON.stringify(evt), uuidv5.URL));
results.length > 0 ? results[0].uid : translator.fromUUID(uuidv5(JSON.stringify(evt), uuidv5.URL));
// TODO Should just be set to the true case as soon as we have a "bare email" integration class.
// UID generation should happen in the integration itself, not here.
const legacyMailError = await handleLegacyConfirmationMail(results, eventType, evt, hashUID);
@@ -510,6 +336,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
create: evt.attendees,
},
confirmed: !eventType.requiresConfirmation,
location: evt.location,
},
});
} catch (e) {
+6 -5
View File
@@ -1,9 +1,10 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "next-auth/client";
import prisma from "../../../lib/prisma";
import { handleLegacyConfirmationMail, scheduleEvent } from "./[user]";
import { handleLegacyConfirmationMail } from "./[user]";
import { CalendarEvent } from "@lib/calendarClient";
import EventRejectionMail from "@lib/emails/EventRejectionMail";
import EventManager from "@lib/events/EventManager";
export default async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
const session = await getSession({ req: req });
@@ -41,6 +42,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
endTime: true,
confirmed: true,
attendees: true,
location: true,
userId: true,
id: true,
uid: true,
@@ -54,9 +56,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return res.status(400).json({ message: "booking already confirmed" });
}
const calendarCredentials = currentUser.credentials.filter((cred) => cred.type.endsWith("_calendar"));
const videoCredentials = currentUser.credentials.filter((cred) => cred.type.endsWith("_video"));
const evt: CalendarEvent = {
type: booking.title,
title: booking.title,
@@ -65,10 +64,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
endTime: booking.endTime.toISOString(),
organizer: { email: currentUser.email, name: currentUser.name, timeZone: currentUser.timeZone },
attendees: booking.attendees,
location: booking.location,
};
if (req.body.confirmed) {
const scheduleResult = await scheduleEvent([], calendarCredentials, evt, videoCredentials, []);
const eventManager = new EventManager(currentUser.credentials);
const scheduleResult = await eventManager.create(evt, booking.uid);
await handleLegacyConfirmationMail(
scheduleResult.results,
+25 -28
View File
@@ -1,7 +1,7 @@
import prisma from '../../lib/prisma';
import {deleteEvent} from "../../lib/calendarClient";
import async from 'async';
import {deleteMeeting} from "../../lib/videoClient";
import prisma from "../../lib/prisma";
import { deleteEvent } from "../../lib/calendarClient";
import async from "async";
import { deleteMeeting } from "../../lib/videoClient";
export default async function handler(req, res) {
if (req.method == "POST") {
@@ -15,36 +15,38 @@ export default async function handler(req, res) {
id: true,
user: {
select: {
credentials: true
}
credentials: true,
},
},
attendees: true,
references: {
select: {
uid: true,
type: true
}
}
}
type: true,
},
},
},
});
const apiDeletes = async.mapLimit(bookingToDelete.user.credentials, 5, async (credential) => {
const bookingRefUid = bookingToDelete.references.filter((ref) => ref.type === credential.type)[0].uid;
if(credential.type.endsWith("_calendar")) {
return await deleteEvent(credential, bookingRefUid);
} else if(credential.type.endsWith("_video")) {
return await deleteMeeting(credential, bookingRefUid);
const bookingRefUid = bookingToDelete.references.filter((ref) => ref.type === credential.type)[0]?.uid;
if (bookingRefUid) {
if (credential.type.endsWith("_calendar")) {
return await deleteEvent(credential, bookingRefUid);
} else if (credential.type.endsWith("_video")) {
return await deleteMeeting(credential, bookingRefUid);
}
}
});
const attendeeDeletes = prisma.attendee.deleteMany({
where: {
bookingId: bookingToDelete.id
}
bookingId: bookingToDelete.id,
},
});
const bookingReferenceDeletes = prisma.bookingReference.deleteMany({
where: {
bookingId: bookingToDelete.id
}
bookingId: bookingToDelete.id,
},
});
const bookingDeletes = prisma.booking.delete({
where: {
@@ -52,17 +54,12 @@ export default async function handler(req, res) {
},
});
await Promise.all([
apiDeletes,
attendeeDeletes,
bookingReferenceDeletes,
bookingDeletes
]);
await Promise.all([apiDeletes, attendeeDeletes, bookingReferenceDeletes, bookingDeletes]);
//TODO Perhaps send emails to user and client to tell about the cancellation
res.status(200).json({message: 'Booking successfully deleted.'});
res.status(200).json({ message: "Booking successfully deleted." });
} else {
res.status(405).json({message: 'This endpoint only accepts POST requests.'});
res.status(405).json({ message: "This endpoint only accepts POST requests." });
}
}
}