var fs = require('fs'); var mustache = require('mustache'); var locale = require('./locale.js'); var path = require('path'); module.exports = { /** * Obtiene la plantilla. * @param {String} template - Nombre de la plantilla * @param {Object} countryCode - Código del idioma * @param {Object} params - Datos a reemplazar. * @param {Object} cb - Callback */ getTemplate: function(template, countryCode, params, cb) { var templatePath = path.join(__dirname, 'template', `${template}`, `${template}.html`); var classPath = path.join(__dirname, 'template', `${template}`, `${template}.js`); fs.stat(templatePath, (error, stat) => { if (error) return cb(null, 'Template ' + template + ' not found'); let TemplateClass = require(classPath); let instance = new TemplateClass(); let getDataCb = () => { this.render(templatePath, instance, body => { var titleSubject = body.match(new RegExp('(.*?)', 'i'))[1]; this.getAttachments(template, body, attachments => { cb({body: body, subject: titleSubject, attachments: attachments}); }); }); }; locale.load(template, countryCode, (translations, error) => { instance._ = translations; instance.getData(params, () => getDataCb()); }); }); }, /** * Renderiza las plantillas * @param {String} path - Ruta de la plantilla * @param {Object} data - Listado de parámetros a remplazar * @param {Object} cb - Callback */ render: function(path, data, cb) { fs.readFile(path, 'utf8', function(error, body) { mustache.parse(body); cb(mustache.render(body, data)); }); }, /** * Obtiene todos los ficheros adjuntos de la plantilla * @param {String} template - Nombre de la plantilla * @param {String} body - html de la plantilla * @param {Object} cb - Callback */ getAttachments: function(template, body, cb) { var attachments = []; var tplAttachments = body.match(new RegExp('src="cid:(.*?)"', 'ig')); for (var i = 0; i < tplAttachments.length; i++) { var name = tplAttachments[i].replace('src="cid:', '').replace('"', ''); var attachmentPath = path.join(__dirname, 'template/image', name); attachments.push({filename: name, path: attachmentPath, cid: name}); } var attachmentsPath = path.join(__dirname, 'template', `${template}`, 'attachment.json'); fs.stat(attachmentsPath, (error, stats) => { if (error) return cb(null, 'Could not load attachments from template ' + template); var attachObj = require(attachmentsPath); for (var i = 0; i < attachObj.length; i++) { var attachmentPath = path.join(__dirname, 'template', `${template}`, 'attachment', attachObj[i]); attachments.push({filename: attachObj[i], path: attachmentPath, cid: attachObj[i]}); } cb(attachments); }); } };