Mailer mail.send() and mail.sendWithTemplate()

This commit is contained in:
Joan Sanchez 2017-08-30 14:50:46 +02:00
parent ef2e80cbad
commit 22b5e2e8bf
7 changed files with 63 additions and 61 deletions

View File

@ -3,12 +3,12 @@ let settings = require('./settings.js');
module.exports = {
/**
* Variable de instancia del pool
* Pool instance
*/
pool: null,
/**
* Iniciar pool de conexión con la base de datos
* Start database pool
*/
init: function() {
this.pool = mysql.createPool(settings.mysql());
@ -21,6 +21,10 @@ module.exports = {
}
});
},
/**
* Set test environment mail.
*/
testEmail: function() {
this.pool.query('SELECT fakeEmail as email FROM vn.config', function(error, qryRs) {
settings.testEmail = qryRs[0].email;

View File

@ -1,14 +1,14 @@
var nodemailer = require('nodemailer');
var settings = require('./settings.js');
var template = require('./template.js');
/**
* Módulo para el envío de emails
* Mail module
*/
module.exports = {
transporter: null,
/**
* Si todavía no está inicializada la configuración,
* carga el fichero de configuración.
* Load mail settings.
*/
init: function() {
this.transporter = nodemailer.createTransport(settings.smtp());
@ -23,8 +23,12 @@ module.exports = {
},
/**
* Envia un email con los datos recibidos desde un vector.
* @param {Object} data - Datos para el envío del email
* Send email.
* @param {Object} recipient - Mail destinatary
* @param {String} subject - Subject
* @param {String} body - Mail body
* @param {Object} attachments - Mail attachments
* @param {Object} cb - Callback
*/
send: function(recipient, subject, body, attachments, cb) {
let mailOptions = {
@ -35,17 +39,31 @@ module.exports = {
attachments
};
if (process.env.NODE_ENV !== 'production'){
if (process.env.NODE_ENV !== 'production') {
mailOptions.to = settings.testEmail;
}
this.transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return cb(null, 'Email not sent: ' + error);
return cb({status: 'REJECT', data: {message: 'Email not sent: ' + error}});
} else if (settings.app().debug) {
console.log('Mail sent ' + info.messageId + ' [' + info.response + ']');
cb();
}
cb({status: 'ACCEPT', data: {message: 'Email sent'}});
});
},
/**
* Send email with template.
* @param {String} tplName - Template name
* @param {Object} params - Params object
* @param {Object} cb - Callback
*/
sendWithTemplate: function(tplName, params, cb) {
template.get(tplName, params, data => {
this.send(data.recipient, data.subject, data.body, data.attachments, result => {
cb(result);
});
});
}
};

View File

@ -1,26 +1,11 @@
var express = require('express');
var router = new express.Router();
var mail = require('../mail.js');
var database = require('../database.js');
var template = require('../template.js');
// Escrito de cambios en méto de pago del cliente
router.post('/:userId/payment-update', function(request, response, next) {
database.pool.query('SELECT `e-mail` AS email, LOWER(p.Codigo) AS countryCode FROM Clientes AS c JOIN Paises AS p ON p.id = c.Id_Pais WHERE Id_Cliente = ?', [request.params.userId], function(error, qryRs) {
if (qryRs.length == 0)
return response.json({data: {message: 'Client not found'}});
template.getTemplate('payment-update', qryRs[0].countryCode, {userId: request.params.userId}, function(tplRs, error) {
if (error)
return response.json({data: {message: error}});
mail.send(qryRs[0].email, tplRs.subject, tplRs.body, tplRs.attachments, (mailrs, error) => {
if (error)
return response.json({data: {message: error}});
return response.json({data: {message: 'Mail sent'}});
});
});
router.post('/:userFk/payment-update', function(request, response, next) {
mail.sendWithTemplate('payment-update', {userId: request.params.userFk}, result => {
return response.json(result);
});
});

View File

@ -1,28 +1,12 @@
var express = require('express');
var router = new express.Router();
var mail = require('../mail.js');
var database = require('../database.js');
var template = require('../template.js');
router.get('/:userId/notice', function(request, response) {
database.pool.query('SELECT `e-mail` AS email, LOWER(p.Codigo) AS countryCode FROM Clientes AS c JOIN Paises AS p ON p.id = c.Id_Pais WHERE Id_Cliente = ?', [request.params.userId], function(error, qryRs) {
if (qryRs.length == 0)
return response.json({data: {message: 'Client not found'}});
router.get('/:userFk/noticeUserSend', function(request, response) {
template.getTemplate('notice', qryRs[0].countryCode, {userId: request.params.userId}, function(tplRs, error) {
if (error)
return response.json({data: {message: error}});
});
mail.send(qryRs[0].email, tplRs.subject, tplRs.body, tplRs.attachments, (mailrs, error) => {
if (error)
return response.json({data: {message: error}});
return response.json({data: {message: 'Mail sent'}});
});
});
});
response.send(request.params.userid);
router.get('/:categoryFk/noticeCategorySend', function(request, response) {
});
module.exports = router;

View File

@ -12,7 +12,7 @@ module.exports = {
* @param {Object} params - Datos a reemplazar.
* @param {Object} cb - Callback
*/
getTemplate: function(template, countryCode, params, cb) {
get: function(template, params, cb) {
var templatePath = path.join(__dirname, 'template', `${template}`, `${template}.html`);
var classPath = path.join(__dirname, 'template', `${template}`, `${template}.js`);
var stylePath = path.join(__dirname, 'template', `${template}`, `${template}.css`);
@ -28,7 +28,7 @@ module.exports = {
this.renderStyles(stylePath, body, body => {
var titleSubject = body.match(new RegExp('<title>(.*?)</title>', 'i'))[1];
this.getAttachments(template, body, attachments => {
cb({body: body, subject: titleSubject, attachments: attachments});
cb({recipient: instance.email, subject: titleSubject, body: body, attachments: attachments});
});
});
};
@ -37,9 +37,11 @@ module.exports = {
this.render(templatePath, instance, body => getRenderedStyles(body));
};
locale.load(template, countryCode, (translations, error) => {
instance._ = translations;
instance.getData(params, () => getDataCb());
instance.getData(params, () => {
locale.load(template, instance.countryCode, (translations, error) => {
instance._ = translations;
getDataCb();
});
});
});
},

View File

@ -24,7 +24,7 @@
<p style="text-align: justify">{{_.dear}},</p>
<p style="text-align: justify">{{_.bodyDescription}}</p>
<p style="text-align: justify">
<div>{{_.paymentMethod}}: <strong style="font-size: 16px">{{payMethod}}</strong></div>
<div>{{_.paymentMethod}}: <strong style="font-size: 16px">{{payMethodName}}</strong></div>
{{{paymentDay}}}
</p>
<p style="text-align: justify">{{paymentAdvice}}</p>

View File

@ -4,8 +4,19 @@ var format = require(path.join(__dirname, '../../util/format.js'));
module.exports = class PaymentUpdate {
getData(params, cb) {
let query = `SELECT pm.name AS payMethod, pm.id AS payMethodId, c.vencimiento AS payDay, c.CC AS accountAddress
FROM Clientes AS c JOIN pay_met AS pm ON pm.id = c.pay_met_id WHERE Id_Cliente = ?`;
let query = `SELECT
pm.id payMethodFk,
pm.name payMethodName,
c.dueDay,
c.iban,
LOWER(ct.code) countryCode,
email
FROM
client c
JOIN payMethod pm ON pm.id = c.paymentMethodFk
JOIN country ct ON ct.id = c.countryFk
WHERE
c.id = ?`;
database.pool.query(query, [params.userId], (error, result) => {
Object.assign(this, result[0]);
cb();
@ -13,19 +24,17 @@ module.exports = class PaymentUpdate {
}
get paymentDay() {
if (this.payMethodId != 5) {
return `<div>${this._.paymentDay}: <strong style="font-size: 16px">${this.payDay} ${this._.everyMonth}</strong></div>`;
if (this.payMethodFk != 5) {
return `<div>${this._.paymentDay}: <strong style="font-size: 16px">${this.dueDay} ${this._.everyMonth}</strong></div>`;
}
}
get paymentAdvice() {
switch (this.payMethodId) {
switch (this.payMethodFk) {
case 4:
return `${this._.accountPaymentAdviceBefore} ${format.partialAccountAddress(this.accountAddress)} ${this._.accountPaymentAdviceAfter}`;
return `${this._.accountPaymentAdviceBefore} ${format.partialAccountAddress(this.iban)} ${this._.accountPaymentAdviceAfter}`;
case 5:
return this._.cardPaymentAdvice;
}
}
};