UNPKG

openhim-core

Version:

The OpenHIM core application that provides logging and routing of http requests

267 lines (240 loc) 10.8 kB
var Channel, EmailTemplate, Q, User, afterEmail, authorisation, config, contact, fetchChannelReport, fetchDailySubscribers, fetchWeeklySubscribers, logger, metrics, moment, path, plainTemplate, renderTemplate, sendReports, sendUserEmail, setupAgenda, utils; EmailTemplate = require('email-templates').EmailTemplate; logger = require('winston'); moment = require("moment"); path = require('path'); Q = require('q'); authorisation = require('./api/authorisation'); Channel = require('./model/channels').Channel; config = require("./config/config"); config.reports = config.get('reports'); contact = require('./contact'); metrics = require('./metrics'); User = require('./model/users').User; utils = require('./utils'); sendReports = function(job, flag, done) { var channelMap, channelReportMap, fetchUsers, from, reportMap, to; reportMap = {}; channelReportMap = {}; channelMap = {}; if (flag === 'dailyReport') { from = moment().subtract(1, 'days').startOf('day').toDate(); to = moment().subtract(1, 'days').endOf('day').toDate(); } else { from = moment().subtract(1, 'days').startOf('isoWeek').toDate(); to = moment().subtract(1, 'days').endOf('isoWeek').toDate(); } if (flag === 'dailyReport') { fetchUsers = fetchDailySubscribers; } if (flag === 'weeklyReport') { fetchUsers = fetchWeeklySubscribers; } return fetchUsers(function(err, users) { var fn, innerPromises, j, len, promises, user, userIndex, userKey, usersArray; promises = []; userKey = ''; userIndex = 0; usersArray = []; fn = function(user) { var deferred; deferred = Q.defer(); userKey = user.email; authorisation.getUserViewableChannels(user).then(function(channels) { var channel, k, len1, ref; usersArray[userIndex] = user; usersArray[userIndex].allowedChannels = channels; ref = usersArray[userIndex].allowedChannels; for (k = 0, len1 = ref.length; k < len1; k++) { channel = ref[k]; channelMap[channel._id] = { user: user, channel: channel }; } userIndex++; return deferred.resolve(); }); return promises.push(deferred.promise); }; for (j = 0, len = users.length; j < len; j++) { user = users[j]; fn(user); } innerPromises = []; return (Q.all(promises)).then(function() { var fn1, innerDeferred, key, obj; fn1 = function(innerDeferred, key, obj) { return fetchChannelReport(obj.channel, obj.user, flag, from, to, function(err, item) { channelReportMap[key] = item; return innerDeferred.resolve(); }); }; for (key in channelMap) { obj = channelMap[key]; innerDeferred = Q.defer(); fn1(innerDeferred, key, obj); innerPromises.push(innerDeferred.promise); } return (Q.all(innerPromises)).then(function() { var channel, colorGrey, data, error, fn2, i, k, l, len1, len2, len3, m, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, report, rowColor; for (k = 0, len1 = usersArray.length; k < len1; k++) { user = usersArray[k]; userKey = user.email; ref = user.allowedChannels; fn2 = function(channel) { var data; if (reportMap[userKey]) { } else { reportMap[userKey] = { email: user.email, data: [] }; } if (channelReportMap[channel._id]) { data = channelReportMap[channel._id]; if ((data.channel.status == null) || data.channel.status === 'enabled' || data.data.length !== 0) { return reportMap[userKey].data.push(data); } } else { return logger.error('should never be here since channels have been pre-fetched'); } }; for (l = 0, len2 = ref.length; l < len2; l++) { channel = ref[l]; fn2(channel); } } for (key in reportMap) { report = reportMap[key]; if (flag === 'dailyReport') { report.isDaily = true; } else { report.isDaily = false; } report.instance = config.alerts.himInstance; report.consoleURL = config.alerts.consoleURL; report.from = moment(from).format('YYYY-MM-DD'); report.to = moment(to).format('YYYY-MM-DD'); try { ref1 = report.data; for (i = m = 0, len3 = ref1.length; m < len3; i = ++m) { data = ref1[i]; colorGrey = 'color: grey;'; rowColor = 'background-color: #d9ead3'; if (i % 2) { rowColor = 'background-color: #b6d7a8;'; } report.data[i].total = (((ref2 = data.data[0]) != null ? ref2.total : void 0) != null ? data.data[0].total : 0); report.data[i].avgResp = (((ref3 = data.data[0]) != null ? ref3.avgResp : void 0) != null ? Math.round(data.data[0].avgResp) : 0); report.data[i].failed = (((ref4 = data.data[0]) != null ? ref4.failed : void 0) != null ? data.data[0].failed : 0); report.data[i].successful = (((ref5 = data.data[0]) != null ? ref5.successful : void 0) != null ? data.data[0].successful : 0); report.data[i].processing = (((ref6 = data.data[0]) != null ? ref6.processing : void 0) != null ? data.data[0].processing : 0); report.data[i].completed = (((ref7 = data.data[0]) != null ? ref7.completed : void 0) != null ? data.data[0].completed : 0); report.data[i].completedWErrors = (((ref8 = data.data[0]) != null ? ref8.completedWErrors : void 0) != null ? data.data[0].completedWErrors : 0); report.data[i].totalStyle = (report.data[i].total > 0 ? '' : colorGrey); report.data[i].avgRespStyle = (report.data[i].avgResp > 0 ? '' : colorGrey); report.data[i].failedStyle = (report.data[i].failed > 0 ? 'color: red;' : colorGrey); report.data[i].successfulStyle = (report.data[i].successful > 0 ? '' : colorGrey); report.data[i].processingStyle = (report.data[i].processing > 0 ? '' : colorGrey); report.data[i].completedStyle = (report.data[i].completed > 0 ? 'color: orange;' : colorGrey); report.data[i].completedWErrorsStyle = (report.data[i].completedWErrors > 0 ? 'color: orangered;' : colorGrey); report.data[i].rowColor = rowColor; } sendUserEmail(report); } catch (error) { err = error; logger.error(err); job.fail("Failed to send report reason: " + err); } } return done(); }); }); }); }; sendUserEmail = function(report) { report.date = new Date().toString(); return renderTemplate('report', report, function(reportHtml) { return contact.contactUser('email', report.email, report.type + ' report for: ' + report.instance, plainTemplate(report), reportHtml, afterEmail); }); }; fetchChannelReport = function(channel, user, flag, from, to, callback) { var item, period; if (flag === 'dailyReport') { period = 'day'; } else { period = 'week'; } item = {}; logger.info('fetching ' + flag + ' for #' + channel.name + ' ' + user.email + ' ' + channel._id); return metrics.calculateMetrics(from, to, null, [channel._id], period).then(function(data) { item.channel = channel; item.data = data; return callback(null, item); })["catch"](function(err) { logger.error('Error calculating metrics: ', err); return callback(err); }); }; fetchDailySubscribers = function(callback) { return User.find({ dailyReport: true }, callback); }; fetchWeeklySubscribers = function(callback) { return User.find({ weeklyReport: true }, callback); }; plainTemplate = function(report) { var data, fn, j, len, ref, text; text = "Generated on: " + (new Date().toString()); ref = report.data; fn = function(data) { var ref1, ref2, ref3, ref4, ref5, ref6, ref7; return text += " \r\n \r\n <---------- Start Channel " + data.channel.name + " ---------------------------> \r\n \r\n Channel Name: " + data.channel.name + " \r\n Channel total: " + (((ref1 = data.data[0]) != null ? ref1.total : void 0) != null ? data.data[0].total : 0) + " transactions \r\n Ave response time: " + (((ref2 = data.data[0]) != null ? ref2.avgResp : void 0) != null ? data.data[0].avgResp : 0) + " \r\n Failed: " + (((ref3 = data.data[0]) != null ? ref3.failed : void 0) != null ? data.data[0].failed : 0) + " \r\n Successful: " + (((ref4 = data.data[0]) != null ? ref4.successful : void 0) != null ? data.data[0].successful : 0) + " \r\n Processing: " + (((ref5 = data.data[0]) != null ? ref5.processing : void 0) != null ? data.data[0].processing : 0) + " \r\n Completed: " + (((ref6 = data.data[0]) != null ? ref6.completed : void 0) != null ? data.data[0].completed : 0) + " \r\n Completed with errors: " + (((ref7 = data.data[0]) != null ? ref7.completedWErrors : void 0) != null ? data.data[0].completedWErrors : 0) + " \r\n \r\n <---------- End Channel -------------------------------------------------> \r\n \r\n \r\n \r\n"; }; for (j = 0, len = ref.length; j < len; j++) { data = ref[j]; fn(data); } return text; }; renderTemplate = function(templateName, templateData, callback) { var template, templateDir; templateDir = appRoot + "/templates/" + templateName; template = new EmailTemplate(templateDir); return template.render(templateData, function(err, result) { if (err) { logger.err(err); } return callback(result.html.toString()); }); }; afterEmail = function(callback) { return logger.info('email sent..'); }; setupAgenda = function(agenda) { agenda.define('send weekly channel metrics', function(job, done) { return sendReports(job, 'weeklyReport', done); }); agenda.define('send daily channel metrics', function(job, done) { return sendReports(job, 'dailyReport', done); }); agenda.every(config.reports.weeklyReportAt, 'send weekly channel metrics', null, { timezone: utils.serverTimezone() }); return agenda.every(config.reports.dailyReportAt, 'send daily channel metrics', null, { timezone: utils.serverTimezone() }); }; exports.setupAgenda = setupAgenda; if (process.env.NODE_ENV === "test") { exports.sendReports = sendReports; exports.fetchDailySubscribers = fetchDailySubscribers; exports.fetchWeeklySubscribers = fetchWeeklySubscribers; exports.fetchChannelReport = fetchChannelReport; exports.sendUserEmail = sendUserEmail; } //# sourceMappingURL=reports.js.map