This repository has been archived by the owner on Dec 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
email-notifications.js
86 lines (76 loc) · 2.61 KB
/
email-notifications.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
var fs = require('fs');
var _ = require('lodash');
var CpTranslations = require('cp-translations');
var I18NHelper = require('cp-i18n-lib');
module.exports = function (options) {
var seneca = this;
var plugin = 'email-notifications';
var { logger } = options;
var so = seneca.options();
options = seneca.util.deepextend({}, so[plugin], options);
seneca.add({role: plugin, cmd: 'send'}, send_notification);
function send_notification (args, done) {
var subject = args.subject;
var bypassTranslation = args.bypassTranslation;
var subjectVariables = args.subjectVariables || [];
var subjectTranslation;
var emailCode;
var locale = args.locality;
var code = args.code;
var i18nHelper = new I18NHelper({
poFilePath: CpTranslations.getPoFilePath(),
poFileName: 'messages.po',
domain: 'coder-dojo-platform'
});
if (options.sendemail && options.email) {
logger.warn('email-notifications', JSON.stringify(args));
emailCode = code + locale;
if (!fs.existsSync(CpTranslations.getEmailTemplatePath(emailCode))) emailCode = code + 'en_US';
if (!args.to) return done(null, {ok: false, why: 'No recipient set.'});
if (!bypassTranslation) {
subjectTranslation = i18nHelper.getClosestTranslation(locale, subject);
if (subjectTranslation === null) {
logger.warn('email-notifications', JSON.stringify({
ok: false,
why: 'Invalid email subject.',
args
}));
return done(null, {ok: false, why: 'Invalid email subject.'});
}
subject = subjectTranslation.fetch(subjectVariables);
}
seneca.act({
role: 'mail', cmd: 'send',
from: args.from || options.sendFrom,
code: emailCode,
to: args.to,
replyTo: args.replyTo || options.sendFrom,
subject: subject,
content: args.content,
headers: setHeader()
}, done);
} else {
done();
}
/**
* @function : recover the predefined header and append the function name to it
*/
function setHeader () {
var headerContainer = _.cloneDeep(options.email.headers);
if (emailCode) {
var headerKey = _.keys(headerContainer)[0];
if (headerKey) {
var JSONHeaderValue = JSON.parse(headerContainer[headerKey]);
var categoryHeaderKey = _.keys(JSONHeaderValue)[0];
JSONHeaderValue[categoryHeaderKey].push(emailCode);
headerContainer[headerKey] = JSON.stringify(JSONHeaderValue);
}
}
return headerContainer;
}
}
return {
name: plugin
};
};