salix/print/methods/schedule/consumption.js

59 lines
1.9 KiB
JavaScript

const db = require('vn-print/core/database');
const Email = require('vn-print/core/email');
module.exports = async function(request, response, next) {
try {
const reqArgs = request.body;
if (!reqArgs.clientIds)
throw new Error('The argument clientIds is required');
if (!reqArgs.from)
throw new Error('The argument from is required');
if (!reqArgs.to)
throw new Error('The argument to is required');
response.status(200).json({
message: 'Success'
});
const clientIds = reqArgs.clientIds;
const clients = await db.rawSql(`
SELECT
c.id,
c.email,
eu.email salesPersonEmail
FROM client c
JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk
JOIN ticket t ON t.clientFk = c.id
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
WHERE c.id IN(?)
AND it.isPackaging = FALSE
AND DATE(t.shipped) BETWEEN ? AND ?
GROUP BY c.id`, [clientIds, reqArgs.from, reqArgs.to]);
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);
}
};