2019-01-22 08:55:35 +00:00
|
|
|
const reportEngine = require('./reportEngine.js');
|
|
|
|
const emailEngine = require('./emailEngine');
|
|
|
|
const express = require('express');
|
|
|
|
const routes = require(`../config/routes.json`);
|
|
|
|
|
|
|
|
module.exports = app => {
|
2019-01-25 14:08:11 +00:00
|
|
|
this.path = `${appPath}/report`;
|
2019-01-22 08:55:35 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Enables a report
|
|
|
|
*
|
|
|
|
* @param {String} name - Report state path
|
|
|
|
*/
|
|
|
|
function registerReport(name) {
|
|
|
|
if (!name) throw new Error('Report name required');
|
|
|
|
|
2019-01-28 11:28:22 +00:00
|
|
|
app.get(`/api/report/${name}`, (request, response, next) => {
|
2019-01-22 08:55:35 +00:00
|
|
|
reportEngine.toPdf(name, request).then(stream => {
|
2019-01-31 10:44:03 +00:00
|
|
|
// response.setHeader('Content-Disposition', `attachment; filename="${name}.pdf"`);
|
|
|
|
// response.setHeader('Content-type', 'application/pdf');
|
2019-01-22 08:55:35 +00:00
|
|
|
stream.pipe(response);
|
|
|
|
}).catch(e => {
|
|
|
|
next(e);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Enables a email
|
|
|
|
*
|
|
|
|
* @param {String} name - Report state path
|
|
|
|
*/
|
|
|
|
function registerEmail(name) {
|
|
|
|
if (!name) throw new Error('Email name required');
|
|
|
|
|
2019-01-28 11:28:22 +00:00
|
|
|
app.get(`/api/email/${name}`, (request, response, next) => {
|
2019-01-22 08:55:35 +00:00
|
|
|
emailEngine.render(name, request).then(rendered => {
|
|
|
|
response.send(rendered.html);
|
|
|
|
}).catch(e => {
|
|
|
|
next(e);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2019-01-28 11:28:22 +00:00
|
|
|
app.post(`/api/email/${name}`, (request, response, next) => {
|
2019-01-22 08:55:35 +00:00
|
|
|
emailEngine.toEmail(name, request).then(() => {
|
|
|
|
response.status(200).json({status: 200});
|
|
|
|
}).catch(e => {
|
|
|
|
next(e);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Register routes
|
|
|
|
*/
|
|
|
|
routes.forEach(route => {
|
|
|
|
if (route.type === 'email')
|
|
|
|
registerEmail(route.name);
|
|
|
|
else if (route.type === 'report')
|
|
|
|
registerReport(route.name);
|
|
|
|
|
|
|
|
const staticPath = this.path + `/${route.name}/assets`;
|
2019-01-28 11:28:22 +00:00
|
|
|
app.use(`/api/assets`, express.static(staticPath));
|
2019-01-22 08:55:35 +00:00
|
|
|
});
|
|
|
|
};
|