Merge branch 'main' into feature/invite-external-users
This commit is contained in:
27 files changed
+5123
-305
No files matched your search
+164
-56
@@ -1,4 +1,3 @@
|
||||
|
||||
const {google} = require('googleapis');
|
||||
import createNewEventEmail from "./emails/new-event";
|
||||
|
||||
@@ -7,14 +6,21 @@ const googleAuth = () => {
|
||||
return new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
|
||||
};
|
||||
|
||||
function handleErrors(response) {
|
||||
function handleErrorsJson(response) {
|
||||
if (!response.ok) {
|
||||
response.json().then( console.log );
|
||||
response.json().then(console.log);
|
||||
throw Error(response.statusText);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function handleErrorsRaw(response) {
|
||||
if (!response.ok) {
|
||||
response.text().then(console.log);
|
||||
throw Error(response.statusText);
|
||||
}
|
||||
return response.text();
|
||||
}
|
||||
|
||||
const o365Auth = (credential) => {
|
||||
|
||||
@@ -22,7 +28,7 @@ const o365Auth = (credential) => {
|
||||
|
||||
const refreshAccessToken = (refreshToken) => fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
body: new URLSearchParams({
|
||||
'scope': 'User.Read Calendars.Read Calendars.ReadWrite',
|
||||
'client_id': process.env.MS_GRAPH_CLIENT_ID,
|
||||
@@ -31,19 +37,24 @@ const o365Auth = (credential) => {
|
||||
'client_secret': process.env.MS_GRAPH_CLIENT_SECRET,
|
||||
})
|
||||
})
|
||||
.then(handleErrors)
|
||||
.then( (responseBody) => {
|
||||
credential.key.access_token = responseBody.access_token;
|
||||
credential.key.expiry_date = Math.round((+(new Date()) / 1000) + responseBody.expires_in);
|
||||
return credential.key.access_token;
|
||||
})
|
||||
.then(handleErrorsJson)
|
||||
.then((responseBody) => {
|
||||
credential.key.access_token = responseBody.access_token;
|
||||
credential.key.expiry_date = Math.round((+(new Date()) / 1000) + responseBody.expires_in);
|
||||
return credential.key.access_token;
|
||||
})
|
||||
|
||||
return {
|
||||
getToken: () => ! isExpired(credential.key.expiry_date) ? Promise.resolve(credential.key.access_token) : refreshAccessToken(credential.key.refresh_token)
|
||||
getToken: () => !isExpired(credential.key.expiry_date) ? Promise.resolve(credential.key.access_token) : refreshAccessToken(credential.key.refresh_token)
|
||||
};
|
||||
};
|
||||
|
||||
interface Person { name?: string, email: string, timeZone: string }
|
||||
interface Person {
|
||||
name?: string,
|
||||
email: string,
|
||||
timeZone: string
|
||||
}
|
||||
|
||||
interface CalendarEvent {
|
||||
type: string;
|
||||
title: string;
|
||||
@@ -57,6 +68,11 @@ interface CalendarEvent {
|
||||
|
||||
interface CalendarApiAdapter {
|
||||
createEvent(event: CalendarEvent): Promise<any>;
|
||||
|
||||
updateEvent(uid: String, event: CalendarEvent);
|
||||
|
||||
deleteEvent(uid: String);
|
||||
|
||||
getAvailability(dateFrom, dateTo): Promise<any>;
|
||||
}
|
||||
|
||||
@@ -68,7 +84,7 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||
|
||||
let optional = {};
|
||||
if (event.location) {
|
||||
optional.location = { displayName: event.location };
|
||||
optional.location = {displayName: event.location};
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -99,7 +115,7 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||
return {
|
||||
getAvailability: (dateFrom, dateTo) => {
|
||||
const payload = {
|
||||
schedules: [ credential.key.email ],
|
||||
schedules: [credential.key.email],
|
||||
startTime: {
|
||||
dateTime: dateFrom,
|
||||
timeZone: 'UTC',
|
||||
@@ -120,25 +136,42 @@ const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
.then(handleErrors)
|
||||
.then( responseBody => {
|
||||
return responseBody.value[0].scheduleItems.map( (evt) => ({ start: evt.start.dateTime + 'Z', end: evt.end.dateTime + 'Z' }))
|
||||
})
|
||||
).catch( (err) => {
|
||||
.then(handleErrorsJson)
|
||||
.then(responseBody => {
|
||||
return responseBody.value[0].scheduleItems.map((evt) => ({
|
||||
start: evt.start.dateTime + 'Z',
|
||||
end: evt.end.dateTime + 'Z'
|
||||
}))
|
||||
})
|
||||
).catch((err) => {
|
||||
console.log(err);
|
||||
});
|
||||
},
|
||||
createEvent: (event: CalendarEvent) => auth.getToken().then( accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events', {
|
||||
createEvent: (event: CalendarEvent) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + accessToken,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(translateEvent(event))
|
||||
}).then(handleErrors).then( (responseBody) => ({
|
||||
}).then(handleErrorsJson).then((responseBody) => ({
|
||||
...responseBody,
|
||||
disableConfirmationEmail: true,
|
||||
})))
|
||||
}))),
|
||||
deleteEvent: (uid: String) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events/' + uid, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + accessToken
|
||||
}
|
||||
}).then(handleErrorsRaw)),
|
||||
updateEvent: (uid: String, event: CalendarEvent) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events/' + uid, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + accessToken,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(translateEvent(event))
|
||||
}).then(handleErrorsRaw)),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -146,34 +179,34 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
|
||||
const myGoogleAuth = googleAuth();
|
||||
myGoogleAuth.setCredentials(credential.key);
|
||||
return {
|
||||
getAvailability: (dateFrom, dateTo) => new Promise( (resolve, reject) => {
|
||||
const calendar = google.calendar({ version: 'v3', auth: myGoogleAuth });
|
||||
getAvailability: (dateFrom, dateTo) => new Promise((resolve, reject) => {
|
||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
||||
calendar.calendarList
|
||||
.list()
|
||||
.then(cals => {
|
||||
calendar.freebusy.query({
|
||||
requestBody: {
|
||||
timeMin: dateFrom,
|
||||
timeMax: dateTo,
|
||||
items: cals.data.items
|
||||
}
|
||||
}, (err, apires) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(
|
||||
Object.values(apires.data.calendars).flatMap(
|
||||
(item) => item["busy"]
|
||||
)
|
||||
)
|
||||
.list()
|
||||
.then(cals => {
|
||||
calendar.freebusy.query({
|
||||
requestBody: {
|
||||
timeMin: dateFrom,
|
||||
timeMax: dateTo,
|
||||
items: cals.data.items
|
||||
}
|
||||
}, (err, apires) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(
|
||||
Object.values(apires.data.calendars).flatMap(
|
||||
(item) => item["busy"]
|
||||
)
|
||||
)
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
reject(err);
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
}),
|
||||
createEvent: (event: CalendarEvent) => new Promise( (resolve, reject) => {
|
||||
createEvent: (event: CalendarEvent) => new Promise((resolve, reject) => {
|
||||
const payload = {
|
||||
summary: event.title,
|
||||
description: event.description,
|
||||
@@ -198,12 +231,69 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
|
||||
payload['location'] = event.location;
|
||||
}
|
||||
|
||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth });
|
||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
||||
calendar.events.insert({
|
||||
auth: myGoogleAuth,
|
||||
calendarId: 'primary',
|
||||
resource: payload,
|
||||
}, function(err, event) {
|
||||
}, function (err, event) {
|
||||
if (err) {
|
||||
console.log('There was an error contacting the Calendar service: ' + err);
|
||||
return reject(err);
|
||||
}
|
||||
return resolve(event.data);
|
||||
});
|
||||
}),
|
||||
updateEvent: (uid: String, event: CalendarEvent) => new Promise((resolve, reject) => {
|
||||
const payload = {
|
||||
summary: event.title,
|
||||
description: event.description,
|
||||
start: {
|
||||
dateTime: event.startTime,
|
||||
timeZone: event.organizer.timeZone,
|
||||
},
|
||||
end: {
|
||||
dateTime: event.endTime,
|
||||
timeZone: event.organizer.timeZone,
|
||||
},
|
||||
attendees: event.attendees,
|
||||
reminders: {
|
||||
useDefault: false,
|
||||
overrides: [
|
||||
{'method': 'email', 'minutes': 60}
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
if (event.location) {
|
||||
payload['location'] = event.location;
|
||||
}
|
||||
|
||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
||||
calendar.events.update({
|
||||
auth: myGoogleAuth,
|
||||
calendarId: 'primary',
|
||||
eventId: uid,
|
||||
sendNotifications: true,
|
||||
sendUpdates: 'all',
|
||||
resource: payload
|
||||
}, function (err, event) {
|
||||
if (err) {
|
||||
console.log('There was an error contacting the Calendar service: ' + err);
|
||||
return reject(err);
|
||||
}
|
||||
return resolve(event.data);
|
||||
});
|
||||
}),
|
||||
deleteEvent: (uid: String) => new Promise( (resolve, reject) => {
|
||||
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
||||
calendar.events.delete({
|
||||
auth: myGoogleAuth,
|
||||
calendarId: 'primary',
|
||||
eventId: uid,
|
||||
sendNotifications: true,
|
||||
sendUpdates: 'all',
|
||||
}, function (err, event) {
|
||||
if (err) {
|
||||
console.log('There was an error contacting the Calendar service: ' + err);
|
||||
return reject(err);
|
||||
@@ -215,10 +305,12 @@ const GoogleCalendar = (credential): CalendarApiAdapter => {
|
||||
};
|
||||
|
||||
// factory
|
||||
const calendars = (withCredentials): CalendarApiAdapter[] => withCredentials.map( (cred) => {
|
||||
switch(cred.type) {
|
||||
case 'google_calendar': return GoogleCalendar(cred);
|
||||
case 'office365_calendar': return MicrosoftOffice365Calendar(cred);
|
||||
const calendars = (withCredentials): CalendarApiAdapter[] => withCredentials.map((cred) => {
|
||||
switch (cred.type) {
|
||||
case 'google_calendar':
|
||||
return GoogleCalendar(cred);
|
||||
case 'office365_calendar':
|
||||
return MicrosoftOffice365Calendar(cred);
|
||||
default:
|
||||
return; // unknown credential, could be legacy? In any case, ignore
|
||||
}
|
||||
@@ -226,15 +318,15 @@ const calendars = (withCredentials): CalendarApiAdapter[] => withCredentials.map
|
||||
|
||||
|
||||
const getBusyTimes = (withCredentials, dateFrom, dateTo) => Promise.all(
|
||||
calendars(withCredentials).map( c => c.getAvailability(dateFrom, dateTo) )
|
||||
calendars(withCredentials).map(c => c.getAvailability(dateFrom, dateTo))
|
||||
).then(
|
||||
(results) => results.reduce( (acc, availability) => acc.concat(availability), [])
|
||||
(results) => results.reduce((acc, availability) => acc.concat(availability), [])
|
||||
);
|
||||
|
||||
const createEvent = (credential, calEvent: CalendarEvent): Promise<any> => {
|
||||
|
||||
createNewEventEmail(
|
||||
calEvent,
|
||||
calEvent,
|
||||
);
|
||||
|
||||
if (credential) {
|
||||
@@ -244,4 +336,20 @@ const createEvent = (credential, calEvent: CalendarEvent): Promise<any> => {
|
||||
return Promise.resolve({});
|
||||
};
|
||||
|
||||
export { getBusyTimes, createEvent, CalendarEvent };
|
||||
const updateEvent = (credential, uid: String, calEvent: CalendarEvent): Promise<any> => {
|
||||
if (credential) {
|
||||
return calendars([credential])[0].updateEvent(uid, calEvent);
|
||||
}
|
||||
|
||||
return Promise.resolve({});
|
||||
};
|
||||
|
||||
const deleteEvent = (credential, uid: String): Promise<any> => {
|
||||
if (credential) {
|
||||
return calendars([credential])[0].deleteEvent(uid);
|
||||
}
|
||||
|
||||
return Promise.resolve({});
|
||||
};
|
||||
|
||||
export {getBusyTimes, createEvent, updateEvent, deleteEvent, CalendarEvent};
|
||||
@@ -11,8 +11,8 @@ dayjs.extend(localizedFormat);
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
export default function createConfirmBookedEmail(calEvent: CalendarEvent, options: any = {}) {
|
||||
return sendEmail(calEvent, {
|
||||
export default function createConfirmBookedEmail(calEvent: CalendarEvent, uid: String, options: any = {}) {
|
||||
return sendEmail(calEvent, uid, {
|
||||
provider: {
|
||||
transport: serverConfig.transport,
|
||||
from: serverConfig.from,
|
||||
@@ -21,7 +21,7 @@ export default function createConfirmBookedEmail(calEvent: CalendarEvent, option
|
||||
});
|
||||
}
|
||||
|
||||
const sendEmail = (calEvent: CalendarEvent, {
|
||||
const sendEmail = (calEvent: CalendarEvent, uid: String, {
|
||||
provider,
|
||||
}) => new Promise( (resolve, reject) => {
|
||||
|
||||
@@ -32,9 +32,10 @@ const sendEmail = (calEvent: CalendarEvent, {
|
||||
{
|
||||
to: `${calEvent.attendees[0].name} <${calEvent.attendees[0].email}>`,
|
||||
from: `${calEvent.organizer.name} <${from}>`,
|
||||
replyTo: calEvent.organizer.email,
|
||||
subject: `Confirmed: ${calEvent.type} with ${calEvent.organizer.name} on ${inviteeStart.format('dddd, LL')}`,
|
||||
html: html(calEvent),
|
||||
text: text(calEvent),
|
||||
html: html(calEvent, uid),
|
||||
text: text(calEvent, uid),
|
||||
},
|
||||
(error, info) => {
|
||||
if (error) {
|
||||
@@ -46,7 +47,10 @@ const sendEmail = (calEvent: CalendarEvent, {
|
||||
)
|
||||
});
|
||||
|
||||
const html = (calEvent: CalendarEvent) => {
|
||||
const html = (calEvent: CalendarEvent, uid: String) => {
|
||||
const cancelLink = process.env.BASE_URL + '/cancel/' + uid;
|
||||
const rescheduleLink = process.env.BASE_URL + '/reschedule/' + uid;
|
||||
|
||||
const inviteeStart: Dayjs = <Dayjs>dayjs(calEvent.startTime).tz(calEvent.attendees[0].timeZone);
|
||||
return `
|
||||
<div>
|
||||
@@ -58,9 +62,13 @@ const html = (calEvent: CalendarEvent) => {
|
||||
calEvent.location ? `<strong>Location:</strong> ${calEvent.location}<br /><br />` : ''
|
||||
) +
|
||||
`Additional notes:<br />
|
||||
${calEvent.description}
|
||||
${calEvent.description}<br />
|
||||
<br />
|
||||
Need to change this event?<br />
|
||||
Cancel: <a href="${cancelLink}">${cancelLink}</a><br />
|
||||
Reschedule: <a href="${rescheduleLink}">${rescheduleLink}</a>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
const text = (evt: CalendarEvent) => html(evt).replace('<br />', "\n").replace(/<[^>]+>/g, '');
|
||||
const text = (evt: CalendarEvent, uid: String) => html(evt, uid).replace('<br />', "\n").replace(/<[^>]+>/g, '');
|
||||
+2
-1
@@ -9,7 +9,8 @@ export const telemetryEventTypes = {
|
||||
pageView: 'page_view',
|
||||
dateSelected: 'date_selected',
|
||||
timeSelected: 'time_selected',
|
||||
bookingConfirmed: 'booking_confirmed'
|
||||
bookingConfirmed: 'booking_confirmed',
|
||||
bookingCancelled: 'booking_cancelled'
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user