-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathemail.js
More file actions
306 lines (264 loc) · 8.17 KB
/
Copy pathemail.js
File metadata and controls
306 lines (264 loc) · 8.17 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/**
* Email service.
* Compiles emails and pushes to an email web service.
*/
const Promise = require('bluebird');
const Nodemailer = require('nodemailer');
const Mustache = require('mustache');
const dir = require('node-dir');
const path = require('path');
const Juice = require('juice');
const Log = require('../lib/log');
const Config = require('../lib/config');
const Alert = require('../model/alert');
const { meirimStatuses } = require('../constants');
class Email {
/**
* Generate test SMTP service account from ethereal.email
* Only needed if you don't have a real mail account for testing
*/
constructor() {
// create reusable transporter object using the default SMTP transport
const env = process.env.NODE_ENV === 'test' ? 'test.email' : 'email'; // hack, should be fixed
this.config = Config.get(`${env}`);
this.baseUrl = Config.get('general.domain');
this.transporter = Nodemailer.createTransport(this.config.options);
this.templates = {};
}
/**
* Init the class and load the template files.
*/
init () {
const templateDir = `${__dirname}/email/`;
const templates = {};
const contents = [];
let mapper = [];
return new Promise((resolve, reject) => {
dir.readFiles(
templateDir,
{
match: /.mustache$/,
shortName: true
},
(err, content, next) => {
if (err) {
reject(err);
}
contents.push(content);
next();
},
(err, files) => {
if (err) {
reject(err);
}
mapper = files;
resolve();
}
);
}).then(() => {
mapper.map((file, index) => {
const key = file
.split('.')
.shift();
templates[key] = contents[index];
});
for (const key in templates) {
const title = templates[key].match(
/<title[^>]*>((.|[\n\r])*)<\/title>/im
)[1];
const body = templates[key].match(
/<body[^>]*>((.|[\n\r])*)<\/body>/im
)[1];
const html = Mustache.render(templates.wrapper, {
body
});
this.templates[key] = {
title,
body: Juice(html)
};
}
});
}
newSignUp (person) {
const token = person.getActivationToken();
const templateProperties = {
url: `${this.baseUrl}activate/?token=${token}`,
email: person.get('email'),
type: 'signup'
};
// setup email data with unicode symbols
return this.sendWithTemplate(this.templates.newSignUp, templateProperties);
}
newPlanAlert (user, unsentPlan, planStaticMap) {
const alert = new Alert({
id: user.alert_id,
person_id: user.person_id
});
const data = user;
Object.assign(data, unsentPlan.attributes);
if (data.data.DEPOSITING_DATE) {
const dates = data.data.DEPOSITING_DATE.split('T');
data.data.DEPOSITING_DATE = dates[0];
}
data.unsubscribeLink =
`${this.baseUrl}alerts/unsubscribe/${alert.unsubsribeToken()}`;
data.link = `${this.baseUrl}plan/${unsentPlan.get('id')}`;
data.jurisdiction = unsentPlan.get('jurisdiction');
data.isLocalAuthority = data.jurisdiction === 'מקומית';
data.type = 'plan-alert';
data.attachments = [
{
cid: 'planmap',
filename: 'plan_map.png',
content: planStaticMap,
encoding: 'base64'
}
];
return this.sendWithTemplate(this.templates.alert, data);
}
planDepositAlert (user, unsentPlan) {
const data = user;
Object.assign(data, unsentPlan.attributes);
if (data.data.DEPOSITING_DATE) {
const dates = data.data.DEPOSITING_DATE.split('T');
data.data.DEPOSITING_DATE = dates[0];
}
data.link = `${this.baseUrl}plan/${unsentPlan.get('id')}`;
data.jurisdiction = unsentPlan.get('jurisdiction');
data.type = 'plan-alert';
return this.sendWithTemplate(this.templates.planDeposit, data);
}
donePlanAlert (user, unsentPlan, meirimStatus, planStaticMap) {
const alert = new Alert({
id: user.alert_id,
person_id: user.person_id
});
const data = user;
Object.assign(data, unsentPlan.attributes);
if (data.data.DEPOSITING_DATE) {
const dates = data.data.DEPOSITING_DATE.split('T');
data.data.DEPOSITING_DATE = dates[0];
}
if (meirimStatus === meirimStatuses.APPROVED) {
data.data.PLAN_STATE_DESC = 'אושרה';
data.data.PLAN_STATE_LONG = meirimStatuses.APPROVED;
} else {
data.data.PLAN_STATE_DESC = 'בוטלה';
data.data.PLAN_STATE_LONG = meirimStatuses.CANCELLED;
}
data.unsubscribeLink =
`${this.baseUrl}alerts/unsubscribe/${alert.unsubsribeToken()}`;
data.link = `${this.baseUrl}plan/${unsentPlan.get('id')}`;
data.jurisdiction = unsentPlan.get('jurisdiction');
data.isLocalAuthority = data.jurisdiction === 'מקומית';
data.type = 'plan-alert';
data.attachments = [
{
cid: 'planmap',
filename: 'plan_map.png',
content: planStaticMap,
encoding: 'base64'
}
];
return this.sendWithTemplate(this.templates.planDone, data);
}
formatDate(date) {
const d = new Date(date);
return `${(d.getDate() > 9) ? d.getDate() : ('0' + d.getDate())}/${(d.getMonth() > 8) ? (d.getMonth() + 1) : ('0' + (d.getMonth() + 1))}/${d.getFullYear()}`;
}
treeAlert (user, unsentTree, treeStaticMap) {
const alert = new Alert({
id: user.alert_id,
person_id: user.person_id
});
const data = user;
Object.assign(data, unsentTree.attributes);
data.unsubscribeLink = `${this.baseUrl}alerts/unsubscribe/${alert.unsubsribeToken()}`;
data.link = `${this.baseUrl}tree/${unsentTree.get('id')}`;
data.place_text = data.place? `רשיון כריתה חדש ב${data.place}` : 'רשיון כריתה חדש באזורך';
data.address = data.street ? (data.street_number? `${data.street} ${data.street_number}`: `${data.street}`) : 'לא צוינה כתובת';
data.total_trees_text = (data.total_trees === 1)? 'עץ אחד': `${data.total_trees} עצים`;
data.reason_short_text = data.reason_short? data.reason_short : 'לא צוינה סיבה';
data.reason_detailed_text = data.reason_detailed? data.reason_detailed : 'לא צוין פירוט הסיבה';
data.start_date_text = this.formatDate(data.start_date);
data.hasMap = Boolean(treeStaticMap);
data.type = 'tree-alert';
if (treeStaticMap) {
data.attachments = [
{
cid: 'planmap',
filename: 'plan_map.png',
content: treeStaticMap,
encoding: 'base64'
}
];
}
return this.sendWithTemplate(this.templates.treeAlert, data);
}
// digestPlanAlert (user, plans = []) {
// }
newAlertTemplateByType(type){
let alertTemplate = this.templates.newAlert;
if (type === 'tree'){
alertTemplate = this.templates.newTreeAlert;
}
return alertTemplate;
}
newAlert (person, alert) {
const templateProperties = Object.assign({}, person, alert.toJSON());
templateProperties.type = 'new-alert';
const alertTemplate = this.newAlertTemplateByType(alert.attributes.type);
return this.sendWithTemplate(alertTemplate, templateProperties);
}
resetPasswordToken (person) {
const templateProperties = {
email: person.get('email'),
url: `${Config.get(
'general.domain'
)}forgot/?token=${person.resetPasswordToken()}`,
type: 'reset-password'
};
return this.sendWithTemplate(
this.templates.resetPasswordToken,
templateProperties
);
}
sendWithTemplate (template, templateProperties) {
const attachments = templateProperties.attachments
? templateProperties.attachments
: [];
attachments.push({
filename: 'logo_email.png',
path: path.resolve('api/service/email/logo_email.png'),
cid: 'logomeirim'
});
attachments.push({
filename: 'support_us.png',
path: path.resolve('api/service/email/support_us.png'),
cid: 'supportus'
});
const subject = Mustache.render(template.title, templateProperties)
.replace(/\r?\n|\r/g, '')
.replace(/\s\s+/g, ' ');
const email = {
from: `"${this.config.from_name}" <${this.config.from_email}>`, // sender address
to: templateProperties.email, // list of receivers
subject, // Subject line
html: Mustache.render(template.body, templateProperties), // html body
attachments,
encoding: 'utf8',
textEncoding: 'base64'
};
return this.send(email);
}
/**
* send mail with defined transport object
* @param {*} mailOptions
*/
send (mailOptions) {
return this.transporter
.sendMail(mailOptions)
.then(info => Log.info('Message sent: %s', info.messageId, mailOptions.to));
}
}
module.exports = new Email();