const db = require('vn-print/core/database'); const Email = require('vn-print/core/email'); const Report = require('vn-print/core/report'); const storage = require('vn-print/core/storage'); module.exports = async function(request, response, next) { try { response.status(200).json({ message: 'Success' }); const invoices = await db.rawSql(` SELECT io.id, io.clientFk, io.issued, io.ref, c.email recipient, c.salesPersonFk, c.isToBeMailed, c.hasToInvoice, co.hasDailyInvoice, eu.email salesPersonEmail FROM invoiceOut_queue ioq JOIN invoiceOut io ON io.id = ioq.invoiceFk JOIN client c ON c.id = io.clientFk JOIN province p ON p.id = c.provinceFk JOIN country co ON co.id = p.countryFk LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk WHERE status = ''`); let connection; let invoiceId; for (const invoiceOut of invoices) { try { invoiceId = invoiceOut.id; connection = await db.getConnection(); connection.query('START TRANSACTION'); const args = Object.assign({ invoiceId: invoiceOut.id, recipientId: invoiceOut.clientFk, recipient: invoiceOut.recipient, replyTo: invoiceOut.salesPersonEmail }, response.locals); const invoiceReport = new Report('invoice', args); const stream = await invoiceReport.toPdfStream(); const issued = invoiceOut.issued; const year = issued.getFullYear().toString(); const month = (issued.getMonth() + 1).toString(); const day = issued.getDate().toString(); const fileName = `${year}${invoiceOut.ref}.pdf`; // Store invoice storage.write(stream, { type: 'invoice', path: `${year}/${month}/${day}`, fileName: fileName }); connection.query('UPDATE invoiceOut SET hasPdf = true WHERE id = ?', [invoiceOut.id]); const isToBeMailed = invoiceOut.recipient && invoiceOut.salesPersonFk && invoiceOut.isToBeMailed; if (isToBeMailed) { const mailOptions = { overrideAttachments: true, attachments: [] }; const invoiceAttachment = { filename: fileName, content: stream }; if (invoiceOut.serial == 'E' && invoiceOut.companyCode == 'VNL') { const exportation = new Report('exportation', args); const stream = await exportation.toPdfStream(); const fileName = `CITES-${invoiceOut.ref}.pdf`; mailOptions.attachments.push({ filename: fileName, content: stream }); } mailOptions.attachments.push(invoiceAttachment); const email = new Email('invoice', args); await email.send(mailOptions); } // Update queue status const date = new Date(); sql = `UPDATE invoiceOut_queue SET status = "printed", printed = ? WHERE invoiceFk = ?`; connection.query(sql, [date, invoiceOut.id]); connection.query('COMMIT'); } catch (error) { connection.query('ROLLBACK'); connection.release(); sql = `UPDATE invoiceOut_queue SET status = ? WHERE invoiceFk = ?`; await db.rawSql(sql, [error.message, invoiceId]); } } } catch (error) { next(error); } };