Transactional mail: use tools to format message

This commit is contained in:
Alexey Zinkevych 2019-04-02 16:15:35 +03:00
parent 76b4f8b8c2
commit e588e218b6
2 changed files with 18 additions and 17 deletions

View file

@ -1,6 +1,7 @@
'use strict';
const mailers = require('./mailers');
const tools = require('./tools');
const templates = require('../models/templates');
class TemplateSender {
@ -21,11 +22,13 @@ class TemplateSender {
templates.getById(options.context, this.templateId, false)
]);
const html = this._substituteVariables(
const html = tools.formatTemplate(
template.html,
options.variables
null,
options.variables,
true
);
const subject = this._substituteVariables(
const subject = tools.formatTemplate(
options.subject || template.description || template.name,
options.variables
);
@ -63,17 +66,6 @@ class TemplateSender {
throw new Error('Missing locale');
}
}
_substituteVariables(html, variables) {
if (!variables) {
return html;
}
return Object.keys(variables).reduce(
(res, key) =>
res.replace(new RegExp(`\\[${key}\\]`, 'gmi'), variables[key]),
html
);
}
}
module.exports = TemplateSender;

View file

@ -14,6 +14,7 @@ const mjml2html = require('mjml');
const hbs = require('hbs');
const juice = require('juice');
const he = require('he');
const htmlToText = require('html-to-text');
const fs = require('fs-extra');
@ -148,14 +149,21 @@ function validateEmailGetMessage(result, address, language) {
function formatMessage(campaign, list, subscription, mergeTags, message, isHTML) {
const links = getMessageLinks(campaign, list, subscription);
return formatTemplate(message, links, mergeTags, isHTML);
}
function formatTemplate(template, links, mergeTags, isHTML) {
if (!links && !mergeTags) { return template; }
const getValue = fullKey => {
const keys = (fullKey || '').split('.');
if (links.hasOwnProperty(keys[0])) {
if (links && links.hasOwnProperty(keys[0])) {
return links[keys[0]];
}
if (!mergeTags) { return false; }
let value = mergeTags;
while (keys.length > 0) {
let key = keys.shift();
@ -173,7 +181,7 @@ function formatMessage(campaign, list, subscription, mergeTags, message, isHTML)
}) : (containsHTML ? htmlToText.fromString(value) : value);
};
return message.replace(/\[([a-z0-9_.]+)(?:\/([^\]]+))?\]/ig, (match, identifier, fallback) => {
return template.replace(/\[([a-z0-9_.]+)(?:\/([^\]]+))?\]/ig, (match, identifier, fallback) => {
let value = getValue(identifier);
if (value === false) {
return match;
@ -229,6 +237,7 @@ module.exports = {
getTemplate,
prepareHtml,
getMessageLinks,
formatMessage
formatMessage,
formatTemplate
};