salix/print/methods/schedule/invoice.js

119 lines
4.2 KiB
JavaScript
Raw Normal View History

2022-04-28 12:59:29 +00:00
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 {
const reqArgs = request.body;
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 = ''`);
for (const invoiceOut of invoices) {
try {
const args = Object.assign({
invoiceId: invoiceOut.id,
recipientId: invoiceOut.clientFk,
recipient: invoiceOut.recipient,
replyTo: invoiceOut.salesPersonEmail
}, reqArgs);
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
});
await db.rawSql('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);
}
} catch (error) {
console.log(error);
}
}
// const clientData = new Map();
// for (const client of clients)
// clientData.set(client.id, client);
// for (const clientId of reqArgs.clientIds) {
// const client = clientData.get(clientId);
// if (client) {
// const args = Object.assign({
// recipientId: clientId,
// recipient: client.email,
// replyTo: client.salesPersonEmail
// }, response.locals);
// const email = new Email('campaign-metrics', args);
// await email.send();
// }
// }
} catch (error) {
next(error);
}
};