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.ticketId) throw new Error('The argument ticketId is required'); const ticketId = reqArgs.ticketId; const ticket = await db.findOneFromDef(`${sqlPath}/ticket`, [ticketId]); const sales = await db.rawSqlFromDef(`${sqlPath}/sales`, [ticketId]); const args = Object.assign({ ticketId: (String(ticket.id)), recipientId: ticket.clientFk, recipient: ticket.recipient, replyTo: ticket.salesPersonEmail }, response.locals); const content = toCSV(sales); const fileName = `ticket_${ticketId}.csv`; const email = new Email('delivery-note', args); await email.send({ overrideAttachments: true, attachments: [{ filename: fileName, content: content }] }); response.status(200).json({message: 'Success'}); } catch (error) { next(error); } };