Merge branch 'dev' of https://git.verdnatura.es/salix into dev

This commit is contained in:
Juan Ferrer Toribio 2017-05-31 16:21:08 +02:00
commit 9b9b460bb8
24 changed files with 196 additions and 89 deletions

View File

@ -1,2 +1,3 @@
node_modules
config.json
mailerMysql.json
mailerSmtp.json

View File

@ -0,0 +1,9 @@
{
"name": "MailServer",
"version": "1.0.0",
"port": 3003,
"debug": true,
"defaultLanguage": "es",
"senderMail": "nocontestar@verdnatura.es",
"senderName": "VerdNatura"
}

View File

@ -0,0 +1,8 @@
{
"subject": "Cambios en las condiciones de pago",
"title": "Cambio en las condiciones",
"dear": "Estimado cliente",
"bodyDescription": "Le enviamos este email para comunicarle que las condiciones de pago han cambiado. Le indicamos las nuevas condiciones a continuación.",
"fiscalAddress": "VERDNATURA LEVANTE SL, B97367486 Avda. Espioca, 100, 46460 Silla _ www.verdnatura.es _ clientes@verdnatura.es",
"privacy": "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."
}

View File

@ -7,18 +7,13 @@ 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) {
// Datos del escrito
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)) {
// Obtener plantilla y enviar
template.getTemplate('paymentUpdate', 'es', params, function(tplResult) {
if (mail.send({recipient: rs[0].email, subject: tplResult.subject, body: tplResult.body})) {
response.json({status: "OK"});
} else {
response.json({status: "ERROR"});

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -1,35 +1,74 @@
<div style="width:600px;font-family:arial,sans-serif;font-size:16px;color:#555;margin:0 auto">
<div style="padding:20px;text-align: center;border-bottom: 1px solid #CCC">
<img class="logo" src="https://verdnatura.es/image/logo.png" style="width:307px;margin-bottom: 5px"/>
<div style="color: #CCC">
<span style="display: block;color:#555;font-size: 10px">Verdnatura Levante SL, B97367486</span>
<span style="display: block;color:#555;font-size: 10px">Avda. Espioca 100, 46460 Silla (Valencia)</span>
</div>
</div>
<div>
<div style="text-align:center">
<h1 style="color: #999;font-size: 34px;margin-top: 35px;margin-bottom: 35px">CAMBIOS EN CONDICIONES DE PAGO</h1>
</div>
<!DOCTYPE html>
<html lang="es">
<head>
<title>{{subject}}</title>
<meta charset="utf8"/>
</head>
<body>
<div style="width: 600px;margin: 0 auto;font-family: arial, sans-serif;font-size: 16px;color: #555">
<!-- Banner block -->
<div style="">
<a href="https://www.verdnatura.es"/><img src="cid:header" alt="VerdNatura" style="margin:0"/></a>
</div>
<!-- Title block -->
<div style="padding: 35px 0;margin:0 10px;background-color: #95d831;text-align: center">
<h1 style="margin: 0;font-size: 32px;color: #333;">{{title}}</h1>
</div>
<!-- Mail body block -->
<p>
Estimado cliente <strong style="font-size: 20px">{{clientName}}</strong>
</p>
<!-- Mail body block -->
<div style="padding: 20px 0;margin:0 10px">
<p style="text-align: justify">{{dear}} <strong style="font-size: 20px">{{clientName}}</strong>,</p>
<p style="text-align: justify">{{bodyDescription}}</p>
<p style="text-align: justify">
Se han cambiado las condiciones de pago, estas son las nuevas:
</p>
</div>
<div style="font-size:10px;font-weight:100;border-top: 1px solid #CCC;margin-top: 35px">
<p style="text-align: justify">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.</p>
<p style="text-align: justify">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.</p>
</div>
</div>
<p style="text-align: justify">??</p>
<p style="text-align: justify">??</p>
</div>
<!-- Mail body block -->
<!-- Action button block -->
<div style="margin:0 10px;text-align: center;background-color: #333;overflow:hidden">
<a href="https://www.verdnatura.es" target="_blank" style="width:50%;display:block;float:left;font-size:16px;font-weight:bold;color:#FFF">
<div style="float:left;padding:35px 20px 20px 20px;text-align:center">Visitar Verdnatura</div>
<div style="float:right;width:80px;background-color:#95d831;padding: 20px 0"><img src="cid:arrow" style="margin:0"/></div>
</a>
<a href="https://goo.gl/forms/j8WSL151ZW6QtlT72" target="_blank" style="width:50%;display:block;float:left;font-size:16px;font-weight:bold;color:#FFF">
<div style="float:left;padding:35px 20px 20px 20px;text-align:center">Ayúdanos a mejorar</div>
<div style="float:right;width:80px;background-color:#95d831;padding: 20px 0"><img src="cid:chat" alt="Encuesta" style="margin:0"/></div>
</a>
</div>
<!-- Action button block -->
<!-- Networks block -->
<div style="padding:20px 0;margin:0 10px;background-color:#555;text-align:center">
<a href="https://www.facebook.com/Verdnatura" target="_blank" style="text-decoration:none;margin-right: 10px">
<img src="cid:facebook" alt="Visita nuestro Facebook" style="width:50px;margin:0"/>
</a>
<a href="https://www.twitter.com/Verdnatura" target="_blank" style="text-decoration:none;margin-right: 10px">
<img src="cid:twitter" alt="Visita nuestro Twitter" style="width:50px;margin:0"/>
</a>
<a href="https://www.youtube.com/Verdnatura" target="_blank" style="text-decoration:none;margin-right: 10px">
<img src="cid:youtube" alt="Visita nuestro canal de Youtube" style="width:50px;margin:0"/>
</a>
<a href="https://www.pinterest.com/Verdnatura" target="_blank" style="text-decoration:none;margin-right: 10px">
<img src="cid:pinterest" alt="Visita nuestro Pinterest" style="width:50px;margin:0"/>
</a>
<a href="https://www.instagram.com/Verdnatura" target="_blank" style="text-decoration:none;margin-right: 10px">
<img src="cid:instagram" alt="Visita nuestro Instagram" style="width:50px;margin:0"/>
</a>
<a href="https://www.linkedin.com/company/verdnatura" target="_blank" style="text-decoration:none;margin-right: 10px">
<img src="cid:linkedin" alt="Visita nuestro Linkedin" style="width:50px;margin:0"/>
</a>
</div>
<!-- Networks block -->
<!-- Privacy block -->
<div style="padding:20px 0;margin:0 10px;font-size:10px;font-weight:100">
<p style="text-align: justify">{{fiscalAddress}}</p>
<p style="text-align: justify">- AVISO - 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.</p>
<p style="text-align: justify">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.</p>
</div>
<!-- Privacy block -->
</div>
</body>
</html>

View File

@ -1,13 +1,4 @@
var Settings = require('../Settings.js');
module.exports = {
/**
* Imprimir cabecera
*/
printHeader: function() {
console.log('##########################################################');
console.log('## ' + Settings.name + ' ##');
console.log('##########################################################');
}
};

View File

@ -1,6 +1,6 @@
var mysql = require('mysql');
var settings = require('./Settings.js');
var logger = require('./Logger.js');
var settings = require('./settings.js');
var logger = require('./logger.js');
module.exports = {
@ -13,7 +13,7 @@ module.exports = {
* Iniciar pool de conexión con la base de datos
*/
init: function() {
this.pool = mysql.createPool(settings.mysql);
this.pool = mysql.createPool(settings.mysql());
this.pool.getConnection(function(error, connection) {
if (error) {

View File

@ -0,0 +1,26 @@
var fs = require('fs');
var settings = require('./settings.js');
var logger = require('./logger.js');
var path = require('path');
module.exports = {
/**
* Devuelve las claves de idioma de una plantilla
* @param {String} templateName - Nombre de la plantilla
* @param {String} langCode - Código de idioma
* @return {Object} Devuelve el objeto con las claves de idioma
*/
load: function(templateName, langCode) {
// Comprobamos que exista una traducción para esta plantilla
var localeFile = path.join(__dirname, 'Language', `${langCode}.${templateName}.json`);
var defaultLocaleFile = path.join(__dirname, 'Language', `${settings.defaultLanguage}.${templateName}.json`);
if (fs.existsSync(localeFile)) {
return require(localeFile);
} else if (fs.existsSync(defaultLocaleFile)) {
return require(defaultLocaleFile);
} else {
throw new Error('No se ha encontrado ninguna traducción para la plantilla ' + templateName + '.');
}
}
};

View File

@ -1,6 +1,7 @@
var nodemailer = require('nodemailer');
var settings = require('./Settings.js');
var logger = require('./Logger.js');
var settings = require('./settings.js');
var logger = require('./logger.js');
var path = require('path');
// Módulo para el envío de emails
module.exports = {
@ -12,7 +13,7 @@ module.exports = {
* carga el fichero de configuración.
*/
init: function() {
this.transporter = nodemailer.createTransport(settings.smtp);
this.transporter = nodemailer.createTransport(settings.smtp());
this.transporter.verify(function(error, success) {
if (error) {
@ -28,17 +29,29 @@ module.exports = {
* @param {Object} data - Datos para el envío del email
*/
send: function(data) {
var filePath = 'Template/images/';
let mailOptions = {
from: '"' + settings.senderName + '" <' + settings.senderMail + '>',
from: '"' + settings.app().senderName + '" <' + settings.app().senderMail + '>',
to: data.recipient,
subject: data.subject,
html: data.body
html: data.body,
attachments: [
{filename: 'header.png', path: path.join(__dirname, filePath, 'header.png'), cid: 'header'},
{filename: 'arrow.png', path: path.join(__dirname, filePath, 'arrow.png'), cid: 'arrow'},
{filename: 'chat.png', path: path.join(__dirname, filePath, 'chat.png'), cid: 'chat'},
{filename: 'facebook.png', path: path.join(__dirname, filePath, 'facebook.png'), cid: 'facebook'},
{filename: 'twitter.png', path: path.join(__dirname, filePath, 'twitter.png'), cid: 'twitter'},
{filename: 'youtube.png', path: path.join(__dirname, filePath, 'youtube.png'), cid: 'youtube'},
{filename: 'pinterest.png', path: path.join(__dirname, filePath, 'pinterest.png'), cid: 'pinterest'},
{filename: 'instagram.png', path: path.join(__dirname, filePath, 'instagram.png'), cid: 'instagram'},
{filename: 'linkedin.png', path: path.join(__dirname, filePath, 'linkedin.png'), cid: 'linkedin'}
]
};
this.transporter.sendMail(mailOptions, (error, info) => {
if (error) {
logger.print(__LOG_ERROR, error);
} else if (Settings.debug) {
} else if (settings.app().debug) {
logger.print(__LOG_INFO, 'Se ha enviado el email ' + info.messageId + ' [' + info.response + ']');
return true;

View File

@ -4,7 +4,7 @@ var settings = require('./settings.js');
// Página por defecto
router.get('/', function(request, response) {
response.send(settings.name + ' v' + settings.version);
response.send(settings.app().name + ' v' + settings.app().version);
});
// Rutas de los escritos.

View File

@ -1,2 +1,27 @@
// Módulo de configuración
module.exports = require('./config.json');
module.exports = {
/**
* Configuración de la aplicación
* @return {Object} Objeto de configuración app
*/
app: function() {
return require('./Config/mailerApp.json');
},
/**
* Configuración de smtp
* @return {Object} Objeto de configuración smtp
*/
smtp: function() {
return require('./Config/mailerSmtp.json');
},
/**
* Configuración de mysql
* @return {Object} Objeto de configuración MySQL
*/
mysql: function() {
return require('./Config/mailerMysql.json');
}
}

View File

@ -1,33 +1,33 @@
var fs = require('fs');
var mustache = require('mustache');
var database = require('./database.js');
var logger = require('./logger.js');
var language = require('./language.js');
var path = require('path');
var Template = {
/**
* Obtiene la plantilla
* @param {String} name - Nombre de la plantilla
* @param {String} templateName - Nombre de la plantilla
* @param {Object} langCode - Código del idioma
* @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;
}
getTemplate: function(templateName, langCode, params, callback) {
database.pool.query('SELECT name, attachmentPath FROM vn.mailTemplates WHERE name = ?', [templateName], function(error, rs) {
// Comprobamos que exista la plantilla
if (rs.length == 0)
throw new Error('La plantilla ' + templateName + ' no existe');
var path = './Application/Template/' + rs[0].name + '.html';
var langParams = language.load(templateName, langCode);
params = Object.assign({}, langParams, params);
var templatePath = path.join(__dirname, '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);
});
}
if (!fs.existsSync(templatePath))
throw new Error('No se ha podido cargar la plantilla ' + templateName + '.html');
Template.render(templatePath, params, function(tplBody) {
callback({subject: params.subject, body: tplBody});
});
});
},

View File

@ -8,6 +8,7 @@
"express": "^4.15.3",
"mustache": "^2.3.0",
"mysql": "^2.13.0",
"nodemailer": "^4.0.1"
"nodemailer": "^4.0.1",
"path": "^0.12.7"
}
}

View File

@ -9,7 +9,6 @@ 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());
@ -18,14 +17,13 @@ app.use(bodyParser.urlencoded({extended: true}));
// Cargar rutas
app.use('/', require('./Application/router.js'));
// Iniciar escucha del servidor
app.start = function() {
return app.listen(settings.port, function() {
terminal.printHeader();
return app.listen(settings.app().port, function() {
mail.init();
database.init();
logger.print(__LOG_INFO, 'Servidor de correo iniciado en el puerto ' + settings.port);
if (settings.debug) {
logger.print(__LOG_INFO, 'Servidor de correo iniciado en el puerto ' + settings.app().port);
if (settings.app().debug) {
logger.print(__LOG_WARNING, 'El modo debug está activado');
}
});
@ -35,3 +33,4 @@ if (require.main === module) {
app.start();
}