Emails Revamp (#1201)

* refactor: emails (WIP)

* wip

* wip

* refactor: calendarClient

* chore: remove comment

* feat: new templates

* feat: more templates (wip)

* feat: email templates wip

* feat: email templates wip

* feat: prepare for testing

* For testing stripe integration

* Uses imported BASE_URL

* Fixes types

* use BASE_URL

Co-authored-by: Omar López <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2021-11-26 11:03:43 +00:00
1 parent 36767afbf5
commit 8322e5c8d1
57 files changed
+4950 -2572

No files matched your search

@@ -18,7 +18,6 @@ import { symmetricDecrypt } from "@lib/crypto";
import logger from "@lib/logger";
import { IntegrationCalendar, CalendarApiAdapter, CalendarEvent } from "../../calendarClient";
import { stripHtml } from "../../emails/helpers";
dayjs.extend(utc);
@@ -80,7 +79,7 @@ export class AppleCalendar implements CalendarApiAdapter {
start: this.convertDate(event.startTime),
duration: this.getDuration(event.startTime, event.endTime),
title: event.title,
description: stripHtml(event.description ?? ""),
description: event.description ?? "",
location: event.location,
organizer: { email: event.organizer.email, name: event.organizer.name },
attendees: this.getAttendees(event.attendees),
@@ -138,7 +137,7 @@ export class AppleCalendar implements CalendarApiAdapter {
start: this.convertDate(event.startTime),
duration: this.getDuration(event.startTime, event.endTime),
title: event.title,
description: stripHtml(event.description ?? ""),
description: event.description ?? "",
location: event.location,
organizer: { email: event.organizer.email, name: event.organizer.name },
attendees: this.getAttendees(event.attendees),
@@ -18,7 +18,6 @@ import { symmetricDecrypt } from "@lib/crypto";
import logger from "@lib/logger";
import { CalendarApiAdapter, CalendarEvent, IntegrationCalendar } from "../../calendarClient";
import { stripHtml } from "../../emails/helpers";
dayjs.extend(utc);
@@ -83,7 +82,7 @@ export class CalDavCalendar implements CalendarApiAdapter {
start: this.convertDate(event.startTime),
duration: this.getDuration(event.startTime, event.endTime),
title: event.title,
description: stripHtml(event.description ?? ""),
description: event.description ?? "",
location: event.location,
organizer: { email: event.organizer.email, name: event.organizer.name },
attendees: this.getAttendees(event.attendees),
@@ -142,7 +141,7 @@ export class CalDavCalendar implements CalendarApiAdapter {
start: this.convertDate(event.startTime),
duration: this.getDuration(event.startTime, event.endTime),
title: event.title,
description: stripHtml(event.description ?? ""),
description: event.description ?? "",
location: event.location,
organizer: { email: event.organizer.email, name: event.organizer.name },
attendees: this.getAttendees(event.attendees),
+20 -8
View File
@@ -1,9 +1,11 @@
import { Credential } from "@prisma/client";
import { CalendarEvent } from "@lib/calendarClient";
import { BASE_URL } from "@lib/config/constants";
import { handleErrorsJson } from "@lib/errors";
import { PartialReference } from "@lib/events/EventManager";
import prisma from "@lib/prisma";
import { VideoApiAdapter } from "@lib/videoClient";
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
export interface DailyReturnType {
/** Long UID string ie: 987b5eb5-d116-4a4e-8e2c-14fcb5710966 */
@@ -67,7 +69,7 @@ const DailyVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
});
}
async function createOrUpdateMeeting(endpoint: string, event: CalendarEvent) {
async function createOrUpdateMeeting(endpoint: string, event: CalendarEvent): Promise<VideoCallData> {
if (!event.uid) {
throw new Error("We need need the booking uid to create the Daily reference in DB");
}
@@ -89,7 +91,12 @@ const DailyVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
},
});
return dailyEvent;
return Promise.resolve({
type: "daily_video",
id: dailyEvent.name,
password: "",
url: BASE_URL + "/call/" + event.uid,
});
}
const translateEvent = (event: CalendarEvent) => {
@@ -133,15 +140,20 @@ const DailyVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
getAvailability: () => {
return Promise.resolve([]);
},
createMeeting: async (event: CalendarEvent) => createOrUpdateMeeting("/rooms", event),
deleteMeeting: (uid: string) =>
fetch("https://api.daily.co/v1/rooms/" + uid, {
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> =>
createOrUpdateMeeting("/rooms", event),
deleteMeeting: async (uid: string): Promise<void> => {
await fetch("https://api.daily.co/v1/rooms/" + uid, {
method: "DELETE",
headers: {
Authorization: "Bearer " + dailyApiToken,
},
}).then(handleErrorsJson),
updateMeeting: (uid: string, event: CalendarEvent) => createOrUpdateMeeting("/rooms/" + uid, event),
}).then(handleErrorsJson);
return Promise.resolve();
},
updateMeeting: (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> =>
createOrUpdateMeeting("/rooms/" + bookingRef.uid, event),
};
};
@@ -0,0 +1,255 @@
import { Credential, Prisma } from "@prisma/client";
import { GetTokenResponse } from "google-auth-library/build/src/auth/oauth2client";
import { Auth, calendar_v3, google } from "googleapis";
import { CalendarApiAdapter, CalendarEvent, IntegrationCalendar } from "@lib/calendarClient";
import prisma from "@lib/prisma";
export interface ConferenceData {
createRequest: calendar_v3.Schema$CreateConferenceRequest;
}
const googleAuth = (credential: Credential) => {
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 googleCredentials = credential.key as Auth.Credentials;
myGoogleAuth.setCredentials(googleCredentials);
// FIXME - type errors IDK Why this is a protected method ¯\_(ツ)_/¯
const isExpired = () => myGoogleAuth.isTokenExpiring();
const refreshAccessToken = () =>
myGoogleAuth
// FIXME - type errors IDK Why this is a protected method ¯\_(ツ)_/¯
.refreshToken(googleCredentials.refresh_token)
.then((res: GetTokenResponse) => {
const token = res.res?.data;
googleCredentials.access_token = token.access_token;
googleCredentials.expiry_date = token.expiry_date;
return prisma.credential
.update({
where: {
id: credential.id,
},
data: {
key: googleCredentials as Prisma.InputJsonValue,
},
})
.then(() => {
myGoogleAuth.setCredentials(googleCredentials);
return myGoogleAuth;
});
})
.catch((err) => {
console.error("Error refreshing google token", err);
return myGoogleAuth;
});
return {
getToken: () => (!isExpired() ? Promise.resolve(myGoogleAuth) : refreshAccessToken()),
};
};
export const GoogleCalendarApiAdapter = (credential: Credential): CalendarApiAdapter => {
const auth = googleAuth(credential);
const integrationType = "google_calendar";
return {
getAvailability: (dateFrom, dateTo, selectedCalendars) =>
new Promise((resolve, reject) =>
auth.getToken().then((myGoogleAuth) => {
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
resolve([]);
return;
}
(selectedCalendarIds.length === 0
? calendar.calendarList
.list()
.then((cals) => cals.data.items?.map((cal) => cal.id).filter(Boolean) || [])
: Promise.resolve(selectedCalendarIds)
)
.then((calsIds) => {
calendar.freebusy.query(
{
requestBody: {
timeMin: dateFrom,
timeMax: dateTo,
items: calsIds.map((id) => ({ id: id })),
},
},
(err, apires) => {
if (err) {
reject(err);
}
resolve(Object.values(apires.data.calendars).flatMap((item) => item["busy"]));
}
);
})
.catch((err) => {
console.error("There was an error contacting google calendar service: ", err);
reject(err);
});
})
),
createEvent: (event: CalendarEvent) =>
new Promise((resolve, reject) =>
auth.getToken().then((myGoogleAuth) => {
const payload: calendar_v3.Schema$Event = {
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: 10 }],
},
};
if (event.location) {
payload["location"] = event.location;
}
if (event.conferenceData && event.location === "integrations:google:meet") {
payload["conferenceData"] = event.conferenceData;
}
const calendar = google.calendar({
version: "v3",
auth: myGoogleAuth,
});
calendar.events.insert(
{
auth: myGoogleAuth,
calendarId: "primary",
requestBody: payload,
conferenceDataVersion: 1,
},
function (err, event) {
if (err || !event?.data) {
console.error("There was an error contacting google calendar service: ", err);
return reject(err);
}
return resolve(event.data);
}
);
})
),
updateEvent: (uid: string, event: CalendarEvent) =>
new Promise((resolve, reject) =>
auth.getToken().then((myGoogleAuth) => {
const payload: calendar_v3.Schema$Event = {
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: 10 }],
},
};
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",
requestBody: payload,
},
function (err, event) {
if (err) {
console.error("There was an error contacting google calendar service: ", err);
return reject(err);
}
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(
{
auth: myGoogleAuth,
calendarId: "primary",
eventId: uid,
sendNotifications: true,
sendUpdates: "all",
},
function (err, event) {
if (err) {
console.error("There was an error contacting google calendar service: ", err);
return reject(err);
}
return resolve(event?.data);
}
);
})
),
listCalendars: () =>
new Promise((resolve, reject) =>
auth.getToken().then((myGoogleAuth) => {
const calendar = google.calendar({
version: "v3",
auth: myGoogleAuth,
});
calendar.calendarList
.list()
.then((cals) => {
resolve(
cals.data.items?.map((cal) => {
const calendar: IntegrationCalendar = {
externalId: cal.id ?? "No id",
integration: integrationType,
name: cal.summary ?? "No name",
primary: cal.primary ?? false,
};
return calendar;
}) || []
);
})
.catch((err) => {
console.error("There was an error contacting google calendar service: ", err);
reject(err);
});
})
),
};
};
@@ -0,0 +1,216 @@
import { Calendar as OfficeCalendar } from "@microsoft/microsoft-graph-types-beta";
import { Credential } from "@prisma/client";
import { CalendarApiAdapter, CalendarEvent, IntegrationCalendar } from "@lib/calendarClient";
import { handleErrorsJson, handleErrorsRaw } from "@lib/errors";
import prisma from "@lib/prisma";
export type BufferedBusyTime = {
start: string;
end: string;
};
type O365AuthCredentials = {
expiry_date: number;
access_token: string;
refresh_token: string;
};
const o365Auth = (credential: Credential) => {
const isExpired = (expiryDate: number) => expiryDate < Math.round(+new Date() / 1000);
const o365AuthCredentials = credential.key as O365AuthCredentials;
const refreshAccessToken = (refreshToken: string) => {
return fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
method: "POST",
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!,
refresh_token: refreshToken,
grant_type: "refresh_token",
client_secret: process.env.MS_GRAPH_CLIENT_SECRET!,
}),
})
.then(handleErrorsJson)
.then((responseBody) => {
o365AuthCredentials.access_token = responseBody.access_token;
o365AuthCredentials.expiry_date = Math.round(+new Date() / 1000 + responseBody.expires_in);
return prisma.credential
.update({
where: {
id: credential.id,
},
data: {
key: o365AuthCredentials,
},
})
.then(() => o365AuthCredentials.access_token);
});
};
return {
getToken: () =>
!isExpired(o365AuthCredentials.expiry_date)
? Promise.resolve(o365AuthCredentials.access_token)
: refreshAccessToken(o365AuthCredentials.refresh_token),
};
};
export const Office365CalendarApiAdapter = (credential: Credential): CalendarApiAdapter => {
const auth = o365Auth(credential);
const translateEvent = (event: CalendarEvent) => {
return {
subject: event.title,
body: {
contentType: "HTML",
content: event.description,
},
start: {
dateTime: event.startTime,
timeZone: event.organizer.timeZone,
},
end: {
dateTime: event.endTime,
timeZone: event.organizer.timeZone,
},
attendees: event.attendees.map((attendee) => ({
emailAddress: {
address: attendee.email,
name: attendee.name,
},
type: "required",
})),
location: event.location ? { displayName: event.location } : undefined,
};
};
const integrationType = "office365_calendar";
function listCalendars(): Promise<IntegrationCalendar[]> {
return auth.getToken().then((accessToken) =>
fetch("https://graph.microsoft.com/v1.0/me/calendars", {
method: "get",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
})
.then(handleErrorsJson)
.then((responseBody: { value: OfficeCalendar[] }) => {
return responseBody.value.map((cal) => {
const calendar: IntegrationCalendar = {
externalId: cal.id ?? "No Id",
integration: integrationType,
name: cal.name ?? "No calendar name",
primary: cal.isDefaultCalendar ?? false,
};
return calendar;
});
})
);
}
return {
getAvailability: (dateFrom, dateTo, selectedCalendars) => {
const filter = `?startdatetime=${encodeURIComponent(dateFrom)}&enddatetime=${encodeURIComponent(
dateTo
)}`;
return auth
.getToken()
.then((accessToken) => {
const selectedCalendarIds = selectedCalendars
.filter((e) => e.integration === integrationType)
.map((e) => e.externalId)
.filter(Boolean);
if (selectedCalendarIds.length === 0 && selectedCalendars.length > 0) {
// Only calendars of other integrations selected
return Promise.resolve([]);
}
return (
selectedCalendarIds.length === 0
? listCalendars().then((cals) => cals.map((e) => e.externalId).filter(Boolean) || [])
: Promise.resolve(selectedCalendarIds)
).then((ids) => {
const requests = ids.map((calendarId, id) => ({
id,
method: "GET",
headers: {
Prefer: 'outlook.timezone="Etc/GMT"',
},
url: `/me/calendars/${calendarId}/calendarView${filter}`,
}));
type BatchResponse = {
responses: SubResponse[];
};
type SubResponse = {
body: { value: { start: { dateTime: string }; end: { dateTime: string } }[] };
};
return fetch("https://graph.microsoft.com/v1.0/$batch", {
method: "POST",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify({ requests }),
})
.then(handleErrorsJson)
.then((responseBody: BatchResponse) =>
responseBody.responses.reduce(
(acc: BufferedBusyTime[], subResponse) =>
acc.concat(
subResponse.body.value.map((evt) => {
return {
start: evt.start.dateTime + "Z",
end: evt.end.dateTime + "Z",
};
})
),
[]
)
);
});
})
.catch((err) => {
console.log(err);
return Promise.reject([]);
});
},
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(handleErrorsJson)
),
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)
),
listCalendars,
};
};
+53 -32
View File
@@ -2,11 +2,13 @@ import { Credential } from "@prisma/client";
import { CalendarEvent } from "@lib/calendarClient";
import { handleErrorsJson, handleErrorsRaw } from "@lib/errors";
import { PartialReference } from "@lib/events/EventManager";
import prisma from "@lib/prisma";
import { VideoApiAdapter } from "@lib/videoClient";
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
/** @link https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate */
export interface ZoomEventResult {
password: string;
created_at: string;
duration: number;
host_id: string;
@@ -168,37 +170,56 @@ const ZoomVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
return [];
});
},
createMeeting: (event: CalendarEvent) =>
auth.getToken().then((accessToken) =>
fetch("https://api.zoom.us/v2/users/me/meetings", {
method: "POST",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify(translateEvent(event)),
}).then(handleErrorsJson)
),
deleteMeeting: (uid: string) =>
auth.getToken().then((accessToken) =>
fetch("https://api.zoom.us/v2/meetings/" + uid, {
method: "DELETE",
headers: {
Authorization: "Bearer " + accessToken,
},
}).then(handleErrorsRaw)
),
updateMeeting: (uid: string, event: CalendarEvent) =>
auth.getToken().then((accessToken: string) =>
fetch("https://api.zoom.us/v2/meetings/" + uid, {
method: "PATCH",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify(translateEvent(event)),
}).then(handleErrorsRaw)
),
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> => {
const accessToken = await auth.getToken();
const result = await fetch("https://api.zoom.us/v2/users/me/meetings", {
method: "POST",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify(translateEvent(event)),
}).then(handleErrorsJson);
return Promise.resolve({
type: "zoom_video",
id: result.id as string,
password: result.password ?? "",
url: result.join_url,
});
},
deleteMeeting: async (uid: string): Promise<void> => {
const accessToken = await auth.getToken();
await fetch("https://api.zoom.us/v2/meetings/" + uid, {
method: "DELETE",
headers: {
Authorization: "Bearer " + accessToken,
},
}).then(handleErrorsRaw);
return Promise.resolve();
},
updateMeeting: async (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> => {
const accessToken = await auth.getToken();
await fetch("https://api.zoom.us/v2/meetings/" + bookingRef.uid, {
method: "PATCH",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify(translateEvent(event)),
}).then(handleErrorsRaw);
return Promise.resolve({
type: "zoom_video",
id: bookingRef.meetingId as string,
password: bookingRef.meetingPassword as string,
url: bookingRef.meetingUrl as string,
});
},
};
};