From 609c13efbf9ec856350ec83b03a3143d23ee84ce Mon Sep 17 00:00:00 2001 From: Joan Date: Tue, 30 May 2017 08:06:14 +0200 Subject: [PATCH 1/2] Service mailer --- services/mailer/.gitignore | 1 + .../mailer/Application/Route/manuscript.js | 30 ++++++++++++ .../mailer/Application/Route/notification.js | 8 ++++ .../Application/Template/paymentUpdate.html | 35 ++++++++++++++ services/mailer/Application/Util/system.js | 11 +++++ services/mailer/Application/Util/terminal.js | 13 +++++ services/mailer/Application/database.js | 26 ++++++++++ services/mailer/Application/language.js | 0 services/mailer/Application/logger.js | 28 +++++++++++ services/mailer/Application/mail.js | 48 +++++++++++++++++++ services/mailer/Application/router.js | 16 +++++++ services/mailer/Application/settings.js | 2 + services/mailer/Application/template.js | 48 +++++++++++++++++++ services/mailer/package.json | 13 +++++ services/mailer/server.js | 38 +++++++++++++++ 15 files changed, 317 insertions(+) create mode 100644 services/mailer/.gitignore create mode 100644 services/mailer/Application/Route/manuscript.js create mode 100644 services/mailer/Application/Route/notification.js create mode 100644 services/mailer/Application/Template/paymentUpdate.html create mode 100644 services/mailer/Application/Util/system.js create mode 100644 services/mailer/Application/Util/terminal.js create mode 100644 services/mailer/Application/database.js create mode 100644 services/mailer/Application/language.js create mode 100644 services/mailer/Application/logger.js create mode 100644 services/mailer/Application/mail.js create mode 100644 services/mailer/Application/router.js create mode 100644 services/mailer/Application/settings.js create mode 100644 services/mailer/Application/template.js create mode 100644 services/mailer/package.json create mode 100644 services/mailer/server.js diff --git a/services/mailer/.gitignore b/services/mailer/.gitignore new file mode 100644 index 0000000000..b512c09d47 --- /dev/null +++ b/services/mailer/.gitignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/services/mailer/Application/Route/manuscript.js b/services/mailer/Application/Route/manuscript.js new file mode 100644 index 0000000000..a229fd499d --- /dev/null +++ b/services/mailer/Application/Route/manuscript.js @@ -0,0 +1,30 @@ +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('/paymentUpdate', function(request, response) { + database.pool.query('SELECT Cliente, `e-mail` AS email FROM Clientes WHERE Id_Cliente = ?', [request.body.user], function(error, rs) { + var params = { + clientName: rs[0].Cliente + }; + + template.getTemplate('paymentUpdate', params, function(body) { + var data = { + recipient: rs[0].email, + subject: 'Cambios en las condiciones de pago', + body: body + }; + + if (mail.send(data)) { + response.json({status: "OK"}); + } else { + response.json({status: "ERROR"}); + } + }); + }); +}); + +module.exports = router; diff --git a/services/mailer/Application/Route/notification.js b/services/mailer/Application/Route/notification.js new file mode 100644 index 0000000000..5ec515dd1a --- /dev/null +++ b/services/mailer/Application/Route/notification.js @@ -0,0 +1,8 @@ +var express = require('express'); +var router = new express.Router(); + +router.get('/test', function(request, response) { + response.send("test"); +}); + +module.exports = router; diff --git a/services/mailer/Application/Template/paymentUpdate.html b/services/mailer/Application/Template/paymentUpdate.html new file mode 100644 index 0000000000..203db80478 --- /dev/null +++ b/services/mailer/Application/Template/paymentUpdate.html @@ -0,0 +1,35 @@ +
+
+ +
+ Verdnatura Levante SL, B97367486 + Avda. Espioca 100, 46460 Silla (Valencia) +
+
+
+
+

CAMBIOS EN CONDICIONES DE PAGO

+
+ +

+ Estimado cliente {{clientName}} +

+ +

+ Se han cambiado las condiciones de pago, estas son las nuevas: + +

+
+
+

