const path = require('path'); const db = require('vn-print/core/database'); const Email = require('vn-print/core/email'); const {toCSV} = require('../csv'); const sqlPath = path.join(__dirname, 'sql'); module.exports = async function(request, response, next) { try { const reqArgs = request.query; 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 }, response.locals); const content = toCSV(sales); const fileName = `invoice_${invoiceId}.csv`; const email = new Email('invoice', args); await email.send({ overrideAttachments: true, attachments: [{ filename: fileName, content: content }] }); response.status(200).json({message: 'Success'}); } catch (error) { next(error); } };