eslint fixes
This commit is contained in:
parent
917b2c4821
commit
646ff4a107
3 changed files with 438 additions and 419 deletions
|
@ -1,15 +1,14 @@
|
||||||
import dayjs, {Dayjs} from "dayjs";
|
import dayjs from "dayjs";
|
||||||
import isBetween from 'dayjs/plugin/isBetween';
|
import isBetween from "dayjs/plugin/isBetween";
|
||||||
dayjs.extend(isBetween);
|
dayjs.extend(isBetween);
|
||||||
import {useEffect, useMemo, useState} from "react";
|
import { useEffect, useState } from "react";
|
||||||
import getSlots from "../../lib/slots";
|
import getSlots from "../../lib/slots";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {timeZone} from "../../lib/clock";
|
import { timeZone } from "../../lib/clock";
|
||||||
import {useRouter} from "next/router";
|
import { useRouter } from "next/router";
|
||||||
import {ExclamationIcon} from "@heroicons/react/solid";
|
import { ExclamationIcon } from "@heroicons/react/solid";
|
||||||
|
|
||||||
const AvailableTimes = (props) => {
|
const AvailableTimes = (props) => {
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { user, rescheduleUid } = router.query;
|
const { user, rescheduleUid } = router.query;
|
||||||
const [loaded, setLoaded] = useState(false);
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
@ -27,12 +26,12 @@ const AvailableTimes = (props) => {
|
||||||
const handleAvailableSlots = (busyTimes: []) => {
|
const handleAvailableSlots = (busyTimes: []) => {
|
||||||
// Check for conflicts
|
// Check for conflicts
|
||||||
for (let i = times.length - 1; i >= 0; i -= 1) {
|
for (let i = times.length - 1; i >= 0; i -= 1) {
|
||||||
busyTimes.forEach(busyTime => {
|
busyTimes.forEach((busyTime) => {
|
||||||
let startTime = dayjs(busyTime.start);
|
const startTime = dayjs(busyTime.start);
|
||||||
let endTime = dayjs(busyTime.end);
|
const endTime = dayjs(busyTime.end);
|
||||||
|
|
||||||
// Check if start times are the same
|
// Check if start times are the same
|
||||||
if (dayjs(times[i]).format('HH:mm') == startTime.format('HH:mm')) {
|
if (dayjs(times[i]).format("HH:mm") == startTime.format("HH:mm")) {
|
||||||
times.splice(i, 1);
|
times.splice(i, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -42,12 +41,12 @@ const AvailableTimes = (props) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if slot end time is between start and end time
|
// Check if slot end time is between start and end time
|
||||||
if (dayjs(times[i]).add(props.eventType.length, 'minutes').isBetween(startTime, endTime)) {
|
if (dayjs(times[i]).add(props.eventType.length, "minutes").isBetween(startTime, endTime)) {
|
||||||
times.splice(i, 1);
|
times.splice(i, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if startTime is between slot
|
// Check if startTime is between slot
|
||||||
if (startTime.isBetween(dayjs(times[i]), dayjs(times[i]).add(props.eventType.length, 'minutes'))) {
|
if (startTime.isBetween(dayjs(times[i]), dayjs(times[i]).add(props.eventType.length, "minutes"))) {
|
||||||
times.splice(i, 1);
|
times.splice(i, 1);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -60,32 +59,44 @@ const AvailableTimes = (props) => {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setLoaded(false);
|
setLoaded(false);
|
||||||
setError(false);
|
setError(false);
|
||||||
fetch(`/api/availability/${user}?dateFrom=${props.date.startOf('day').utc().format()}&dateTo=${props.date.endOf('day').utc().format()}`)
|
fetch(
|
||||||
.then( res => res.json())
|
`/api/availability/${user}?dateFrom=${props.date.startOf("day").utc().format()}&dateTo=${props.date
|
||||||
|
.endOf("day")
|
||||||
|
.utc()
|
||||||
|
.format()}`
|
||||||
|
)
|
||||||
|
.then((res) => res.json())
|
||||||
.then(handleAvailableSlots)
|
.then(handleAvailableSlots)
|
||||||
.catch(e => setError(true))
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
setError(true);
|
||||||
|
});
|
||||||
}, [props.date]);
|
}, [props.date]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="sm:pl-4 mt-8 sm:mt-0 text-center sm:w-1/3 md:max-h-97 overflow-y-auto">
|
<div className="sm:pl-4 mt-8 sm:mt-0 text-center sm:w-1/3 md:max-h-97 overflow-y-auto">
|
||||||
<div className="text-gray-600 font-light text-xl mb-4 text-left">
|
<div className="text-gray-600 font-light text-xl mb-4 text-left">
|
||||||
<span className="w-1/2">
|
<span className="w-1/2">{props.date.format("dddd DD MMMM YYYY")}</span>
|
||||||
{props.date.format("dddd DD MMMM YYYY")}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
{
|
{!error &&
|
||||||
!error && loaded && times.map((time) =>
|
loaded &&
|
||||||
|
times.map((time) => (
|
||||||
<div key={dayjs(time).utc().format()}>
|
<div key={dayjs(time).utc().format()}>
|
||||||
<Link
|
<Link
|
||||||
href={`/${props.user.username}/book?date=${dayjs(time).utc().format()}&type=${props.eventType.id}` + (rescheduleUid ? "&rescheduleUid=" + rescheduleUid : "")}>
|
href={
|
||||||
<a key={dayjs(time).format("hh:mma")}
|
`/${props.user.username}/book?date=${dayjs(time).utc().format()}&type=${props.eventType.id}` +
|
||||||
className="block font-medium mb-4 text-blue-600 border border-blue-600 rounded hover:text-white hover:bg-blue-600 py-4">{dayjs(time).tz(timeZone()).format(props.timeFormat)}</a>
|
(rescheduleUid ? "&rescheduleUid=" + rescheduleUid : "")
|
||||||
|
}>
|
||||||
|
<a
|
||||||
|
key={dayjs(time).format("hh:mma")}
|
||||||
|
className="block font-medium mb-4 text-blue-600 border border-blue-600 rounded hover:text-white hover:bg-blue-600 py-4">
|
||||||
|
{dayjs(time).tz(timeZone()).format(props.timeFormat)}
|
||||||
|
</a>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
)
|
))}
|
||||||
}
|
{!error && !loaded && <div className="loader" />}
|
||||||
{!error && !loaded && <div className="loader"/>}
|
{error && (
|
||||||
{error &&
|
|
||||||
<div className="bg-yellow-50 border-l-4 border-yellow-400 p-4">
|
<div className="bg-yellow-50 border-l-4 border-yellow-400 p-4">
|
||||||
<div className="flex">
|
<div className="flex">
|
||||||
<div className="flex-shrink-0">
|
<div className="flex-shrink-0">
|
||||||
|
@ -93,16 +104,19 @@ const AvailableTimes = (props) => {
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-3">
|
<div className="ml-3">
|
||||||
<p className="text-sm text-yellow-700">
|
<p className="text-sm text-yellow-700">
|
||||||
Could not load the available time slots.{' '}
|
Could not load the available time slots.{" "}
|
||||||
<a href={"mailto:" + props.user.email} className="font-medium underline text-yellow-700 hover:text-yellow-600">
|
<a
|
||||||
|
href={"mailto:" + props.user.email}
|
||||||
|
className="font-medium underline text-yellow-700 hover:text-yellow-600">
|
||||||
Contact {props.user.name} via e-mail
|
Contact {props.user.name} via e-mail
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>}
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
export default AvailableTimes;
|
export default AvailableTimes;
|
||||||
|
|
|
@ -7,44 +7,51 @@ import EventAttendeeRescheduledMail from "./emails/EventAttendeeRescheduledMail"
|
||||||
|
|
||||||
const translator = short();
|
const translator = short();
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
const { google } = require("googleapis");
|
const { google } = require("googleapis");
|
||||||
import prisma from "./prisma";
|
import prisma from "./prisma";
|
||||||
|
|
||||||
const googleAuth = (credential) => {
|
const googleAuth = (credential) => {
|
||||||
const {client_secret, client_id, redirect_uris} = JSON.parse(process.env.GOOGLE_API_CREDENTIALS).web;
|
const { client_secret, client_id, redirect_uris } = JSON.parse(process.env.GOOGLE_API_CREDENTIALS).web;
|
||||||
const myGoogleAuth = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
|
const myGoogleAuth = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
|
||||||
myGoogleAuth.setCredentials(credential.key);
|
myGoogleAuth.setCredentials(credential.key);
|
||||||
|
|
||||||
const isExpired = () => myGoogleAuth.isTokenExpiring();
|
const isExpired = () => myGoogleAuth.isTokenExpiring();
|
||||||
|
|
||||||
const refreshAccessToken = () => myGoogleAuth.refreshToken(credential.key.refresh_token).then(res => {
|
const refreshAccessToken = () =>
|
||||||
|
myGoogleAuth
|
||||||
|
.refreshToken(credential.key.refresh_token)
|
||||||
|
.then((res) => {
|
||||||
const token = res.res.data;
|
const token = res.res.data;
|
||||||
credential.key.access_token = token.access_token;
|
credential.key.access_token = token.access_token;
|
||||||
credential.key.expiry_date = token.expiry_date;
|
credential.key.expiry_date = token.expiry_date;
|
||||||
return prisma.credential.update({
|
return prisma.credential
|
||||||
|
.update({
|
||||||
where: {
|
where: {
|
||||||
id: credential.id
|
id: credential.id,
|
||||||
},
|
},
|
||||||
data: {
|
data: {
|
||||||
key: credential.key
|
key: credential.key,
|
||||||
}
|
},
|
||||||
}).then(() => {
|
})
|
||||||
|
.then(() => {
|
||||||
myGoogleAuth.setCredentials(credential.key);
|
myGoogleAuth.setCredentials(credential.key);
|
||||||
return myGoogleAuth;
|
return myGoogleAuth;
|
||||||
});
|
});
|
||||||
}).catch(err => {
|
})
|
||||||
|
.catch((err) => {
|
||||||
console.error("Error refreshing google token", err);
|
console.error("Error refreshing google token", err);
|
||||||
return myGoogleAuth;
|
return myGoogleAuth;
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getToken: () => !isExpired() ? Promise.resolve(myGoogleAuth) : refreshAccessToken()
|
getToken: () => (!isExpired() ? Promise.resolve(myGoogleAuth) : refreshAccessToken()),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
function handleErrorsJson(response) {
|
function handleErrorsJson(response) {
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
response.json().then(e => console.error("O365 Error", e));
|
response.json().then((e) => console.error("O365 Error", e));
|
||||||
throw Error(response.statusText);
|
throw Error(response.statusText);
|
||||||
}
|
}
|
||||||
return response.json();
|
return response.json();
|
||||||
|
@ -52,41 +59,43 @@ function handleErrorsJson(response) {
|
||||||
|
|
||||||
function handleErrorsRaw(response) {
|
function handleErrorsRaw(response) {
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
response.text().then(e => console.error("O365 Error", e));
|
response.text().then((e) => console.error("O365 Error", e));
|
||||||
throw Error(response.statusText);
|
throw Error(response.statusText);
|
||||||
}
|
}
|
||||||
return response.text();
|
return response.text();
|
||||||
}
|
}
|
||||||
|
|
||||||
const o365Auth = (credential) => {
|
const o365Auth = (credential) => {
|
||||||
const isExpired = (expiryDate) => expiryDate < Math.round((+(new Date()) / 1000));
|
const isExpired = (expiryDate) => expiryDate < Math.round(+new Date() / 1000);
|
||||||
|
|
||||||
const refreshAccessToken = (refreshToken) => {
|
const refreshAccessToken = (refreshToken) => {
|
||||||
return fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
|
return fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
|
||||||
method: 'POST',
|
method: "POST",
|
||||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
body: new URLSearchParams({
|
body: new URLSearchParams({
|
||||||
'scope': 'User.Read Calendars.Read Calendars.ReadWrite',
|
scope: "User.Read Calendars.Read Calendars.ReadWrite",
|
||||||
'client_id': process.env.MS_GRAPH_CLIENT_ID,
|
client_id: process.env.MS_GRAPH_CLIENT_ID,
|
||||||
'refresh_token': refreshToken,
|
refresh_token: refreshToken,
|
||||||
'grant_type': 'refresh_token',
|
grant_type: "refresh_token",
|
||||||
'client_secret': process.env.MS_GRAPH_CLIENT_SECRET,
|
client_secret: process.env.MS_GRAPH_CLIENT_SECRET,
|
||||||
})
|
}),
|
||||||
})
|
})
|
||||||
.then(handleErrorsJson)
|
.then(handleErrorsJson)
|
||||||
.then((responseBody) => {
|
.then((responseBody) => {
|
||||||
credential.key.access_token = responseBody.access_token;
|
credential.key.access_token = responseBody.access_token;
|
||||||
credential.key.expiry_date = Math.round((+(new Date()) / 1000) + responseBody.expires_in);
|
credential.key.expiry_date = Math.round(+new Date() / 1000 + responseBody.expires_in);
|
||||||
return prisma.credential.update({
|
return prisma.credential
|
||||||
|
.update({
|
||||||
where: {
|
where: {
|
||||||
id: credential.id
|
id: credential.id,
|
||||||
},
|
},
|
||||||
data: {
|
data: {
|
||||||
key: credential.key
|
key: credential.key,
|
||||||
}
|
},
|
||||||
}).then(() => credential.key.access_token)
|
|
||||||
})
|
})
|
||||||
}
|
.then(() => credential.key.access_token);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getToken: () =>
|
getToken: () =>
|
||||||
|
@ -128,15 +137,11 @@ interface IntegrationCalendar {
|
||||||
interface CalendarApiAdapter {
|
interface CalendarApiAdapter {
|
||||||
createEvent(event: CalendarEvent): Promise<any>;
|
createEvent(event: CalendarEvent): Promise<any>;
|
||||||
|
|
||||||
updateEvent(uid: String, event: CalendarEvent);
|
updateEvent(uid: string, event: CalendarEvent);
|
||||||
|
|
||||||
deleteEvent(uid: String);
|
deleteEvent(uid: string);
|
||||||
|
|
||||||
getAvailability(
|
getAvailability(dateFrom, dateTo, selectedCalendars: IntegrationCalendar[]): Promise<any>;
|
||||||
dateFrom,
|
|
||||||
dateTo,
|
|
||||||
selectedCalendars: IntegrationCalendar[]
|
|
||||||
): Promise<any>;
|
|
||||||
|
|
||||||
listCalendars(): Promise<IntegrationCalendar[]>;
|
listCalendars(): Promise<IntegrationCalendar[]>;
|
||||||
}
|
}
|
||||||
|
@ -145,7 +150,7 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||||
const auth = o365Auth(credential);
|
const auth = o365Auth(credential);
|
||||||
|
|
||||||
const translateEvent = (event: CalendarEvent) => {
|
const translateEvent = (event: CalendarEvent) => {
|
||||||
let optional = {};
|
const optional = {};
|
||||||
if (event.location) {
|
if (event.location) {
|
||||||
optional.location = { displayName: event.location };
|
optional.location = { displayName: event.location };
|
||||||
}
|
}
|
||||||
|
@ -203,12 +208,7 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getAvailability: (dateFrom, dateTo, selectedCalendars) => {
|
getAvailability: (dateFrom, dateTo, selectedCalendars) => {
|
||||||
const filter =
|
const filter = "?$filter=start/dateTime ge '" + dateFrom + "' and end/dateTime le '" + dateTo + "'";
|
||||||
"?$filter=start/dateTime ge '" +
|
|
||||||
dateFrom +
|
|
||||||
"' and end/dateTime le '" +
|
|
||||||
dateTo +
|
|
||||||
"'";
|
|
||||||
return auth
|
return auth
|
||||||
.getToken()
|
.getToken()
|
||||||
.then((accessToken) => {
|
.then((accessToken) => {
|
||||||
|
@ -227,10 +227,7 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||||
).then((ids: string[]) => {
|
).then((ids: string[]) => {
|
||||||
const urls = ids.map(
|
const urls = ids.map(
|
||||||
(calendarId) =>
|
(calendarId) =>
|
||||||
"https://graph.microsoft.com/v1.0/me/calendars/" +
|
"https://graph.microsoft.com/v1.0/me/calendars/" + calendarId + "/events" + filter
|
||||||
calendarId +
|
|
||||||
"/events" +
|
|
||||||
filter
|
|
||||||
);
|
);
|
||||||
return Promise.all(
|
return Promise.all(
|
||||||
urls.map((url) =>
|
urls.map((url) =>
|
||||||
|
@ -249,9 +246,7 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||||
}))
|
}))
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
).then((results) =>
|
).then((results) => results.reduce((acc, events) => acc.concat(events), []));
|
||||||
results.reduce((acc, events) => acc.concat(events), [])
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
|
@ -274,7 +269,7 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||||
disableConfirmationEmail: true,
|
disableConfirmationEmail: true,
|
||||||
}))
|
}))
|
||||||
),
|
),
|
||||||
deleteEvent: (uid: String) =>
|
deleteEvent: (uid: string) =>
|
||||||
auth.getToken().then((accessToken) =>
|
auth.getToken().then((accessToken) =>
|
||||||
fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
|
fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
|
@ -283,7 +278,7 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||||
},
|
},
|
||||||
}).then(handleErrorsRaw)
|
}).then(handleErrorsRaw)
|
||||||
),
|
),
|
||||||
updateEvent: (uid: String, event: CalendarEvent) =>
|
updateEvent: (uid: string, event: CalendarEvent) =>
|
||||||
auth.getToken().then((accessToken) =>
|
auth.getToken().then((accessToken) =>
|
||||||
fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
|
fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
|
@ -303,42 +298,49 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
|
||||||
const integrationType = "google_calendar";
|
const integrationType = "google_calendar";
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getAvailability: (dateFrom, dateTo, selectedCalendars) => new Promise((resolve, reject) => auth.getToken().then(myGoogleAuth => {
|
getAvailability: (dateFrom, dateTo, selectedCalendars) =>
|
||||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
new Promise((resolve, reject) =>
|
||||||
const selectedCalendarIds = selectedCalendars.filter(e => e.integration === integrationType).map(e => e.externalId);
|
auth.getToken().then((myGoogleAuth) => {
|
||||||
if (selectedCalendarIds.length == 0 && selectedCalendars.length > 0){
|
const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
|
||||||
|
const selectedCalendarIds = selectedCalendars
|
||||||
|
.filter((e) => e.integration === integrationType)
|
||||||
|
.map((e) => e.externalId);
|
||||||
|
if (selectedCalendarIds.length == 0 && selectedCalendars.length > 0) {
|
||||||
// Only calendars of other integrations selected
|
// Only calendars of other integrations selected
|
||||||
resolve([]);
|
resolve([]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
(selectedCalendarIds.length == 0
|
(selectedCalendarIds.length == 0
|
||||||
? calendar.calendarList.list().then(cals => cals.data.items.map(cal => cal.id))
|
? calendar.calendarList.list().then((cals) => cals.data.items.map((cal) => cal.id))
|
||||||
: Promise.resolve(selectedCalendarIds)).then(calsIds => {
|
: Promise.resolve(selectedCalendarIds)
|
||||||
calendar.freebusy.query({
|
)
|
||||||
|
.then((calsIds) => {
|
||||||
|
calendar.freebusy.query(
|
||||||
|
{
|
||||||
requestBody: {
|
requestBody: {
|
||||||
timeMin: dateFrom,
|
timeMin: dateFrom,
|
||||||
timeMax: dateTo,
|
timeMax: dateTo,
|
||||||
items: calsIds.map(id => ({id: id}))
|
items: calsIds.map((id) => ({ id: id })),
|
||||||
}
|
},
|
||||||
}, (err, apires) => {
|
},
|
||||||
|
(err, apires) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
reject(err);
|
||||||
}
|
}
|
||||||
resolve(
|
resolve(Object.values(apires.data.calendars).flatMap((item) => item["busy"]));
|
||||||
Object.values(apires.data.calendars).flatMap(
|
}
|
||||||
(item) => item["busy"]
|
);
|
||||||
)
|
|
||||||
)
|
|
||||||
});
|
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.error('There was an error contacting google calendar service: ', err);
|
console.error("There was an error contacting google calendar service: ", err);
|
||||||
reject(err);
|
reject(err);
|
||||||
});
|
});
|
||||||
|
})
|
||||||
})),
|
),
|
||||||
createEvent: (event: CalendarEvent) => new Promise((resolve, reject) => auth.getToken().then(myGoogleAuth => {
|
createEvent: (event: CalendarEvent) =>
|
||||||
|
new Promise((resolve, reject) =>
|
||||||
|
auth.getToken().then((myGoogleAuth) => {
|
||||||
const payload = {
|
const payload = {
|
||||||
summary: event.title,
|
summary: event.title,
|
||||||
description: event.description,
|
description: event.description,
|
||||||
|
@ -353,9 +355,7 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
|
||||||
attendees: event.attendees,
|
attendees: event.attendees,
|
||||||
reminders: {
|
reminders: {
|
||||||
useDefault: false,
|
useDefault: false,
|
||||||
overrides: [
|
overrides: [{ method: "email", minutes: 60 }],
|
||||||
{'method': 'email', 'minutes': 60}
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -367,20 +367,26 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
|
||||||
payload["conferenceData"] = event.conferenceData;
|
payload["conferenceData"] = event.conferenceData;
|
||||||
}
|
}
|
||||||
|
|
||||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
|
||||||
calendar.events.insert({
|
calendar.events.insert(
|
||||||
|
{
|
||||||
auth: myGoogleAuth,
|
auth: myGoogleAuth,
|
||||||
calendarId: 'primary',
|
calendarId: "primary",
|
||||||
resource: payload,
|
resource: payload,
|
||||||
}, function (err, event) {
|
},
|
||||||
|
function (err, event) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error('There was an error contacting google calendar service: ', err);
|
console.error("There was an error contacting google calendar service: ", err);
|
||||||
return reject(err);
|
return reject(err);
|
||||||
}
|
}
|
||||||
return resolve(event.data);
|
return resolve(event.data);
|
||||||
});
|
}
|
||||||
})),
|
);
|
||||||
updateEvent: (uid: String, event: CalendarEvent) => new Promise((resolve, reject) => auth.getToken().then(myGoogleAuth => {
|
})
|
||||||
|
),
|
||||||
|
updateEvent: (uid: string, event: CalendarEvent) =>
|
||||||
|
new Promise((resolve, reject) =>
|
||||||
|
auth.getToken().then((myGoogleAuth) => {
|
||||||
const payload = {
|
const payload = {
|
||||||
summary: event.title,
|
summary: event.title,
|
||||||
description: event.description,
|
description: event.description,
|
||||||
|
@ -395,9 +401,7 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
|
||||||
attendees: event.attendees,
|
attendees: event.attendees,
|
||||||
reminders: {
|
reminders: {
|
||||||
useDefault: false,
|
useDefault: false,
|
||||||
overrides: [
|
overrides: [{ method: "email", minutes: 60 }],
|
||||||
{'method': 'email', 'minutes': 60}
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -405,55 +409,73 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
|
||||||
payload["location"] = event.location;
|
payload["location"] = event.location;
|
||||||
}
|
}
|
||||||
|
|
||||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
|
||||||
calendar.events.update({
|
calendar.events.update(
|
||||||
|
{
|
||||||
auth: myGoogleAuth,
|
auth: myGoogleAuth,
|
||||||
calendarId: 'primary',
|
calendarId: "primary",
|
||||||
eventId: uid,
|
eventId: uid,
|
||||||
sendNotifications: true,
|
sendNotifications: true,
|
||||||
sendUpdates: 'all',
|
sendUpdates: "all",
|
||||||
resource: payload
|
resource: payload,
|
||||||
}, function (err, event) {
|
},
|
||||||
|
function (err, event) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error('There was an error contacting google calendar service: ', err);
|
console.error("There was an error contacting google calendar service: ", err);
|
||||||
return reject(err);
|
return reject(err);
|
||||||
}
|
}
|
||||||
return resolve(event.data);
|
return resolve(event.data);
|
||||||
});
|
}
|
||||||
})),
|
);
|
||||||
deleteEvent: (uid: String) => new Promise( (resolve, reject) => auth.getToken().then(myGoogleAuth => {
|
})
|
||||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
),
|
||||||
calendar.events.delete({
|
deleteEvent: (uid: string) =>
|
||||||
|
new Promise((resolve, reject) =>
|
||||||
|
auth.getToken().then((myGoogleAuth) => {
|
||||||
|
const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
|
||||||
|
calendar.events.delete(
|
||||||
|
{
|
||||||
auth: myGoogleAuth,
|
auth: myGoogleAuth,
|
||||||
calendarId: 'primary',
|
calendarId: "primary",
|
||||||
eventId: uid,
|
eventId: uid,
|
||||||
sendNotifications: true,
|
sendNotifications: true,
|
||||||
sendUpdates: 'all',
|
sendUpdates: "all",
|
||||||
}, function (err, event) {
|
},
|
||||||
|
function (err, event) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error('There was an error contacting google calendar service: ', err);
|
console.error("There was an error contacting google calendar service: ", err);
|
||||||
return reject(err);
|
return reject(err);
|
||||||
}
|
}
|
||||||
return resolve(event.data);
|
return resolve(event.data);
|
||||||
});
|
}
|
||||||
})),
|
);
|
||||||
listCalendars: () => new Promise((resolve, reject) => auth.getToken().then(myGoogleAuth => {
|
})
|
||||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
),
|
||||||
|
listCalendars: () =>
|
||||||
|
new Promise((resolve, reject) =>
|
||||||
|
auth.getToken().then((myGoogleAuth) => {
|
||||||
|
const calendar = google.calendar({ version: "v3", auth: myGoogleAuth });
|
||||||
calendar.calendarList
|
calendar.calendarList
|
||||||
.list()
|
.list()
|
||||||
.then(cals => {
|
.then((cals) => {
|
||||||
resolve(cals.data.items.map(cal => {
|
resolve(
|
||||||
|
cals.data.items.map((cal) => {
|
||||||
const calendar: IntegrationCalendar = {
|
const calendar: IntegrationCalendar = {
|
||||||
externalId: cal.id, integration: integrationType, name: cal.summary, primary: cal.primary
|
externalId: cal.id,
|
||||||
}
|
integration: integrationType,
|
||||||
|
name: cal.summary,
|
||||||
|
primary: cal.primary,
|
||||||
|
};
|
||||||
return calendar;
|
return calendar;
|
||||||
}))
|
})
|
||||||
|
);
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.error('There was an error contacting google calendar service: ', err);
|
console.error("There was an error contacting google calendar service: ", err);
|
||||||
reject(err);
|
reject(err);
|
||||||
});
|
});
|
||||||
}))
|
})
|
||||||
|
),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -472,50 +494,36 @@ const calendars = (withCredentials): CalendarApiAdapter[] =>
|
||||||
})
|
})
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
|
|
||||||
const getBusyCalendarTimes = (
|
const getBusyCalendarTimes = (withCredentials, dateFrom, dateTo, selectedCalendars) =>
|
||||||
withCredentials,
|
|
||||||
dateFrom,
|
|
||||||
dateTo,
|
|
||||||
selectedCalendars
|
|
||||||
) =>
|
|
||||||
Promise.all(
|
Promise.all(
|
||||||
calendars(withCredentials).map((c) =>
|
calendars(withCredentials).map((c) => c.getAvailability(dateFrom, dateTo, selectedCalendars))
|
||||||
c.getAvailability(dateFrom, dateTo, selectedCalendars)
|
|
||||||
)
|
|
||||||
).then((results) => {
|
).then((results) => {
|
||||||
return results.reduce((acc, availability) => acc.concat(availability), []);
|
return results.reduce((acc, availability) => acc.concat(availability), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
const listCalendars = (withCredentials) =>
|
const listCalendars = (withCredentials) =>
|
||||||
Promise.all(calendars(withCredentials).map((c) => c.listCalendars())).then(
|
Promise.all(calendars(withCredentials).map((c) => c.listCalendars())).then((results) =>
|
||||||
(results) => results.reduce((acc, calendars) => acc.concat(calendars), [])
|
results.reduce((acc, calendars) => acc.concat(calendars), [])
|
||||||
);
|
);
|
||||||
|
|
||||||
const createEvent = async (
|
const createEvent = async (credential, calEvent: CalendarEvent): Promise<any> => {
|
||||||
credential,
|
const uid: string = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
|
||||||
calEvent: CalendarEvent
|
|
||||||
): Promise<any> => {
|
|
||||||
const uid: string = translator.fromUUID(
|
|
||||||
uuidv5(JSON.stringify(calEvent), uuidv5.URL)
|
|
||||||
);
|
|
||||||
|
|
||||||
const creationResult = credential
|
const creationResult = credential ? await calendars([credential])[0].createEvent(calEvent) : null;
|
||||||
? await calendars([credential])[0].createEvent(calEvent)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
const organizerMail = new EventOrganizerMail(calEvent, uid);
|
const organizerMail = new EventOrganizerMail(calEvent, uid);
|
||||||
const attendeeMail = new EventAttendeeMail(calEvent, uid);
|
const attendeeMail = new EventAttendeeMail(calEvent, uid);
|
||||||
try {
|
try {
|
||||||
await organizerMail.sendEmail();
|
await organizerMail.sendEmail();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("organizerMail.sendEmail failed", e)
|
console.error("organizerMail.sendEmail failed", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!creationResult || !creationResult.disableConfirmationEmail) {
|
if (!creationResult || !creationResult.disableConfirmationEmail) {
|
||||||
try {
|
try {
|
||||||
await attendeeMail.sendEmail();
|
await attendeeMail.sendEmail();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("attendeeMail.sendEmail failed", e)
|
console.error("attendeeMail.sendEmail failed", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -525,14 +533,8 @@ const createEvent = async (
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateEvent = async (
|
const updateEvent = async (credential, uidToUpdate: string, calEvent: CalendarEvent): Promise<any> => {
|
||||||
credential,
|
const newUid: string = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
|
||||||
uidToUpdate: String,
|
|
||||||
calEvent: CalendarEvent
|
|
||||||
): Promise<any> => {
|
|
||||||
const newUid: string = translator.fromUUID(
|
|
||||||
uuidv5(JSON.stringify(calEvent), uuidv5.URL)
|
|
||||||
);
|
|
||||||
|
|
||||||
const updateResult = credential
|
const updateResult = credential
|
||||||
? await calendars([credential])[0].updateEvent(uidToUpdate, calEvent)
|
? await calendars([credential])[0].updateEvent(uidToUpdate, calEvent)
|
||||||
|
@ -543,14 +545,14 @@ const updateEvent = async (
|
||||||
try {
|
try {
|
||||||
await organizerMail.sendEmail();
|
await organizerMail.sendEmail();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("organizerMail.sendEmail failed", e)
|
console.error("organizerMail.sendEmail failed", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!updateResult || !updateResult.disableConfirmationEmail) {
|
if (!updateResult || !updateResult.disableConfirmationEmail) {
|
||||||
try {
|
try {
|
||||||
await attendeeMail.sendEmail();
|
await attendeeMail.sendEmail();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("attendeeMail.sendEmail failed", e)
|
console.error("attendeeMail.sendEmail failed", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -560,7 +562,7 @@ const updateEvent = async (
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteEvent = (credential, uid: String): Promise<any> => {
|
const deleteEvent = (credential, uid: string): Promise<any> => {
|
||||||
if (credential) {
|
if (credential) {
|
||||||
return calendars([credential])[0].deleteEvent(uid);
|
return calendars([credential])[0].deleteEvent(uid);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,38 +1,38 @@
|
||||||
import type {NextApiRequest, NextApiResponse} from 'next';
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
import prisma from '../../../lib/prisma';
|
import prisma from "../../../lib/prisma";
|
||||||
import {CalendarEvent, createEvent, updateEvent} from '../../../lib/calendarClient';
|
import { CalendarEvent, createEvent, updateEvent } from "../../../lib/calendarClient";
|
||||||
import async from 'async';
|
import async from "async";
|
||||||
import {v5 as uuidv5} from 'uuid';
|
import { v5 as uuidv5 } from "uuid";
|
||||||
import short from 'short-uuid';
|
import short from "short-uuid";
|
||||||
import {createMeeting, updateMeeting} from "../../../lib/videoClient";
|
import { createMeeting, updateMeeting } from "../../../lib/videoClient";
|
||||||
import EventAttendeeMail from "../../../lib/emails/EventAttendeeMail";
|
import EventAttendeeMail from "../../../lib/emails/EventAttendeeMail";
|
||||||
import {getEventName} from "../../../lib/event";
|
import { getEventName } from "../../../lib/event";
|
||||||
import { LocationType } from '../../../lib/location';
|
import { LocationType } from "../../../lib/location";
|
||||||
import merge from "lodash.merge"
|
import merge from "lodash.merge";
|
||||||
const translator = short();
|
const translator = short();
|
||||||
|
|
||||||
interface p {
|
interface p {
|
||||||
location: string
|
location: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const getLocationRequestFromIntegration = ({location}: p) => {
|
const getLocationRequestFromIntegration = ({ location }: p) => {
|
||||||
if (location === LocationType.GoogleMeet.valueOf()) {
|
if (location === LocationType.GoogleMeet.valueOf()) {
|
||||||
const requestId = uuidv5(location, uuidv5.URL)
|
const requestId = uuidv5(location, uuidv5.URL);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
conferenceData: {
|
conferenceData: {
|
||||||
createRequest: {
|
createRequest: {
|
||||||
requestId: requestId
|
requestId: requestId,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return null
|
return null;
|
||||||
}
|
};
|
||||||
|
|
||||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const {user} = req.query;
|
const { user } = req.query;
|
||||||
|
|
||||||
const currentUser = await prisma.user.findFirst({
|
const currentUser = await prisma.user.findFirst({
|
||||||
where: {
|
where: {
|
||||||
|
@ -44,27 +44,27 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||||
timeZone: true,
|
timeZone: true,
|
||||||
email: true,
|
email: true,
|
||||||
name: true,
|
name: true,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Split credentials up into calendar credentials and video credentials
|
// Split credentials up into calendar credentials and video credentials
|
||||||
const calendarCredentials = currentUser.credentials.filter(cred => cred.type.endsWith('_calendar'));
|
const calendarCredentials = currentUser.credentials.filter((cred) => cred.type.endsWith("_calendar"));
|
||||||
const videoCredentials = currentUser.credentials.filter(cred => cred.type.endsWith('_video'));
|
const videoCredentials = currentUser.credentials.filter((cred) => cred.type.endsWith("_video"));
|
||||||
|
|
||||||
const rescheduleUid = req.body.rescheduleUid;
|
const rescheduleUid = req.body.rescheduleUid;
|
||||||
|
|
||||||
const selectedEventType = await prisma.eventType.findFirst({
|
const selectedEventType = await prisma.eventType.findFirst({
|
||||||
where: {
|
where: {
|
||||||
userId: currentUser.id,
|
userId: currentUser.id,
|
||||||
id: req.body.eventTypeId
|
id: req.body.eventTypeId,
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
eventName: true,
|
eventName: true,
|
||||||
title: true
|
title: true,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
let rawLocation = req.body.location
|
const rawLocation = req.body.location;
|
||||||
|
|
||||||
let evt: CalendarEvent = {
|
let evt: CalendarEvent = {
|
||||||
type: selectedEventType.title,
|
type: selectedEventType.title,
|
||||||
|
@ -72,38 +72,35 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||||
description: req.body.notes,
|
description: req.body.notes,
|
||||||
startTime: req.body.start,
|
startTime: req.body.start,
|
||||||
endTime: req.body.end,
|
endTime: req.body.end,
|
||||||
organizer: {email: currentUser.email, name: currentUser.name, timeZone: currentUser.timeZone},
|
organizer: { email: currentUser.email, name: currentUser.name, timeZone: currentUser.timeZone },
|
||||||
attendees: [
|
attendees: [{ email: req.body.email, name: req.body.name, timeZone: req.body.timeZone }],
|
||||||
{email: req.body.email, name: req.body.name, timeZone: req.body.timeZone}
|
|
||||||
]
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// If phone or inPerson use raw location
|
// If phone or inPerson use raw location
|
||||||
// set evt.location to req.body.location
|
// set evt.location to req.body.location
|
||||||
if (!rawLocation?.includes('integration')) {
|
if (!rawLocation?.includes("integration")) {
|
||||||
evt.location = rawLocation
|
evt.location = rawLocation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// If location is set to an integration location
|
// If location is set to an integration location
|
||||||
// Build proper transforms for evt object
|
// Build proper transforms for evt object
|
||||||
// Extend evt object with those transformations
|
// Extend evt object with those transformations
|
||||||
if (rawLocation?.includes('integration')) {
|
if (rawLocation?.includes("integration")) {
|
||||||
let maybeLocationRequestObject = getLocationRequestFromIntegration({
|
const maybeLocationRequestObject = getLocationRequestFromIntegration({
|
||||||
location: rawLocation
|
location: rawLocation,
|
||||||
})
|
});
|
||||||
|
|
||||||
evt = merge(evt, maybeLocationRequestObject)
|
evt = merge(evt, maybeLocationRequestObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
const eventType = await prisma.eventType.findFirst({
|
const eventType = await prisma.eventType.findFirst({
|
||||||
where: {
|
where: {
|
||||||
userId: currentUser.id,
|
userId: currentUser.id,
|
||||||
title: evt.type
|
title: evt.type,
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true
|
id: true,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
let results = [];
|
let results = [];
|
||||||
|
@ -113,7 +110,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||||
// Reschedule event
|
// Reschedule event
|
||||||
const booking = await prisma.booking.findFirst({
|
const booking = await prisma.booking.findFirst({
|
||||||
where: {
|
where: {
|
||||||
uid: rescheduleUid
|
uid: rescheduleUid,
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
|
@ -121,35 +118,39 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
type: true,
|
type: true,
|
||||||
uid: true
|
uid: true,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Use all integrations
|
// Use all integrations
|
||||||
results = results.concat(await async.mapLimit(calendarCredentials, 5, async (credential) => {
|
results = results.concat(
|
||||||
|
await async.mapLimit(calendarCredentials, 5, async (credential) => {
|
||||||
const bookingRefUid = booking.references.filter((ref) => ref.type === credential.type)[0].uid;
|
const bookingRefUid = booking.references.filter((ref) => ref.type === credential.type)[0].uid;
|
||||||
return updateEvent(credential, bookingRefUid, evt)
|
return updateEvent(credential, bookingRefUid, evt)
|
||||||
.then(response => ({type: credential.type, success: true, response}))
|
.then((response) => ({ type: credential.type, success: true, response }))
|
||||||
.catch(e => {
|
.catch((e) => {
|
||||||
console.error("updateEvent failed", e)
|
console.error("updateEvent failed", e);
|
||||||
return {type: credential.type, success: false}
|
return { type: credential.type, success: false };
|
||||||
});
|
});
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
|
|
||||||
results = results.concat(await async.mapLimit(videoCredentials, 5, async (credential) => {
|
results = results.concat(
|
||||||
|
await async.mapLimit(videoCredentials, 5, async (credential) => {
|
||||||
const bookingRefUid = booking.references.filter((ref) => ref.type === credential.type)[0].uid;
|
const bookingRefUid = booking.references.filter((ref) => ref.type === credential.type)[0].uid;
|
||||||
return updateMeeting(credential, bookingRefUid, evt)
|
return updateMeeting(credential, bookingRefUid, evt)
|
||||||
.then(response => ({type: credential.type, success: true, response}))
|
.then((response) => ({ type: credential.type, success: true, response }))
|
||||||
.catch(e => {
|
.catch((e) => {
|
||||||
console.error("updateMeeting failed", e)
|
console.error("updateMeeting failed", e);
|
||||||
return {type: credential.type, success: false}
|
return { type: credential.type, success: false };
|
||||||
});
|
});
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
|
|
||||||
if (results.length > 0 && results.every(res => !res.success)) {
|
if (results.length > 0 && results.every((res) => !res.success)) {
|
||||||
res.status(500).json({message: "Rescheduling failed"});
|
res.status(500).json({ message: "Rescheduling failed" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -157,84 +158,86 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||||
referencesToCreate = [...booking.references];
|
referencesToCreate = [...booking.references];
|
||||||
|
|
||||||
// Now we can delete the old booking and its references.
|
// Now we can delete the old booking and its references.
|
||||||
let bookingReferenceDeletes = prisma.bookingReference.deleteMany({
|
const bookingReferenceDeletes = prisma.bookingReference.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
bookingId: booking.id
|
bookingId: booking.id,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
let attendeeDeletes = prisma.attendee.deleteMany({
|
const attendeeDeletes = prisma.attendee.deleteMany({
|
||||||
where: {
|
where: {
|
||||||
bookingId: booking.id
|
bookingId: booking.id,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
let bookingDeletes = prisma.booking.delete({
|
const bookingDeletes = prisma.booking.delete({
|
||||||
where: {
|
where: {
|
||||||
uid: rescheduleUid
|
uid: rescheduleUid,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
await Promise.all([
|
await Promise.all([bookingReferenceDeletes, attendeeDeletes, bookingDeletes]);
|
||||||
bookingReferenceDeletes,
|
|
||||||
attendeeDeletes,
|
|
||||||
bookingDeletes
|
|
||||||
]);
|
|
||||||
} else {
|
} else {
|
||||||
// Schedule event
|
// Schedule event
|
||||||
results = results.concat(await async.mapLimit(calendarCredentials, 5, async (credential) => {
|
results = results.concat(
|
||||||
|
await async.mapLimit(calendarCredentials, 5, async (credential) => {
|
||||||
return createEvent(credential, evt)
|
return createEvent(credential, evt)
|
||||||
.then(response => ({type: credential.type, success: true, response}))
|
.then((response) => ({ type: credential.type, success: true, response }))
|
||||||
.catch(e => {
|
.catch((e) => {
|
||||||
console.error("createEvent failed", e)
|
console.error("createEvent failed", e);
|
||||||
return {type: credential.type, success: false}
|
return { type: credential.type, success: false };
|
||||||
});
|
});
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
|
|
||||||
results = results.concat(await async.mapLimit(videoCredentials, 5, async (credential) => {
|
results = results.concat(
|
||||||
|
await async.mapLimit(videoCredentials, 5, async (credential) => {
|
||||||
return createMeeting(credential, evt)
|
return createMeeting(credential, evt)
|
||||||
.then(response => ({type: credential.type, success: true, response}))
|
.then((response) => ({ type: credential.type, success: true, response }))
|
||||||
.catch(e => {
|
.catch((e) => {
|
||||||
console.error("createMeeting failed", e)
|
console.error("createMeeting failed", e);
|
||||||
return {type: credential.type, success: false}
|
return { type: credential.type, success: false };
|
||||||
});
|
});
|
||||||
}));
|
})
|
||||||
|
);
|
||||||
|
|
||||||
if (results.length > 0 && results.every(res => !res.success)) {
|
if (results.length > 0 && results.every((res) => !res.success)) {
|
||||||
res.status(500).json({message: "Booking failed"});
|
res.status(500).json({ message: "Booking failed" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
referencesToCreate = results.map((result => {
|
referencesToCreate = results.map((result) => {
|
||||||
return {
|
return {
|
||||||
type: result.type,
|
type: result.type,
|
||||||
uid: result.response.createdEvent.id.toString()
|
uid: result.response.createdEvent.id.toString(),
|
||||||
};
|
};
|
||||||
}));
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const hashUID = results.length > 0 ? results[0].response.uid : translator.fromUUID(uuidv5(JSON.stringify(evt), uuidv5.URL));
|
const hashUID =
|
||||||
|
results.length > 0
|
||||||
|
? results[0].response.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.
|
||||||
if(results.length === 0) {
|
if (results.length === 0) {
|
||||||
// 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 {
|
||||||
const mail = new EventAttendeeMail(evt, hashUID);
|
const mail = new EventAttendeeMail(evt, hashUID);
|
||||||
await mail.sendEmail();
|
await mail.sendEmail();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Sending legacy event mail failed", e)
|
console.error("Sending legacy event mail failed", e);
|
||||||
res.status(500).json({message: "Booking failed"});
|
res.status(500).json({ message: "Booking failed" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let booking;
|
|
||||||
try {
|
try {
|
||||||
booking = await prisma.booking.create({
|
await prisma.booking.create({
|
||||||
data: {
|
data: {
|
||||||
uid: hashUID,
|
uid: hashUID,
|
||||||
userId: currentUser.id,
|
userId: currentUser.id,
|
||||||
references: {
|
references: {
|
||||||
create: referencesToCreate
|
create: referencesToCreate,
|
||||||
},
|
},
|
||||||
eventTypeId: eventType.id,
|
eventTypeId: eventType.id,
|
||||||
|
|
||||||
|
@ -244,13 +247,13 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||||
endTime: evt.endTime,
|
endTime: evt.endTime,
|
||||||
|
|
||||||
attendees: {
|
attendees: {
|
||||||
create: evt.attendees
|
create: evt.attendees,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error when saving booking to db", e);
|
console.error("Error when saving booking to db", e);
|
||||||
res.status(500).json({message: "Booking already exists"});
|
res.status(500).json({ message: "Booking already exists" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue