2019-11-18 14:04:51 +00:00
|
|
|
const db = require('../core/database');
|
|
|
|
const Email = require('../core/email');
|
|
|
|
const smtp = require('../core/smtp');
|
|
|
|
const config = require('../core/config');
|
|
|
|
|
|
|
|
module.exports = app => {
|
2020-01-23 12:31:07 +00:00
|
|
|
app.get('/api/closure', async function(request, response) {
|
2019-11-18 14:04:51 +00:00
|
|
|
const failedtickets = [];
|
|
|
|
const tickets = await db.rawSql(`
|
|
|
|
SELECT
|
|
|
|
t.id,
|
|
|
|
t.clientFk,
|
|
|
|
c.email recipient
|
|
|
|
FROM expedition e
|
|
|
|
JOIN ticket t ON t.id = e.ticketFk
|
|
|
|
JOIN client c ON c.id = t.clientFk
|
|
|
|
JOIN warehouse w ON w.id = t.warehouseFk AND hasComission
|
|
|
|
LEFT JOIN ticketState ts ON ts.ticketFk = t.id
|
2019-11-19 10:53:01 +00:00
|
|
|
WHERE ts.code = 'PACKED'
|
2019-11-18 14:04:51 +00:00
|
|
|
AND DATE(t.shipped) BETWEEN DATE_ADD(CURDATE(), INTERVAL -2 DAY) AND CURDATE()
|
|
|
|
AND t.refFk IS NULL
|
|
|
|
GROUP BY e.ticketFk`);
|
|
|
|
|
|
|
|
for (const ticket of tickets) {
|
|
|
|
try {
|
|
|
|
await db.rawSql(`CALL vn.ticketClosureTicket(:ticketId)`, {
|
|
|
|
ticketId: ticket.id
|
|
|
|
});
|
|
|
|
|
|
|
|
const args = {
|
|
|
|
ticketId: ticket.id,
|
|
|
|
clientId: ticket.clientFk,
|
|
|
|
recipient: ticket.recipient
|
|
|
|
};
|
|
|
|
const email = new Email('delivery-note-link', args);
|
|
|
|
await email.send();
|
|
|
|
} catch (error) {
|
|
|
|
// Save tickets on a list of failed ids
|
2019-11-19 10:53:01 +00:00
|
|
|
failedtickets.push({
|
|
|
|
id: ticket.id,
|
|
|
|
stacktrace: error
|
|
|
|
});
|
2019-11-18 14:04:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send email with failed tickets
|
|
|
|
if (failedtickets.length > 0) {
|
2019-11-19 10:53:01 +00:00
|
|
|
let body = 'This following tickets has failed:<br/><br/>';
|
|
|
|
|
|
|
|
for (ticket of failedtickets) {
|
|
|
|
body += `Ticket: <strong>${ticket.id}</strong>
|
|
|
|
<br/> <strong>${ticket.stacktrace}</strong><br/><br/>`;
|
|
|
|
}
|
|
|
|
|
2019-11-18 14:04:51 +00:00
|
|
|
smtp.send({
|
|
|
|
to: config.app.reportEmail,
|
2019-11-19 10:53:01 +00:00
|
|
|
subject: '[API] Nightly ticket closure has failed',
|
|
|
|
html: body
|
2019-11-18 14:04:51 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-01-23 12:31:07 +00:00
|
|
|
response.status(200).json({
|
2019-11-18 14:04:51 +00:00
|
|
|
message: 'Closure executed successfully'
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|