2022-10-07 13:31:05 +03:00
|
|
|
const {promises: fs, readFileSync} = require('fs');
|
2022-08-25 10:25:36 +03:00
|
|
|
const path = require('path');
|
|
|
|
const moment = require('moment');
|
2022-10-07 13:31:05 +03:00
|
|
|
const glob = require('glob');
|
2022-08-25 10:25:36 +03:00
|
|
|
|
|
|
|
class StaffServiceEmails {
|
2022-09-02 17:57:59 +03:00
|
|
|
constructor({logging, models, mailer, settingsHelpers, settingsCache, urlUtils}) {
|
2022-08-25 10:25:36 +03:00
|
|
|
this.logging = logging;
|
|
|
|
this.models = models;
|
|
|
|
this.mailer = mailer;
|
2022-09-02 17:57:59 +03:00
|
|
|
this.settingsHelpers = settingsHelpers;
|
2022-08-25 10:25:36 +03:00
|
|
|
this.settingsCache = settingsCache;
|
|
|
|
this.urlUtils = urlUtils;
|
|
|
|
|
|
|
|
this.Handlebars = require('handlebars');
|
2022-10-07 13:31:05 +03:00
|
|
|
this.registerPartials();
|
2022-08-25 10:25:36 +03:00
|
|
|
}
|
|
|
|
|
2023-03-06 12:36:47 +03:00
|
|
|
async notifyFreeMemberSignup({
|
|
|
|
member, attribution
|
|
|
|
}, options) {
|
2022-08-25 10:25:36 +03:00
|
|
|
const users = await this.models.User.getEmailAlertUsers('free-signup', options);
|
|
|
|
|
|
|
|
for (const user of users) {
|
|
|
|
const to = user.email;
|
|
|
|
const memberData = this.getMemberData(member);
|
|
|
|
|
|
|
|
const subject = `🥳 Free member signup: ${memberData.name}`;
|
|
|
|
|
2023-03-10 17:44:53 +03:00
|
|
|
let attributionTitle = attribution?.title || '';
|
|
|
|
// In case of a homepage attribution, we want to show the title as "Homepage" on email
|
|
|
|
if (attributionTitle === 'homepage') {
|
|
|
|
attributionTitle = 'Homepage';
|
|
|
|
}
|
|
|
|
|
2022-08-25 10:25:36 +03:00
|
|
|
const templateData = {
|
|
|
|
memberData,
|
2023-03-10 17:44:53 +03:00
|
|
|
attributionTitle,
|
|
|
|
attributionUrl: attribution?.url || '',
|
2023-03-06 12:36:47 +03:00
|
|
|
referrerSource: attribution?.referrerSource,
|
2022-08-25 10:25:36 +03:00
|
|
|
siteTitle: this.settingsCache.get('title'),
|
|
|
|
siteUrl: this.urlUtils.getSiteUrl(),
|
|
|
|
siteDomain: this.siteDomain,
|
|
|
|
accentColor: this.settingsCache.get('accent_color'),
|
|
|
|
fromEmail: this.fromEmailAddress,
|
|
|
|
toEmail: to,
|
|
|
|
staffUrl: this.urlUtils.urlJoin(this.urlUtils.urlFor('admin', true), '#', `/settings/staff/${user.slug}`)
|
|
|
|
};
|
|
|
|
|
|
|
|
const {html, text} = await this.renderEmailTemplate('new-free-signup', templateData);
|
|
|
|
|
|
|
|
await this.sendMail({
|
|
|
|
to,
|
|
|
|
subject,
|
|
|
|
html,
|
|
|
|
text
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-06 12:36:47 +03:00
|
|
|
async notifyPaidSubscriptionStarted({member, subscription, offer, tier, attribution}, options = {}) {
|
2022-08-25 10:25:36 +03:00
|
|
|
const users = await this.models.User.getEmailAlertUsers('paid-started', options);
|
|
|
|
|
|
|
|
for (const user of users) {
|
|
|
|
const to = user.email;
|
|
|
|
const memberData = this.getMemberData(member);
|
|
|
|
|
|
|
|
const subject = `💸 Paid subscription started: ${memberData.name}`;
|
|
|
|
|
2022-09-09 17:23:43 +03:00
|
|
|
const amount = this.getAmount(subscription?.amount);
|
|
|
|
const formattedAmount = this.getFormattedAmount({currency: subscription?.currency, amount});
|
|
|
|
const interval = subscription?.interval || '';
|
2022-08-25 10:25:36 +03:00
|
|
|
const tierData = {
|
|
|
|
name: tier?.name || '',
|
|
|
|
details: `${formattedAmount}/${interval}`
|
|
|
|
};
|
|
|
|
|
|
|
|
const subscriptionData = {
|
2022-09-09 17:23:43 +03:00
|
|
|
startedOn: this.getFormattedDate(subscription.startDate)
|
2022-08-25 10:25:36 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
let offerData = this.getOfferData(offer);
|
|
|
|
|
2023-03-10 17:44:53 +03:00
|
|
|
let attributionTitle = attribution?.title || '';
|
|
|
|
// In case of a homepage attribution, we want to show the title as "Homepage" on email
|
|
|
|
if (attributionTitle === 'homepage') {
|
|
|
|
attributionTitle = 'Homepage';
|
|
|
|
}
|
|
|
|
|
2022-08-25 10:25:36 +03:00
|
|
|
const templateData = {
|
|
|
|
memberData,
|
2023-03-10 17:44:53 +03:00
|
|
|
attributionTitle,
|
|
|
|
attributionUrl: attribution?.url || '',
|
2023-03-06 12:36:47 +03:00
|
|
|
referrerSource: attribution?.referrerSource,
|
2022-08-25 10:25:36 +03:00
|
|
|
tierData,
|
|
|
|
offerData,
|
|
|
|
subscriptionData,
|
|
|
|
siteTitle: this.settingsCache.get('title'),
|
|
|
|
siteUrl: this.urlUtils.getSiteUrl(),
|
|
|
|
siteDomain: this.siteDomain,
|
|
|
|
accentColor: this.settingsCache.get('accent_color'),
|
|
|
|
fromEmail: this.fromEmailAddress,
|
|
|
|
toEmail: to,
|
|
|
|
staffUrl: this.urlUtils.urlJoin(this.urlUtils.urlFor('admin', true), '#', `/settings/staff/${user.slug}`)
|
|
|
|
};
|
|
|
|
|
|
|
|
const {html, text} = await this.renderEmailTemplate('new-paid-started', templateData);
|
|
|
|
|
|
|
|
await this.sendMail({
|
|
|
|
to,
|
|
|
|
subject,
|
|
|
|
html,
|
|
|
|
text
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-09 17:23:43 +03:00
|
|
|
async notifyPaidSubscriptionCanceled({member, tier, subscription}, options = {}) {
|
2022-08-25 10:25:36 +03:00
|
|
|
const users = await this.models.User.getEmailAlertUsers('paid-canceled', options);
|
2022-09-09 17:23:43 +03:00
|
|
|
|
2022-08-25 10:25:36 +03:00
|
|
|
for (const user of users) {
|
|
|
|
const to = user.email;
|
|
|
|
const memberData = this.getMemberData(member);
|
2022-08-25 22:49:55 +03:00
|
|
|
const subject = `⚠️ Cancellation: ${memberData.name}`;
|
2022-08-25 10:25:36 +03:00
|
|
|
|
2022-09-09 17:23:43 +03:00
|
|
|
const amount = this.getAmount(subscription?.amount);
|
|
|
|
const formattedAmount = this.getFormattedAmount({currency: subscription?.currency, amount});
|
|
|
|
const interval = subscription?.interval;
|
2022-08-25 10:25:36 +03:00
|
|
|
const tierDetail = `${formattedAmount}/${interval}`;
|
|
|
|
const tierData = {
|
|
|
|
name: tier?.name || '',
|
|
|
|
details: tierDetail
|
|
|
|
};
|
|
|
|
|
|
|
|
const subscriptionData = {
|
2022-09-09 17:23:43 +03:00
|
|
|
expiryAt: this.getFormattedDate(subscription.cancelAt),
|
|
|
|
canceledAt: this.getFormattedDate(subscription.canceledAt),
|
|
|
|
cancellationReason: subscription.cancellationReason || ''
|
2022-08-25 10:25:36 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
const templateData = {
|
|
|
|
memberData,
|
|
|
|
tierData,
|
|
|
|
subscriptionData,
|
|
|
|
siteTitle: this.settingsCache.get('title'),
|
|
|
|
siteUrl: this.urlUtils.getSiteUrl(),
|
|
|
|
siteDomain: this.siteDomain,
|
|
|
|
accentColor: this.settingsCache.get('accent_color'),
|
|
|
|
fromEmail: this.fromEmailAddress,
|
|
|
|
toEmail: to,
|
|
|
|
staffUrl: this.urlUtils.urlJoin(this.urlUtils.urlFor('admin', true), '#', `/settings/staff/${user.slug}`)
|
|
|
|
};
|
|
|
|
|
|
|
|
const {html, text} = await this.renderEmailTemplate('new-paid-cancellation', templateData);
|
|
|
|
|
|
|
|
await this.sendMail({
|
|
|
|
to,
|
|
|
|
subject,
|
|
|
|
html,
|
|
|
|
text
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-12 19:11:45 +03:00
|
|
|
/**
|
|
|
|
* @param {object} recipient
|
|
|
|
* @param {string} recipient.email
|
|
|
|
* @param {string} recipient.slug
|
|
|
|
*/
|
|
|
|
async getSharedData(recipient) {
|
|
|
|
return {
|
|
|
|
siteTitle: this.settingsCache.get('title'),
|
|
|
|
siteUrl: this.urlUtils.getSiteUrl(),
|
|
|
|
siteDomain: this.siteDomain,
|
|
|
|
accentColor: this.settingsCache.get('accent_color'),
|
|
|
|
fromEmail: this.fromEmailAddress,
|
|
|
|
toEmail: recipient.email,
|
|
|
|
staffUrl: this.urlUtils.urlJoin(this.urlUtils.urlFor('admin', true), '#', `/settings/staff/${recipient.slug}`)
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2023-02-23 12:20:13 +03:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {object} eventData
|
|
|
|
* @param {object} eventData.milestone
|
|
|
|
*
|
|
|
|
* @returns {Promise<void>}
|
|
|
|
*/
|
|
|
|
async notifyMilestoneReceived({milestone}) {
|
2023-03-21 16:39:40 +03:00
|
|
|
if (!milestone?.emailSentAt || milestone?.meta?.reason) {
|
|
|
|
// Do not send an email when no email was set to be sent or a reason
|
|
|
|
// not to send provided
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const formattedValue = this.getFormattedAmount({currency: milestone?.currency, amount: milestone.value, maximumFractionDigits: 0});
|
|
|
|
const milestoneEmailConfig = require('./milestone-email-config')(this.settingsCache.get('title'), formattedValue);
|
|
|
|
|
|
|
|
const emailData = milestoneEmailConfig?.[milestone.type]?.[milestone.value];
|
|
|
|
|
|
|
|
if (!emailData || Object.keys(emailData).length === 0) {
|
|
|
|
// Do not attempt to send an email with invalid or missing data
|
|
|
|
this.logging.warn('No Milestone email sent. Invalid or missing data.');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const emailPromises = [];
|
2023-02-23 12:20:13 +03:00
|
|
|
const users = await this.models.User.getEmailAlertUsers('milestone-received');
|
|
|
|
|
|
|
|
for (const user of users) {
|
|
|
|
const to = user.email;
|
|
|
|
|
2023-03-21 16:39:40 +03:00
|
|
|
const templateData = {
|
|
|
|
siteTitle: this.settingsCache.get('title'),
|
|
|
|
siteUrl: this.urlUtils.getSiteUrl(),
|
|
|
|
siteDomain: this.siteDomain,
|
|
|
|
fromEmail: this.fromEmailAddress,
|
|
|
|
...emailData,
|
|
|
|
partial: `milestones/${milestone.value}`,
|
|
|
|
toEmail: to,
|
|
|
|
adminUrl: this.urlUtils.urlFor('admin', true),
|
|
|
|
staffUrl: this.urlUtils.urlJoin(this.urlUtils.urlFor('admin', true), '#', `/settings/staff/${user.slug}`)
|
|
|
|
};
|
|
|
|
|
|
|
|
const {html, text} = await this.renderEmailTemplate('new-milestone-received', templateData);
|
|
|
|
|
|
|
|
emailPromises.push(await this.sendMail({
|
|
|
|
to,
|
|
|
|
subject: emailData.subject,
|
|
|
|
html,
|
|
|
|
text
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
const results = await Promise.allSettled(emailPromises);
|
|
|
|
|
|
|
|
for (const result of results) {
|
|
|
|
if (result.status === 'rejected') {
|
|
|
|
this.logging.warn(result?.reason);
|
|
|
|
}
|
2023-02-23 12:20:13 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-25 10:25:36 +03:00
|
|
|
// Utils
|
|
|
|
|
|
|
|
/** @private */
|
|
|
|
getMemberData(member) {
|
2022-09-02 13:56:01 +03:00
|
|
|
let name = member?.name || member?.email;
|
2022-08-25 10:25:36 +03:00
|
|
|
return {
|
2022-09-02 13:56:01 +03:00
|
|
|
name,
|
2022-08-25 18:57:50 +03:00
|
|
|
email: member?.email,
|
2022-09-02 13:56:01 +03:00
|
|
|
showEmail: !!member?.name,
|
2022-08-25 10:25:36 +03:00
|
|
|
adminUrl: this.urlUtils.urlJoin(this.urlUtils.urlFor('admin', true), '#', `/members/${member.id}`),
|
|
|
|
initials: this.extractInitials(name),
|
2022-08-25 21:46:54 +03:00
|
|
|
location: this.getGeolocationData(member.geolocation),
|
2022-08-25 10:25:36 +03:00
|
|
|
createdAt: moment(member.created_at).format('D MMM YYYY')
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-08-25 21:46:54 +03:00
|
|
|
/** @private */
|
|
|
|
getGeolocationData(geolocation) {
|
|
|
|
if (!geolocation) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const geolocationData = JSON.parse(geolocation);
|
|
|
|
return geolocationData?.country || null;
|
|
|
|
} catch (e) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-25 10:25:36 +03:00
|
|
|
/** @private */
|
2023-03-21 16:39:40 +03:00
|
|
|
getFormattedAmount({amount = 0, currency, maximumFractionDigits = 2}) {
|
2022-08-25 10:25:36 +03:00
|
|
|
if (!currency) {
|
2023-03-21 16:39:40 +03:00
|
|
|
return amount > 0 ? Intl.NumberFormat('en', {maximumFractionDigits}).format(amount) : '';
|
2022-08-25 10:25:36 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return Intl.NumberFormat('en', {
|
|
|
|
style: 'currency',
|
|
|
|
currency,
|
2023-03-21 16:39:40 +03:00
|
|
|
currencyDisplay: 'symbol',
|
|
|
|
maximumFractionDigits,
|
|
|
|
// see https://github.com/andyearnshaw/Intl.js/issues/123
|
|
|
|
minimumFractionDigits: maximumFractionDigits
|
2022-08-25 10:25:36 +03:00
|
|
|
}).format(amount);
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @private */
|
|
|
|
getAmount(amount) {
|
|
|
|
if (!amount) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return amount / 100;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @private */
|
|
|
|
getFormattedDate(date) {
|
|
|
|
if (!date) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
return moment(date).format('D MMM YYYY');
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @private */
|
|
|
|
getOfferData(offer) {
|
|
|
|
if (offer) {
|
|
|
|
let offAmount = '';
|
|
|
|
let offDuration = '';
|
|
|
|
|
|
|
|
if (offer.duration === 'once') {
|
|
|
|
offDuration = ', first payment';
|
|
|
|
} else if (offer.duration === 'repeating') {
|
2022-09-09 17:23:43 +03:00
|
|
|
offDuration = `, first ${offer.durationInMonths} months`;
|
2022-08-25 10:25:36 +03:00
|
|
|
} else if (offer.duration === 'forever') {
|
|
|
|
offDuration = `, forever`;
|
|
|
|
} else if (offer.duration === 'trial') {
|
|
|
|
offDuration = '';
|
|
|
|
}
|
|
|
|
if (offer.type === 'percent') {
|
|
|
|
offAmount = `${offer.amount}% off`;
|
|
|
|
} else if (offer.type === 'fixed') {
|
2022-09-05 20:43:40 +03:00
|
|
|
const amount = this.getAmount(offer.amount);
|
|
|
|
offAmount = `${this.getFormattedAmount({currency: offer.currency, amount})} off`;
|
2022-08-25 10:25:36 +03:00
|
|
|
} else if (offer.type === 'trial') {
|
|
|
|
offAmount = `${offer.amount} days free`;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
name: offer.name,
|
|
|
|
details: `${offAmount}${offDuration}`
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
get siteDomain() {
|
|
|
|
const [, siteDomain] = this.urlUtils.getSiteUrl()
|
|
|
|
.match(new RegExp('^https?://([^/:?#]+)(?:[/:?#]|$)', 'i'));
|
|
|
|
|
|
|
|
return siteDomain;
|
|
|
|
}
|
|
|
|
|
2022-09-02 17:57:59 +03:00
|
|
|
get defaultEmailDomain() {
|
|
|
|
return this.settingsHelpers.getDefaultEmailDomain();
|
|
|
|
}
|
|
|
|
|
2022-08-25 10:25:36 +03:00
|
|
|
get membersAddress() {
|
|
|
|
// TODO: get from address of default newsletter?
|
2022-09-02 17:57:59 +03:00
|
|
|
return `noreply@${this.defaultEmailDomain}`;
|
2022-08-25 10:25:36 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
get fromEmailAddress() {
|
2022-09-02 17:57:59 +03:00
|
|
|
return `ghost@${this.defaultEmailDomain}`;
|
2022-08-25 10:25:36 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
extractInitials(name = '') {
|
|
|
|
const names = name.split(' ');
|
|
|
|
const initials = names.length > 1 ? [names[0][0], names[names.length - 1][0]] : [names[0][0]];
|
|
|
|
return initials.join('').toUpperCase();
|
|
|
|
}
|
|
|
|
|
|
|
|
async sendMail(message) {
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
this.logging.warn(message.text);
|
|
|
|
}
|
|
|
|
|
|
|
|
let msg = Object.assign({
|
|
|
|
from: this.fromEmailAddress,
|
|
|
|
forceTextContent: true
|
|
|
|
}, message);
|
|
|
|
|
|
|
|
return this.mailer.send(msg);
|
|
|
|
}
|
|
|
|
|
2022-10-07 13:31:05 +03:00
|
|
|
registerPartials() {
|
|
|
|
const rootDirname = './email-templates/partials/';
|
|
|
|
const files = glob.sync('*.hbs', {cwd: path.join(__dirname, rootDirname)});
|
|
|
|
files.forEach((fileName) => {
|
|
|
|
const name = fileName.replace(/.hbs$/, '');
|
|
|
|
const filePath = path.join(__dirname, rootDirname, `${name}.hbs`);
|
|
|
|
const content = readFileSync(filePath, 'utf8');
|
|
|
|
this.Handlebars.registerPartial(name, content);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-03-12 19:11:45 +03:00
|
|
|
async renderHTML(templateName, data) {
|
2022-08-25 10:25:36 +03:00
|
|
|
const htmlTemplateSource = await fs.readFile(path.join(__dirname, './email-templates/', `${templateName}.hbs`), 'utf8');
|
|
|
|
const htmlTemplate = this.Handlebars.compile(Buffer.from(htmlTemplateSource).toString());
|
2023-03-12 19:11:45 +03:00
|
|
|
|
|
|
|
this.Handlebars.registerHelper('eq', function (arg, value, options) {
|
|
|
|
if (arg === value) {
|
|
|
|
return options.fn(this);
|
|
|
|
} else {
|
|
|
|
return options.inverse(this);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
this.Handlebars.registerHelper('limit', function (array, limit) {
|
|
|
|
if (!Array.isArray(array)) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
return array.slice(0,limit);
|
|
|
|
});
|
|
|
|
|
|
|
|
let sharedData = {};
|
|
|
|
if (data.recipient) {
|
|
|
|
sharedData = await this.getSharedData(data.recipient);
|
|
|
|
}
|
|
|
|
|
|
|
|
return htmlTemplate({
|
|
|
|
...data,
|
|
|
|
...sharedData
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async renderText(templateName, data) {
|
2022-08-25 10:25:36 +03:00
|
|
|
const textTemplate = require(`./email-templates/${templateName}.txt.js`);
|
|
|
|
|
2023-03-12 19:11:45 +03:00
|
|
|
let sharedData = {};
|
|
|
|
if (data.recipient) {
|
|
|
|
sharedData = await this.getSharedData(data.recipient);
|
|
|
|
}
|
|
|
|
|
|
|
|
return textTemplate({
|
|
|
|
...data,
|
|
|
|
...sharedData
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async renderEmailTemplate(templateName, data) {
|
|
|
|
const html = await this.renderHTML(templateName, data);
|
|
|
|
const text = await this.renderText(templateName, data);
|
2022-08-25 10:25:36 +03:00
|
|
|
|
|
|
|
return {html, text};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = StaffServiceEmails;
|