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

+8 -12
View File
@@ -4,8 +4,8 @@ import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import { NextApiRequest, NextApiResponse } from "next";
import sendEmail from "@lib/emails/sendMail";
import { buildForgotPasswordMessage } from "@lib/forgot-password/messaging/forgot-password";
import { sendPasswordResetEmail } from "@lib/emails/email-manager";
import { PasswordReset, PASSWORD_RESET_EXPIRY_HOURS } from "@lib/emails/templates/forgot-password-email";
import prisma from "@lib/prisma";
import { getTranslation } from "@server/lib/i18n";
@@ -51,7 +51,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (maybePreviousRequest && maybePreviousRequest?.length >= 1) {
passwordRequest = maybePreviousRequest[0];
} else {
const expiry = dayjs().add(6, "hours").toDate();
const expiry = dayjs().add(PASSWORD_RESET_EXPIRY_HOURS, "hours").toDate();
const createdResetPasswordRequest = await prisma.resetPasswordRequest.create({
data: {
email: rawEmail,
@@ -61,20 +61,16 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
passwordRequest = createdResetPasswordRequest;
}
const passwordResetLink = `${process.env.BASE_URL}/auth/forgot-password/${passwordRequest.id}`;
const { subject, message } = buildForgotPasswordMessage({
const passwordEmail: PasswordReset = {
language: t,
user: {
name: maybeUser.name,
email: rawEmail,
},
link: passwordResetLink,
});
resetLink: `${process.env.BASE_URL}/auth/forgot-password/${passwordRequest.id}`,
};
await sendEmail({
to: rawEmail,
subject: subject,
text: message,
});
await sendPasswordResetEmail(passwordEmail);
return res.status(201).json({ message: "Reset Requested" });
} catch (reason) {
+30 -4
View File
@@ -4,9 +4,11 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { refund } from "@ee/lib/stripe/server";
import { getSession } from "@lib/auth";
import { CalendarEvent } from "@lib/calendarClient";
import EventRejectionMail from "@lib/emails/EventRejectionMail";
import { CalendarEvent, AdditionInformation } from "@lib/calendarClient";
import { sendDeclinedEmails } from "@lib/emails/email-manager";
import { sendScheduledEmails } from "@lib/emails/email-manager";
import EventManager from "@lib/events/EventManager";
import logger from "@lib/logger";
import prisma from "@lib/prisma";
import { BookingConfirmBody } from "@lib/types/booking";
@@ -38,6 +40,8 @@ const authorized = async (
return false;
};
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
export default async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
const t = await getTranslation(req.body.language ?? "en", "common");
@@ -63,6 +67,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
timeZone: true,
email: true,
name: true,
username: true,
},
});
@@ -124,6 +129,27 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const eventManager = new EventManager(currentUser.credentials);
const scheduleResult = await eventManager.create(evt);
const results = scheduleResult.results;
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
errorCode: "BookingCreatingMeetingFailed",
message: "Booking failed",
};
log.error(`Booking ${currentUser.username} failed`, error, results);
} else {
const metadata: AdditionInformation = {};
if (results.length) {
// TODO: Handle created event metadata more elegantly
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
metadata.conferenceData = results[0].createdEvent?.conferenceData;
metadata.entryPoints = results[0].createdEvent?.entryPoints;
}
await sendScheduledEmails({ ...evt, additionInformation: metadata });
}
await prisma.booking.update({
where: {
id: bookingId,
@@ -149,8 +175,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
status: BookingStatus.REJECTED,
},
});
const attendeeMail = new EventRejectionMail(evt);
await attendeeMail.sendEmail();
await sendDeclinedEmails(evt);
res.status(204).end();
}
+36 -18
View File
@@ -11,11 +11,16 @@ import { v5 as uuidv5 } from "uuid";
import { handlePayment } from "@ee/lib/stripe/server";
import { CalendarEvent, getBusyCalendarTimes } from "@lib/calendarClient";
import EventOrganizerRequestMail from "@lib/emails/EventOrganizerRequestMail";
import { CalendarEvent, AdditionInformation, getBusyCalendarTimes } from "@lib/calendarClient";
import {
sendScheduledEmails,
sendRescheduledEmails,
sendOrganizerRequestEmail,
} from "@lib/emails/email-manager";
import { getErrorFromUnknown } from "@lib/errors";
import { getEventName } from "@lib/event";
import EventManager, { EventResult, PartialReference } from "@lib/events/EventManager";
import { BufferedBusyTime } from "@lib/integrations/Office365Calendar/Office365CalendarApiAdapter";
import logger from "@lib/logger";
import prisma from "@lib/prisma";
import { BookingCreateBody } from "@lib/types/booking";
@@ -25,13 +30,6 @@ import getSubscribers from "@lib/webhooks/subscriptions";
import { getTranslation } from "@server/lib/i18n";
export interface DailyReturnType {
name: string;
url: string;
id: string;
created_at: string;
}
dayjs.extend(dayjsBusinessTime);
dayjs.extend(utc);
dayjs.extend(isBetween);
@@ -40,7 +38,7 @@ dayjs.extend(timezone);
const translator = short();
const log = logger.getChildLogger({ prefix: ["[api] book:user"] });
type BufferedBusyTimes = { start: string; end: string }[];
type BufferedBusyTimes = BufferedBusyTime[];
/**
* Refreshes a Credential with fresh data from the database.
@@ -285,7 +283,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
attendees: attendeesList,
location: reqBody.location, // Will be processed by the EventManager later.
language: t,
uid,
};
if (eventType.schedulingType === SchedulingType.COLLECTIVE) {
@@ -439,10 +436,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (rescheduleUid) {
// Use EventManager to conditionally use all needed integrations.
const updateResults = await eventManager.update(evt, rescheduleUid);
const updateManager = await eventManager.update(evt, rescheduleUid);
results = updateResults.results;
referencesToCreate = updateResults.referencesToCreate;
results = updateManager.results;
referencesToCreate = updateManager.referencesToCreate;
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
@@ -451,15 +448,26 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
};
log.error(`Booking ${user.name} failed`, error, results);
} else {
const metadata: AdditionInformation = {};
if (results.length) {
// TODO: Handle created event metadata more elegantly
metadata.hangoutLink = results[0].updatedEvent?.hangoutLink;
metadata.conferenceData = results[0].updatedEvent?.conferenceData;
metadata.entryPoints = results[0].updatedEvent?.entryPoints;
}
await sendRescheduledEmails({ ...evt, additionInformation: metadata });
}
// If it's not a reschedule, doesn't require confirmation and there's no price,
// Create a booking
} else if (!eventType.requiresConfirmation && !eventType.price) {
// Use EventManager to conditionally use all needed integrations.
const createResults = await eventManager.create(evt);
const createManager = await eventManager.create(evt);
results = createResults.results;
referencesToCreate = createResults.referencesToCreate;
results = createManager.results;
referencesToCreate = createManager.referencesToCreate;
if (results.length > 0 && results.every((res) => !res.success)) {
const error = {
@@ -468,11 +476,21 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
};
log.error(`Booking ${user.username} failed`, error, results);
} else {
const metadata: AdditionInformation = {};
if (results.length) {
// TODO: Handle created event metadata more elegantly
metadata.hangoutLink = results[0].createdEvent?.hangoutLink;
metadata.conferenceData = results[0].createdEvent?.conferenceData;
metadata.entryPoints = results[0].createdEvent?.entryPoints;
}
await sendScheduledEmails({ ...evt, additionInformation: metadata });
}
}
if (eventType.requiresConfirmation && !rescheduleUid) {
await new EventOrganizerRequestMail(evt).sendEmail();
await sendOrganizerRequestEmail(evt);
}
if (typeof eventType.price === "number" && eventType.price > 0) {
+3 -1
View File
@@ -7,6 +7,7 @@ import { refund } from "@ee/lib/stripe/server";
import { asStringOrNull } from "@lib/asStringOrNull";
import { getSession } from "@lib/auth";
import { CalendarEvent, deleteEvent } from "@lib/calendarClient";
import { sendCancelledEmails } from "@lib/emails/email-manager";
import { FAKE_DAILY_CREDENTIAL } from "@lib/integrations/Daily/DailyVideoApiAdapter";
import prisma from "@lib/prisma";
import { deleteMeeting } from "@lib/videoClient";
@@ -101,6 +102,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return retObj;
}),
uid: bookingToDelete?.uid,
location: bookingToDelete?.location,
language: t,
};
@@ -189,7 +191,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
await Promise.all([apiDeletes, attendeeDeletes, bookingReferenceDeletes]);
//TODO Perhaps send emails to user and client to tell about the cancellation
await sendCancelledEmails(evt);
res.status(204).end();
}
+3 -2
View File
@@ -3,7 +3,7 @@ import dayjs from "dayjs";
import type { NextApiRequest, NextApiResponse } from "next";
import { CalendarEvent } from "@lib/calendarClient";
import EventOrganizerRequestReminderMail from "@lib/emails/EventOrganizerRequestReminderMail";
import { sendOrganizerRequestReminderEmail } from "@lib/emails/email-manager";
import prisma from "@lib/prisma";
import { getTranslation } from "@server/lib/i18n";
@@ -90,7 +90,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
language: t,
};
await new EventOrganizerRequestReminderMail(evt).sendEmail();
await sendOrganizerRequestReminderEmail(evt);
await prisma.reminderMail.create({
data: {
referenceId: booking.id,
+15 -8
View File
@@ -2,7 +2,9 @@ import { randomBytes } from "crypto";
import type { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@lib/auth";
import { createInvitationEmail } from "@lib/emails/invitation";
import { BASE_URL } from "@lib/config/constants";
import { sendTeamInviteEmail } from "@lib/emails/email-manager";
import { TeamInvite } from "@lib/emails/templates/team-invite-email";
import prisma from "@lib/prisma";
import { getTranslation } from "@server/lib/i18n";
@@ -72,13 +74,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
});
if (session?.user?.name && team?.name) {
createInvitationEmail({
const teamInviteEvent: TeamInvite = {
language: t,
toEmail: req.body.usernameOrEmail,
from: session.user.name,
to: req.body.usernameOrEmail,
teamName: team.name,
token,
});
joinLink: `${BASE_URL}/auth/signup?token=${token}&callbackUrl=${BASE_URL + "/settings/teams"}`,
};
await sendTeamInviteEmail(teamInviteEvent);
}
return res.status(201).json({});
@@ -106,12 +110,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// inform user of membership by email
if (req.body.sendEmailInvitation && session?.user?.name && team?.name) {
createInvitationEmail({
const teamInviteEvent: TeamInvite = {
language: t,
toEmail: invitee.email,
from: session.user.name,
to: req.body.usernameOrEmail,
teamName: team.name,
});
joinLink: BASE_URL + "/settings/teams",
};
await sendTeamInviteEmail(teamInviteEvent);
}
res.status(201).json({});