Merge pull request #412 from emrysal/bugfix/eventType-merge-artifacts

Removed selectedEventType + fixed missing booking.eventTypeId
pull/459/head
Bailey Pumfleet 2021-08-16 10:22:38 +01:00 committed by GitHub
commit 3d725a9573
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 22 additions and 31 deletions

View File

@ -1,5 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../../lib/prisma"; import prisma from "@lib/prisma";
import { EventType, User } from "@prisma/client";
import { CalendarEvent, getBusyCalendarTimes } from "@lib/calendarClient"; import { CalendarEvent, getBusyCalendarTimes } from "@lib/calendarClient";
import { v5 as uuidv5 } from "uuid"; import { v5 as uuidv5 } from "uuid";
import short from "short-uuid"; import short from "short-uuid";
@ -9,7 +10,6 @@ import { getEventName } from "@lib/event";
import dayjs from "dayjs"; import dayjs from "dayjs";
import logger from "../../../lib/logger"; import logger from "../../../lib/logger";
import EventManager, { CreateUpdateResult, EventResult } from "@lib/events/EventManager"; import EventManager, { CreateUpdateResult, EventResult } from "@lib/events/EventManager";
import { User } from "@prisma/client";
import utc from "dayjs/plugin/utc"; import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone"; import timezone from "dayjs/plugin/timezone";
@ -29,13 +29,14 @@ const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
function isAvailable(busyTimes, time, length) { function isAvailable(busyTimes, time, length) {
// Check for conflicts // Check for conflicts
let t = true; let t = true;
if (Array.isArray(busyTimes) && busyTimes.length > 0) { if (Array.isArray(busyTimes) && busyTimes.length > 0) {
busyTimes.forEach((busyTime) => { busyTimes.forEach((busyTime) => {
const startTime = dayjs(busyTime.start); const startTime = dayjs(busyTime.start);
const endTime = dayjs(busyTime.end); const endTime = dayjs(busyTime.end);
// Check if time is between start and end times // Check if time is between start and end times
if (dayjs(time).isBetween(startTime, endTime)) { if (dayjs(time).isBetween(startTime, endTime, null, "(]")) {
t = false; t = false;
} }
@ -82,11 +83,11 @@ function isOutOfBounds(
export async function handleLegacyConfirmationMail( export async function handleLegacyConfirmationMail(
results: Array<EventResult>, results: Array<EventResult>,
selectedEventType: { requiresConfirmation: boolean }, eventType: EventType,
evt: CalendarEvent, evt: CalendarEvent,
hashUID: string hashUID: string
): Promise<{ error: Exception; message: string | null }> { ): Promise<{ error: Exception; message: string | null }> {
if (results.length === 0 && !selectedEventType.requiresConfirmation) { if (results.length === 0 && !eventType.requiresConfirmation) {
// Legacy as well, as soon as we have a separate email integration class. Just used // Legacy as well, as soon as we have a separate email integration class. Just used
// to send an email even if there is no integration at all. // to send an email even if there is no integration at all.
try { try {
@ -179,12 +180,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const eventManager = new EventManager(currentUser.credentials); const eventManager = new EventManager(currentUser.credentials);
const rescheduleUid = req.body.rescheduleUid; const rescheduleUid = req.body.rescheduleUid;
const selectedEventType = await prisma.eventType.findFirst({ const eventType: EventType = await prisma.eventType.findFirst({
where: { where: {
userId: currentUser.id, userId: currentUser.id,
id: req.body.eventTypeId, id: req.body.eventTypeId,
}, },
select: { select: {
id: true,
eventName: true, eventName: true,
title: true, title: true,
length: true, length: true,
@ -209,8 +211,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const attendeesList = [...invitee, ...guests]; const attendeesList = [...invitee, ...guests];
const evt: CalendarEvent = { const evt: CalendarEvent = {
type: selectedEventType.title, type: eventType.title,
title: getEventName(req.body.name, selectedEventType.title, selectedEventType.eventName), title: getEventName(req.body.name, eventType.title, eventType.eventName),
description: req.body.notes, description: req.body.notes,
startTime: req.body.start, startTime: req.body.start,
endTime: req.body.end, endTime: req.body.end,
@ -219,22 +221,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
location: req.body.location, // Will be processed by the EventManager later. location: req.body.location, // Will be processed by the EventManager later.
}; };
const eventType = await prisma.eventType.findFirst({
where: {
userId: currentUser.id,
title: evt.type,
},
select: {
id: true,
},
});
let isAvailableToBeBooked = true; let isAvailableToBeBooked = true;
try { try {
isAvailableToBeBooked = isAvailable(commonAvailability, req.body.start, selectedEventType.length); isAvailableToBeBooked = isAvailable(commonAvailability, req.body.start, eventType.length);
} catch (e) { } catch {
console.log(e);
log.debug({ log.debug({
message: "Unable set isAvailableToBeBooked. Using true. ", message: "Unable set isAvailableToBeBooked. Using true. ",
}); });
@ -254,11 +245,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
try { try {
timeOutOfBounds = isOutOfBounds(req.body.start, { timeOutOfBounds = isOutOfBounds(req.body.start, {
periodType: selectedEventType.periodType, periodType: eventType.periodType,
periodDays: selectedEventType.periodDays, periodDays: eventType.periodDays,
periodEndDate: selectedEventType.periodEndDate, periodEndDate: eventType.periodEndDate,
periodStartDate: selectedEventType.periodStartDate, periodStartDate: eventType.periodStartDate,
periodCountCalendarDays: selectedEventType.periodCountCalendarDays, periodCountCalendarDays: eventType.periodCountCalendarDays,
timeZone: currentUser.timeZone, timeZone: currentUser.timeZone,
}); });
} catch { } catch {
@ -297,7 +288,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// Forward results // Forward results
results = updateResults.results; results = updateResults.results;
referencesToCreate = updateResults.referencesToCreate; referencesToCreate = updateResults.referencesToCreate;
} else if (!selectedEventType.requiresConfirmation) { } else if (!eventType.requiresConfirmation) {
// Use EventManager to conditionally use all needed integrations. // Use EventManager to conditionally use all needed integrations.
const createResults: CreateUpdateResult = await eventManager.create(evt); const createResults: CreateUpdateResult = await eventManager.create(evt);
@ -320,7 +311,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
results.length > 0 ? results[0].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. // 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. // UID generation should happen in the integration itself, not here.
const legacyMailError = await handleLegacyConfirmationMail(results, selectedEventType, evt, hashUID); const legacyMailError = await handleLegacyConfirmationMail(results, eventType, evt, hashUID);
if (legacyMailError) { if (legacyMailError) {
log.error("Sending legacy event mail failed", legacyMailError.error); log.error("Sending legacy event mail failed", legacyMailError.error);
log.error(`Booking ${user} failed`); log.error(`Booking ${user} failed`);
@ -344,8 +335,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
attendees: { attendees: {
create: evt.attendees, create: evt.attendees,
}, },
location: evt.location, // This is the raw location that can be processed by the EventManager. confirmed: !eventType.requiresConfirmation,
confirmed: !selectedEventType.requiresConfirmation, location: evt.location,
}, },
}); });
} catch (e) { } catch (e) {
@ -354,7 +345,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return; return;
} }
if (selectedEventType.requiresConfirmation) { if (eventType.requiresConfirmation) {
await new EventOrganizerRequestMail(evt, hashUID).sendEmail(); await new EventOrganizerRequestMail(evt, hashUID).sendEmail();
} }