Este mensaje es privado y confidencial, y debe ser utilizado exclusivamente por la persona destinataria del mismo. + Si usted ha recibido este mensaje por error, le rogamos lo comunique al remitente y borre dicho mensaje y cualquier + documento adjunto que pudiera contener. Verdnatura Levante SL no renuncia a la confidencialidad ni a ningún privilegio + por causa de transmisión errónea o mal funcionamiento. Igualmente no se hace responsable de los cambios, alteraciones, + errores u omisiones que pudieran hacerse al mensaje una vez enviado.

+ +

En cumplimiento de lo dispuesto en la Ley Orgánica 15/1999, de Protección de Datos de Carácter Personal, le comunicamos + que los datos personales que facilite se incluirán en ficheros automatizados de VERDNATURA LEVANTE S.L., pudiendo en todo momento + ejercitar los derechos de acceso, rectificación, cancelación y oposición, comunicándolo por escrito al domicilio social de la entidad. + La finalidad del fichero es la gestión administrativa, contabilidad, y facturación.

+
+
\ No newline at end of file diff --git a/services/mailer/Application/Util/system.js b/services/mailer/Application/Util/system.js new file mode 100644 index 0000000000..08092ad5c0 --- /dev/null +++ b/services/mailer/Application/Util/system.js @@ -0,0 +1,11 @@ +module.exports = { + + /** + * Obtiene las variables de entorno + * @param {String} env - Nombre de la variable de entorno + * @return {String} Valor de la variable de entorno + */ + getEnv: function(env) { + return process.env[env]; + } +}; diff --git a/services/mailer/Application/Util/terminal.js b/services/mailer/Application/Util/terminal.js new file mode 100644 index 0000000000..d897671e7a --- /dev/null +++ b/services/mailer/Application/Util/terminal.js @@ -0,0 +1,13 @@ +var Settings = require('../Settings.js'); + +module.exports = { + + /** + * Imprimir cabecera + */ + printHeader: function() { + console.log('##########################################################'); + console.log('## ' + Settings.name + ' ##'); + console.log('##########################################################'); + } +}; diff --git a/services/mailer/Application/database.js b/services/mailer/Application/database.js new file mode 100644 index 0000000000..979867a330 --- /dev/null +++ b/services/mailer/Application/database.js @@ -0,0 +1,26 @@ +var mysql = require('mysql'); +var settings = require('./Settings.js'); +var logger = require('./Logger.js'); + +module.exports = { + + /** + * Variable de instancia del pool + */ + pool: null, + + /** + * Iniciar pool de conexión con la base de datos + */ + init: function() { + this.pool = mysql.createPool(settings.mysql); + + this.pool.getConnection(function(error, connection) { + if (error) { + logger.print(__LOG_ERROR, 'No se ha podido establecer la conexión con la base de datos. ' + error.code); + } else { + logger.print(__LOG_INFO, 'Conexión con la base de datos establecida'); + } + }); + } +}; diff --git a/services/mailer/Application/language.js b/services/mailer/Application/language.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/services/mailer/Application/logger.js b/services/mailer/Application/logger.js new file mode 100644 index 0000000000..c7442c33f4 --- /dev/null +++ b/services/mailer/Application/logger.js @@ -0,0 +1,28 @@ + +// Tipos de advertencias +global.__LOG_INFO = 1; +global.__LOG_WARNING = 2; +global.__LOG_ERROR = 3; + +module.exports = { + + /** + * Imprimir advertencia directamente en consola + * @param {Integer} type - Constante tipo de advertencia + */ + print: function(type, message) + { + if (type == __LOG_INFO) + { + console.log('[INFORMACIÓN] -> ' + message); + } + else if(type == __LOG_WARNING) + { + console.log('[ADVERTENCIA] -> ' + message); + } + else if(type == __LOG_ERROR) + { + console.log('[ERROR] -> ' + message); + } + } +} \ No newline at end of file diff --git a/services/mailer/Application/mail.js b/services/mailer/Application/mail.js new file mode 100644 index 0000000000..3390425fe0 --- /dev/null +++ b/services/mailer/Application/mail.js @@ -0,0 +1,48 @@ +var nodemailer = require('nodemailer'); +var settings = require('./Settings.js'); +var logger = require('./Logger.js'); + +// Módulo para el envío de emails +module.exports = { + + transporter: null, + + /** + * Si todavía no está inicializada la configuración, + * carga el fichero de configuración. + */ + init: function() { + this.transporter = nodemailer.createTransport(settings.smtp); + + this.transporter.verify(function(error, success) { + if (error) { + logger.print(__LOG_ERROR, error); + } else { + logger.print(__LOG_INFO, 'Conexión SMTP establecida'); + } + }); + }, + +/** + * Envia un email con los datos recibidos desde un vector. + * @param {Object} data - Datos para el envío del email + */ + send: function(data) { + let mailOptions = { + from: '"' + settings.senderName + '" <' + settings.senderMail + '>', + to: data.recipient, + subject: data.subject, + html: data.body + }; + + this.transporter.sendMail(mailOptions, (error, info) => { + if (error) { + logger.print(__LOG_ERROR, error); + } else if (Settings.debug) { + logger.print(__LOG_INFO, 'Se ha enviado el email ' + info.messageId + ' [' + info.response + ']'); + + return true; + } + }); + }, +} \ No newline at end of file diff --git a/services/mailer/Application/router.js b/services/mailer/Application/router.js new file mode 100644 index 0000000000..6bc5e60bfa --- /dev/null +++ b/services/mailer/Application/router.js @@ -0,0 +1,16 @@ +var express = require('express'); +var router = new express.Router(); +var settings = require('./settings.js'); + +// Página por defecto +router.get('/', function(request, response) { + response.send(Settings.name + ' v' + settings.version); +}); + +// Rutas de los escritos. +router.use('/manuscript', require('./Route/Manuscript.js')); + +// Rutas de las notificaciones. +router.use('/notification', require('./Route/Notification.js')); + +module.exports = router; diff --git a/services/mailer/Application/settings.js b/services/mailer/Application/settings.js new file mode 100644 index 0000000000..f2a22d5d3e --- /dev/null +++ b/services/mailer/Application/settings.js @@ -0,0 +1,2 @@ +// Módulo de configuración +module.exports = require('./config.json'); diff --git a/services/mailer/Application/template.js b/services/mailer/Application/template.js new file mode 100644 index 0000000000..3424c0dd26 --- /dev/null +++ b/services/mailer/Application/template.js @@ -0,0 +1,48 @@ +var fs = require('fs'); +var mustache = require('mustache'); +var database = require('./database.js'); +var logger = require('./logger.js'); + +var Template = { + + /** + * Obtiene la plantilla + * @param {String} name - Nombre de la plantilla + * @param {Object} params - Datos a reemplazar. + * @param {Object} callback - Callback + */ + getTemplate: function(name, params, callback) { + database.pool.query('SELECT name, attachmentPath FROM vn.mailTemplates WHERE name = ?', [name], function(error, rs) + { + if (rs.length == 0) { + logger.print(__LOG_ERROR, 'La plantilla ' + name + ' no existe'); + return; + } + + var path = './Application/Template/' + rs[0].name + '.html'; + + if (!fs.existsSync(path)) { + logger.print(__LOG_ERROR, 'No se ha podido cargar la plantilla ' + name + '.html'); + } else { + Template.render(path, params, function(body) { + callback(body); + }); + } + }); + }, + + /** + * Renderiza las plantillas + * @param {String} path - Ruta de la plantilla + * @param {Object} params - Listado de parámetros a remplazar + * @param {Object} callback - Callback + */ + render: function(path, params, callback) { + fs.readFile(path, 'utf8', function(error, body) { + mustache.parse(body); + callback(mustache.render(body, params)); + }); + } +}; + +module.exports = Template; diff --git a/services/mailer/package.json b/services/mailer/package.json new file mode 100644 index 0000000000..c78bfc567a --- /dev/null +++ b/services/mailer/package.json @@ -0,0 +1,13 @@ +{ + "name": "MailServer", + "version": "0.0.1", + "description": "Servidor de envío de correos", + "main": "server.js", + "dependencies": { + "mysql": "^2.13.0", + "express": "^4.15.3", + "body-parser": "^1.17.2", + "nodemailer": "^4.0.1", + "mustache": "^2.3.0" + } +} \ No newline at end of file diff --git a/services/mailer/server.js b/services/mailer/server.js new file mode 100644 index 0000000000..aa7da128c8 --- /dev/null +++ b/services/mailer/server.js @@ -0,0 +1,38 @@ +/** + * Módulos necesarios + */ +var express = require('express'); +var app = express(); +var bodyParser = require('body-parser'); + +var settings = require('./Application/settings.js'); +var mail = require('./Application/mail.js'); +var logger = require('./Application/logger.js'); +var database = require('./Application/database.js'); +var terminal = require('./Application/Util/terminal.js'); + +// Middleware +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({extended: true})); + +// Cargar rutas +app.use('/', require('./Application/router.js')); + +// Iniciar escucha del servidor +app.listen(settings.port, function() { + // Imprimir cabecera + terminal.printHeader(); + + // Escucha SMTP + mail.init(); + + // Iniciar base de datos + database.init(); + + logger.print(__LOG_INFO, 'Servidor de correo iniciado en el puerto ' + settings.port); + + if (settings.debug) { + logger.print(__LOG_WARNING, 'El modo debug está activado'); + } +}); + From 65cc23b2806060064c1bed6984f76fa0c95ec0f8 Mon Sep 17 00:00:00 2001 From: Vicente Falco Date: Tue, 30 May 2017 08:50:16 +0200 Subject: [PATCH 2/2] gulp services y service mailer --- gulpfile.js | 2 ++ services/mailer/package.json | 24 ++++++++++++------------ services/mailer/server.js | 31 +++++++++++++++---------------- 3 files changed, 29 insertions(+), 28 deletions(-) diff --git a/gulpfile.js b/gulpfile.js index 5b2b0823c1..540c05d6e5 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -158,8 +158,10 @@ gulp.task('services', function() { var auth = require('./services/auth/server/server.js'); var client = require('./services/client/server/server.js'); var server = require('./services/salix/server/server.js'); + var mailer = require('./services/mailer/server.js'); auth.start(); client.start(); server.start(); + mailer.start(); }); diff --git a/services/mailer/package.json b/services/mailer/package.json index c78bfc567a..87aced84ea 100644 --- a/services/mailer/package.json +++ b/services/mailer/package.json @@ -1,13 +1,13 @@ { - "name": "MailServer", - "version": "0.0.1", - "description": "Servidor de envío de correos", - "main": "server.js", - "dependencies": { - "mysql": "^2.13.0", - "express": "^4.15.3", - "body-parser": "^1.17.2", - "nodemailer": "^4.0.1", - "mustache": "^2.3.0" - } -} \ No newline at end of file + "name": "MailServer", + "version": "0.0.1", + "description": "Servidor de envío de correos", + "main": "server.js", + "dependencies": { + "body-parser": "^1.17.2", + "express": "^4.15.3", + "mustache": "^2.3.0", + "mysql": "^2.13.0", + "nodemailer": "^4.0.1" + } +} diff --git a/services/mailer/server.js b/services/mailer/server.js index aa7da128c8..448c9b922f 100644 --- a/services/mailer/server.js +++ b/services/mailer/server.js @@ -2,7 +2,7 @@ * Módulos necesarios */ var express = require('express'); -var app = express(); +var app = module.exports = express(); var bodyParser = require('body-parser'); var settings = require('./Application/settings.js'); @@ -18,21 +18,20 @@ app.use(bodyParser.urlencoded({extended: true})); // Cargar rutas app.use('/', require('./Application/router.js')); -// Iniciar escucha del servidor -app.listen(settings.port, function() { - // Imprimir cabecera - terminal.printHeader(); - // Escucha SMTP - mail.init(); +app.start = function() { + return app.listen(settings.port, function() { + terminal.printHeader(); + mail.init(); + database.init(); + logger.print(__LOG_INFO, 'Servidor de correo iniciado en el puerto ' + settings.port); + if (settings.debug) { + logger.print(__LOG_WARNING, 'El modo debug está activado'); + } + }); +}; - // Iniciar base de datos - database.init(); - - logger.print(__LOG_INFO, 'Servidor de correo iniciado en el puerto ' + settings.port); - - if (settings.debug) { - logger.print(__LOG_WARNING, 'El modo debug está activado'); - } -}); +if (require.main === module) { + app.start(); +}