83 lines
2.8 KiB
JavaScript
83 lines
2.8 KiB
JavaScript
|
const express = require('express');
|
||
|
const router = new express.Router();
|
||
|
const path = require('path');
|
||
|
const db = require('../../../core/database');
|
||
|
const sqlPath = path.join(__dirname, 'sql');
|
||
|
|
||
|
module.exports = app => {
|
||
|
router.get('/preview', async function(req, res, next) {
|
||
|
try {
|
||
|
const reqArgs = req.args;
|
||
|
if (!reqArgs.invoiceId)
|
||
|
throw new Error('The argument invoiceId is required');
|
||
|
|
||
|
const invoiceId = reqArgs.invoiceId;
|
||
|
const sales = await db.rawSqlFromDef(`${sqlPath}/sales`, [invoiceId]);
|
||
|
const content = app.toCSV(sales);
|
||
|
const fileName = `invoice_${invoiceId}.csv`;
|
||
|
|
||
|
res.setHeader('Content-type', 'application/json; charset=utf-8');
|
||
|
res.setHeader('Content-Disposition', `inline; filename="${fileName}"`);
|
||
|
res.end(content);
|
||
|
} catch (error) {
|
||
|
next(error);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
router.get('/download', async function(req, res, next) {
|
||
|
try {
|
||
|
const reqArgs = req.args;
|
||
|
if (!reqArgs.invoiceId)
|
||
|
throw new Error('The argument invoiceId is required');
|
||
|
|
||
|
const invoiceId = reqArgs.invoiceId;
|
||
|
const sales = await db.rawSqlFromDef(`${sqlPath}/sales`, [invoiceId]);
|
||
|
const content = app.toCSV(sales);
|
||
|
const fileName = `invoice_${invoiceId}.csv`;
|
||
|
|
||
|
res.setHeader('Content-type', 'text/csv');
|
||
|
res.setHeader('Content-Disposition', `inline; filename="${fileName}"`);
|
||
|
res.end(content);
|
||
|
} catch (error) {
|
||
|
next(error);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
const Email = require('../../../core/email');
|
||
|
router.get('/send', async function(req, res, next) {
|
||
|
try {
|
||
|
const reqArgs = req.args;
|
||
|
if (!reqArgs.invoiceId)
|
||
|
throw new Error('The argument invoiceId is required');
|
||
|
|
||
|
const invoiceId = reqArgs.invoiceId;
|
||
|
const invoice = await db.findOneFromDef(`${sqlPath}/invoice`, [invoiceId]);
|
||
|
const sales = await db.rawSqlFromDef(`${sqlPath}/sales`, [invoiceId]);
|
||
|
|
||
|
const args = Object.assign({
|
||
|
invoiceId: (String(invoice.id)),
|
||
|
recipientId: invoice.clientFk,
|
||
|
recipient: invoice.recipient,
|
||
|
replyTo: invoice.salesPersonEmail
|
||
|
}, reqArgs);
|
||
|
|
||
|
const content = app.toCSV(sales);
|
||
|
const fileName = `invoice_${invoiceId}.csv`;
|
||
|
const email = new Email('invoice', args);
|
||
|
await email.send({
|
||
|
overrideAttachments: true,
|
||
|
attachments: [{
|
||
|
filename: fileName,
|
||
|
content: content
|
||
|
}]
|
||
|
});
|
||
|
|
||
|
res.status(200).json({message: 'ok'});
|
||
|
} catch (error) {
|
||
|
next(error);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
return router;
|
||
|
};
|