Feature/round robin (#613)

* Heavy WIP

* More WIP

* Playing with backwards compat

* Moar wip

* wip

* Email changes for group feature

* Committing in redundant migrations for reference

* Combine all WIP migrations into a single feature migration

* Make backup of current version of radio area pending refactor

* Improved accessibility through keyboard

* Cleanup in seperate commit so I can cherrypick later

* Added RadioArea component

* wip

* Ignore .yarn file

* Kinda stable

* Getting closer...

* Hide header when there are only personal events

* Added uid to event create, updated EventTypeDescription

* Delete redundant migration

* Committing new team related migrations

* Optimising & implemented backwards compatibility

* Removed now redundant pages

* Undid prototyping to calendarClient I did not end up using

* Properly typed Select & fixed lint throughout

* How'd that get here, removed.

* TODO: investigate why userData is not compatible with passed type

* This likely matches the event type that is created for a user

* Few bugfixes

* Adding datepicker optimisations

* Fixed new event type spacing, initial profile should always be there

* Gave NEXT_PUBLIC_BASE_URL a try but I think it's not the right solution

* Updated EventTypeDescription to account for long titles, added logo to team page.

* Added logo to team query

* Added cancel Cypress test because an upcoming merge contains changes

* Fix for when the event type description is long

* Turned Theme into the useTheme hook, and made it fully compatible with teams pages

* Built AvatarGroup ui component + moved Avatar to ui

* Give the avatar some space fom the description

* Fixed timeZone selector

* Disabled tooltip +1-...

Co-authored-by: Bailey Pumfleet <[email protected]>
This commit is contained in:
Alex van AndelandBailey Pumfleet authored and GitHub committed 2021-09-14 09:45:28 +01:00
1 parent e9ff62109d
commit 6ab741b927
54 files changed
+3980 -2413

No files matched your search

+28 -13
View File
@@ -3,11 +3,19 @@ import prisma from "@lib/prisma";
import { getBusyCalendarTimes } from "@lib/calendarClient";
// import { getBusyVideoTimes } from "@lib/videoClient";
import dayjs from "dayjs";
import { asStringOrNull } from "@lib/asStringOrNull";
import { User } from "@prisma/client";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { user } = req.query;
const user = asStringOrNull(req.query.user);
const dateFrom = dayjs(asStringOrNull(req.query.dateFrom));
const dateTo = dayjs(asStringOrNull(req.query.dateTo));
const currentUser = await prisma.user.findFirst({
if (!dateFrom.isValid() || !dateTo.isValid()) {
return res.status(400).json({ message: "Invalid time range given." });
}
const currentUser: User = await prisma.user.findUnique({
where: {
username: user,
},
@@ -15,7 +23,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
credentials: true,
timeZone: true,
bufferTime: true,
availability: true,
id: true,
startTime: true,
endTime: true,
},
});
@@ -25,23 +36,27 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
const calendarBusyTimes = await getBusyCalendarTimes(
const busyTimes = await getBusyCalendarTimes(
currentUser.credentials,
req.query.dateFrom,
req.query.dateTo,
dateFrom.format(),
dateTo.format(),
selectedCalendars
);
// const videoBusyTimes = await getBusyVideoTimes(
// currentUser.credentials,
// req.query.dateFrom,
// req.query.dateTo
// );
// calendarBusyTimes.push(...videoBusyTimes);
const bufferedBusyTimes = calendarBusyTimes.map((a) => ({
// busyTimes.push(...await getBusyVideoTimes(currentUser.credentials, dateFrom.format(), dateTo.format()));
const bufferedBusyTimes = busyTimes.map((a) => ({
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toString(),
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toString(),
}));
res.status(200).json(bufferedBusyTimes);
res.status(200).json({
busy: bufferedBusyTimes,
workingHours: {
daysOfWeek: [0, 1, 2, 3, 4, 5, 6],
timeZone: currentUser.timeZone,
startTime: currentUser.startTime,
endTime: currentUser.endTime,
},
});
}
+24 -1
View File
@@ -61,15 +61,38 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
minimumBookingNotice: req.body.minimumBookingNotice,
};
if (req.body.schedulingType) {
data.schedulingType = req.body.schedulingType;
}
if (req.method == "POST") {
if (req.body.teamId) {
data.team = {
connect: {
id: req.body.teamId,
},
};
}
const eventType = await prisma.eventType.create({
data: {
userId: session.user.id,
...data,
users: {
connect: {
id: parseInt(session.user.id),
},
},
},
});
res.status(201).json({ eventType });
} else if (req.method == "PATCH") {
if (req.body.users) {
data.users = {
set: [],
connect: req.body.users.map((id: number) => ({ id })),
};
}
if (req.body.timeZone) {
data.timeZone = req.body.timeZone;
}
-330
View File
@@ -1,330 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@lib/prisma";
import { EventType, User } from "@prisma/client";
import { CalendarEvent, getBusyCalendarTimes } from "@lib/calendarClient";
import { v5 as uuidv5 } from "uuid";
import short from "short-uuid";
import { getBusyVideoTimes } from "@lib/videoClient";
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";
import isBetween from "dayjs/plugin/isBetween";
import dayjsBusinessDays from "dayjs-business-days";
import EventOrganizerRequestMail from "@lib/emails/EventOrganizerRequestMail";
dayjs.extend(dayjsBusinessDays);
dayjs.extend(utc);
dayjs.extend(isBetween);
dayjs.extend(timezone);
const translator = short();
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
function isAvailable(busyTimes, time, length) {
// Check for conflicts
let t = true;
if (Array.isArray(busyTimes) && busyTimes.length > 0) {
busyTimes.forEach((busyTime) => {
const startTime = dayjs(busyTime.start);
const endTime = dayjs(busyTime.end);
// Check if time is between start and end times
if (dayjs(time).isBetween(startTime, endTime, null, "[)")) {
t = false;
}
// Check if slot end time is between start and end time
if (dayjs(time).add(length, "minutes").isBetween(startTime, endTime)) {
t = false;
}
// Check if startTime is between slot
if (startTime.isBetween(dayjs(time), dayjs(time).add(length, "minutes"))) {
t = false;
}
});
}
return t;
}
function isOutOfBounds(
time: dayjs.ConfigType,
{ periodType, periodDays, periodCountCalendarDays, periodStartDate, periodEndDate, timeZone }
): boolean {
const date = dayjs(time);
switch (periodType) {
case "rolling": {
const periodRollingEndDay = periodCountCalendarDays
? dayjs().tz(timeZone).add(periodDays, "days").endOf("day")
: dayjs().tz(timeZone).businessDaysAdd(periodDays, "days").endOf("day");
return date.endOf("day").isAfter(periodRollingEndDay);
}
case "range": {
const periodRangeStartDay = dayjs(periodStartDate).tz(timeZone).endOf("day");
const periodRangeEndDay = dayjs(periodEndDate).tz(timeZone).endOf("day");
return date.endOf("day").isBefore(periodRangeStartDay) || date.endOf("day").isAfter(periodRangeEndDay);
}
case "unlimited":
default:
return false;
}
}
export default async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
const { user } = req.query;
log.debug(`Booking ${user} started`);
try {
const isTimeInPast = (time) => {
return dayjs(time).isBefore(new Date(), "day");
};
if (isTimeInPast(req.body.start)) {
const error = {
errorCode: "BookingDateInPast",
message: "Attempting to create a meeting in the past.",
};
log.error(`Booking ${user} failed`, error);
return res.status(400).json(error);
}
let currentUser: User = await prisma.user.findFirst({
where: {
username: user,
},
select: {
id: true,
credentials: true,
timeZone: true,
email: true,
name: true,
},
});
const selectedCalendars = await prisma.selectedCalendar.findMany({
where: {
userId: currentUser.id,
},
});
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(
currentUser.credentials,
dayjs(req.body.start).startOf("day").utc().format("YYYY-MM-DDTHH:mm:ss[Z]"),
dayjs(req.body.end).endOf("day").utc().format("YYYY-MM-DDTHH:mm:ss[Z]"),
selectedCalendars
);
const videoAvailability = await getBusyVideoTimes(currentUser.credentials);
let commonAvailability = [];
if (hasCalendarIntegrations && hasVideoIntegrations) {
commonAvailability = calendarAvailability.filter((availability) =>
videoAvailability.includes(availability)
);
} else if (hasVideoIntegrations) {
commonAvailability = videoAvailability;
} else if (hasCalendarIntegrations) {
commonAvailability = calendarAvailability;
}
// Now, get the newly stored credentials (new refresh token for example).
currentUser = await prisma.user.findFirst({
where: {
username: user,
},
select: {
id: true,
credentials: true,
timeZone: true,
email: true,
name: true,
},
});
// Initialize EventManager with credentials
const eventManager = new EventManager(currentUser.credentials);
const rescheduleUid = req.body.rescheduleUid;
const eventType: EventType = await prisma.eventType.findFirst({
where: {
userId: currentUser.id,
id: req.body.eventTypeId,
},
select: {
id: true,
eventName: true,
title: true,
length: true,
periodType: true,
periodDays: true,
periodStartDate: true,
periodEndDate: true,
periodCountCalendarDays: true,
requiresConfirmation: true,
},
});
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];
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: attendeesList,
location: req.body.location, // Will be processed by the EventManager later.
};
let isAvailableToBeBooked = true;
try {
isAvailableToBeBooked = isAvailable(commonAvailability, req.body.start, eventType.length);
} catch {
log.debug({
message: "Unable set isAvailableToBeBooked. Using true. ",
});
}
if (!isAvailableToBeBooked) {
const error = {
errorCode: "BookingUserUnAvailable",
message: `${currentUser.name} is unavailable at this time.`,
};
log.debug(`Booking ${user} failed`, error);
return res.status(400).json(error);
}
let timeOutOfBounds = false;
try {
timeOutOfBounds = isOutOfBounds(req.body.start, {
periodType: eventType.periodType,
periodDays: eventType.periodDays,
periodEndDate: eventType.periodEndDate,
periodStartDate: eventType.periodStartDate,
periodCountCalendarDays: eventType.periodCountCalendarDays,
timeZone: currentUser.timeZone,
});
} catch {
log.debug({
message: "Unable set timeOutOfBounds. Using false. ",
});
}
if (timeOutOfBounds) {
const error = {
errorCode: "BookingUserUnAvailable",
message: `${currentUser.name} is unavailable at this time.`,
};
log.debug(`Booking ${user} failed`, error);
return res.status(400).json(error);
}
let results: Array<EventResult> = [];
let referencesToCreate = [];
if (rescheduleUid) {
// 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);
}
// Forward results
results = updateResults.results;
referencesToCreate = updateResults.referencesToCreate;
} else if (!eventType.requiresConfirmation) {
// 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);
}
// Forward results
results = createResults.results;
referencesToCreate = createResults.referencesToCreate;
}
const hashUID =
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.
try {
await prisma.booking.create({
data: {
uid: hashUID,
userId: currentUser.id,
references: {
create: referencesToCreate,
},
eventTypeId: eventType.id,
title: evt.title,
description: evt.description,
startTime: evt.startTime,
endTime: evt.endTime,
attendees: {
create: evt.attendees,
},
confirmed: !eventType.requiresConfirmation,
location: evt.location,
},
});
} catch (e) {
log.error(`Booking ${user} failed`, "Error when saving booking to db", e);
res.status(500).json({ message: "Booking already exists" });
return;
}
if (eventType.requiresConfirmation) {
await new EventOrganizerRequestMail(evt, hashUID).sendEmail();
}
log.debug(`Booking ${user} completed`);
return res.status(204).json({ message: "Booking completed" });
} catch (reason) {
log.error(`Booking ${user} failed`, reason);
return res.status(500).json({ message: "Booking failed for some unknown reason" });
}
}
+434
View File
@@ -0,0 +1,434 @@
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "@lib/prisma";
import {
EventType,
User,
SchedulingType,
Credential,
SelectedCalendar,
Booking,
Prisma,
} from "@prisma/client";
import { CalendarEvent, getBusyCalendarTimes } from "@lib/calendarClient";
import { v5 as uuidv5 } from "uuid";
import short from "short-uuid";
import { getBusyVideoTimes } from "@lib/videoClient";
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";
import isBetween from "dayjs/plugin/isBetween";
import dayjsBusinessDays from "dayjs-business-days";
import EventOrganizerRequestMail from "@lib/emails/EventOrganizerRequestMail";
dayjs.extend(dayjsBusinessDays);
dayjs.extend(utc);
dayjs.extend(isBetween);
dayjs.extend(timezone);
const translator = short();
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
function isAvailable(busyTimes, time, length) {
// Check for conflicts
let t = true;
if (Array.isArray(busyTimes) && busyTimes.length > 0) {
busyTimes.forEach((busyTime) => {
const startTime = dayjs(busyTime.start);
const endTime = dayjs(busyTime.end);
// Check if time is between start and end times
if (dayjs(time).isBetween(startTime, endTime, null, "[)")) {
t = false;
}
// Check if slot end time is between start and end time
if (dayjs(time).add(length, "minutes").isBetween(startTime, endTime)) {
t = false;
}
// Check if startTime is between slot
if (startTime.isBetween(dayjs(time), dayjs(time).add(length, "minutes"))) {
t = false;
}
});
}
return t;
}
function isOutOfBounds(
time: dayjs.ConfigType,
{ periodType, periodDays, periodCountCalendarDays, periodStartDate, periodEndDate, timeZone }
): boolean {
const date = dayjs(time);
switch (periodType) {
case "rolling": {
const periodRollingEndDay = periodCountCalendarDays
? dayjs().tz(timeZone).add(periodDays, "days").endOf("day")
: dayjs().tz(timeZone).businessDaysAdd(periodDays, "days").endOf("day");
return date.endOf("day").isAfter(periodRollingEndDay);
}
case "range": {
const periodRangeStartDay = dayjs(periodStartDate).tz(timeZone).endOf("day");
const periodRangeEndDay = dayjs(periodEndDate).tz(timeZone).endOf("day");
return date.endOf("day").isBefore(periodRangeStartDay) || date.endOf("day").isAfter(periodRangeEndDay);
}
case "unlimited":
default:
return false;
}
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const eventTypeId = parseInt(req.body.eventTypeId as string);
log.debug(`Booking eventType ${eventTypeId} started`);
const isTimeInPast = (time) => {
return dayjs(time).isBefore(new Date(), "day");
};
if (isTimeInPast(req.body.start)) {
const error = {
errorCode: "BookingDateInPast",
message: "Attempting to create a meeting in the past.",
};
log.error(`Booking ${eventTypeId} failed`, error);
return res.status(400).json(error);
}
const eventType: EventType = await prisma.eventType.findUnique({
where: {
id: eventTypeId,
},
select: {
users: {
select: {
id: true,
email: true,
name: true,
username: true,
timeZone: true,
},
},
team: {
select: {
id: true,
name: true,
},
},
title: true,
length: true,
eventName: true,
schedulingType: true,
periodType: true,
periodStartDate: true,
periodEndDate: true,
periodDays: true,
periodCountCalendarDays: true,
requiresConfirmation: true,
userId: true,
},
});
if (!eventType.users.length && eventType.userId) {
eventType.users.push(
await prisma.user.findUnique({
where: {
id: eventType.userId,
},
select: {
id: true,
email: true,
name: true,
username: true,
timeZone: true,
},
})
);
}
let users: User[] = eventType.users;
if (eventType.schedulingType === SchedulingType.ROUND_ROBIN) {
const selectedUsers = req.body.users || [];
// one of these things that can probably be done better
// prisma is not well documented.
users = await Promise.all(
selectedUsers.map(async (username) => {
const user = await prisma.user.findUnique({
where: {
username,
},
select: {
bookings: {
where: {
startTime: {
gt: new Date(),
},
},
select: {
id: true,
},
},
},
});
return {
username,
bookingCount: user.bookings.length,
};
})
).then((bookingCounts) => {
if (!bookingCounts.length) {
return users.slice(0, 1);
}
const sorted = bookingCounts.sort((a, b) => (a.bookingCount > b.bookingCount ? 1 : -1));
return [users.find((user) => user.username === sorted[0].username)];
});
}
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 teamMembers =
eventType.schedulingType === SchedulingType.COLLECTIVE
? users.slice(1).map((user) => ({
email: user.email,
name: user.name,
timeZone: user.timeZone,
}))
: [];
const attendeesList = [...invitee, ...guests, ...teamMembers];
const seed = `${users[0].username}:${dayjs(req.body.start).utc().format()}`;
const uid = translator.fromUUID(uuidv5(seed, uuidv5.URL));
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: {
name: users[0].name,
email: users[0].email,
timeZone: users[0].timeZone,
},
attendees: attendeesList,
location: req.body.location, // Will be processed by the EventManager later.
};
if (eventType.schedulingType === SchedulingType.COLLECTIVE) {
evt.team = {
members: users.map((user) => user.name || user.username),
name: eventType.team.name,
}; // used for invitee emails
}
const bookingCreateInput: Prisma.BookingCreateInput = {
uid,
title: evt.title,
startTime: dayjs(evt.startTime).toDate(),
endTime: dayjs(evt.endTime).toDate(),
description: evt.description,
confirmed: !eventType.requiresConfirmation,
location: evt.location,
eventType: {
connect: {
id: eventTypeId,
},
},
attendees: {
createMany: {
data: evt.attendees,
},
},
user: {
connect: {
id: users[0].id,
},
},
};
let booking: Booking | null;
try {
booking = await prisma.booking.create({
data: bookingCreateInput,
});
} catch (e) {
log.error(`Booking ${eventTypeId} failed`, "Error when saving booking to db", e.message);
if (e.code === "P2002") {
return res.status(409).json({ message: "booking.conflict" });
}
return res.status(500).end();
}
let results: EventResult[] = [];
let referencesToCreate = [];
const loadUser = async (id): Promise<User> =>
await prisma.user.findUnique({
where: {
id,
},
select: {
id: true,
credentials: true,
timeZone: true,
email: true,
username: true,
name: true,
bufferTime: true,
},
});
let user: User;
for (const currentUser of await Promise.all(users.map((user) => loadUser(user.id)))) {
if (!user) {
user = currentUser;
}
const selectedCalendars: SelectedCalendar[] = await prisma.selectedCalendar.findMany({
where: {
userId: currentUser.id,
},
});
const credentials: Credential[] = currentUser.credentials;
if (credentials) {
const calendarBusyTimes = await getBusyCalendarTimes(
credentials,
req.body.start,
req.body.end,
selectedCalendars
);
const videoBusyTimes = await getBusyVideoTimes(credentials);
calendarBusyTimes.push(...videoBusyTimes);
const bufferedBusyTimes = calendarBusyTimes.map((a) => ({
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toString(),
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toString(),
}));
let isAvailableToBeBooked = true;
try {
isAvailableToBeBooked = isAvailable(bufferedBusyTimes, req.body.start, eventType.length);
} catch {
log.debug({
message: "Unable set isAvailableToBeBooked. Using true. ",
});
}
if (!isAvailableToBeBooked) {
const error = {
errorCode: "BookingUserUnAvailable",
message: `${currentUser.name} is unavailable at this time.`,
};
log.debug(`Booking ${currentUser.name} failed`, error);
}
let timeOutOfBounds = false;
try {
timeOutOfBounds = isOutOfBounds(req.body.start, {
periodType: eventType.periodType,
periodDays: eventType.periodDays,
periodEndDate: eventType.periodEndDate,
periodStartDate: eventType.periodStartDate,
periodCountCalendarDays: eventType.periodCountCalendarDays,
timeZone: currentUser.timeZone,
});
} catch {
log.debug({
message: "Unable set timeOutOfBounds. Using false. ",
});
}
if (timeOutOfBounds) {
const error = {
errorCode: "BookingUserUnAvailable",
message: `${currentUser.name} is unavailable at this time.`,
};
log.debug(`Booking ${currentUser.name} failed`, error);
res.status(400).json(error);
}
}
}
// Initialize EventManager with credentials
const eventManager = new EventManager(user.credentials);
const rescheduleUid = req.body.rescheduleUid;
if (rescheduleUid) {
// Use EventManager to conditionally use all needed integrations.
const updateResults: CreateUpdateResult = await eventManager.update(evt, rescheduleUid);
results = updateResults.results;
referencesToCreate = updateResults.referencesToCreate;
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingReschedulingMeetingFailed",
message: "Booking Rescheduling failed",
};
log.error(`Booking ${user.name} failed`, error, results);
}
} else if (!eventType.requiresConfirmation) {
// Use EventManager to conditionally use all needed integrations.
const createResults: CreateUpdateResult = await eventManager.create(evt, uid);
results = createResults.results;
referencesToCreate = createResults.referencesToCreate;
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingCreatingMeetingFailed",
message: "Booking failed",
};
log.error(`Booking ${user.username} failed`, error, results);
}
}
if (eventType.requiresConfirmation) {
await new EventOrganizerRequestMail(evt, uid).sendEmail();
}
log.debug(`Booking ${user.username} completed`);
await prisma.booking.update({
where: {
uid: booking.uid,
},
data: {
references: {
createMany: {
data: referencesToCreate,
},
},
},
});
// booking succesfull
return res.status(201).json(booking);
}
+72 -71
View File
@@ -1,79 +1,80 @@
import prisma from "@lib/prisma";
import { deleteEvent } from "@lib/calendarClient";
import async from "async";
import { deleteMeeting } from "@lib/videoClient";
import { asStringOrNull } from "@lib/asStringOrNull";
import async from "async";
import { BookingStatus } from "@prisma/client";
import { asStringOrNull } from "@lib/asStringOrNull";
export default async function handler(req, res) {
if (req.method == "POST") {
const uid = asStringOrNull(req.body.uid);
const bookingToDelete = await prisma.booking.findUnique({
where: {
uid,
},
select: {
id: true,
user: {
select: {
credentials: true,
},
},
attendees: true,
references: {
select: {
uid: true,
type: true,
},
},
},
});
if (!bookingToDelete) {
return res.status(404).end();
}
// by cancelling first, and blocking whilst doing so; we can ensure a cancel
// action always succeeds even if subsequent integrations fail cancellation.
await prisma.booking.update({
where: {
uid,
},
data: {
status: BookingStatus.CANCELLED,
},
});
const apiDeletes = async.mapLimit(bookingToDelete.user.credentials, 5, async (credential) => {
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,
},
});
const bookingReferenceDeletes = prisma.bookingReference.deleteMany({
where: {
bookingId: bookingToDelete.id,
},
});
await Promise.all([apiDeletes, attendeeDeletes, bookingReferenceDeletes]);
//TODO Perhaps send emails to user and client to tell about the cancellation
res.status(200).json({ message: "Booking successfully deleted." });
} else {
res.status(405).json({ message: "This endpoint only accepts POST requests." });
// just bail if it not a DELETE
if (req.method !== "DELETE") {
return res.status(405).end();
}
const uid = asStringOrNull(req.body.uid) || "";
const bookingToDelete = await prisma.booking.findUnique({
where: {
uid,
},
select: {
id: true,
user: {
select: {
credentials: true,
},
},
attendees: true,
references: {
select: {
uid: true,
type: true,
},
},
},
});
if (!bookingToDelete) {
return res.status(404).end();
}
// by cancelling first, and blocking whilst doing so; we can ensure a cancel
// action always succeeds even if subsequent integrations fail cancellation.
await prisma.booking.update({
where: {
uid,
},
data: {
status: BookingStatus.CANCELLED,
},
});
const apiDeletes = async.mapLimit(bookingToDelete.user.credentials, 5, async (credential) => {
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,
},
});
const bookingReferenceDeletes = prisma.bookingReference.deleteMany({
where: {
bookingId: bookingToDelete.id,
},
});
await Promise.all([apiDeletes, attendeeDeletes, bookingReferenceDeletes]);
//TODO Perhaps send emails to user and client to tell about the cancellation
res.status(204).end();
}