salix/print/methods/closure/closeAll.js

73 lines
2.6 KiB
JavaScript
Raw Normal View History

const db = require('vn-print/core/database');
const closure = require('./closure');
2022-01-17 11:33:11 +00:00
module.exports = async function(request, response, next) {
try {
2022-09-13 11:20:18 +00:00
const reqArgs = request.body;
2022-09-13 11:20:18 +00:00
let toDate = new Date();
toDate.setDate(toDate.getDate() - 1);
if (reqArgs.to) toDate = reqArgs.to;
const todayMinDate = new Date();
2022-09-29 07:35:57 +00:00
todayMinDate.setHours(0, 0, 0, 0);
2022-09-13 11:20:18 +00:00
const todayMaxDate = new Date();
2022-09-29 07:35:57 +00:00
todayMinDate.setHours(23, 59, 59, 59);
2022-09-13 11:20:18 +00:00
// Prevent closure for current day
if (toDate >= todayMinDate && toDate <= todayMaxDate)
throw new Error('You cannot close tickets for today');
const tickets = await db.rawSql(`
SELECT
t.id,
t.clientFk,
2022-08-10 10:13:31 +00:00
t.companyFk,
c.name clientName,
c.email recipient,
c.salesPersonFk,
c.isToBeMailed,
c.hasToInvoice,
co.hasDailyInvoice,
eu.email salesPersonEmail
FROM ticket t
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN warehouse wh ON wh.id = t.warehouseFk AND wh.hasComission
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN alertLevel al ON al.id = ts.alertLevel
JOIN client c ON c.id = t.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
2022-01-19 08:12:10 +00:00
WHERE al.code = 'PACKED'
AND DATE(t.shipped) BETWEEN DATE_ADD(?, INTERVAL -2 DAY)
AND util.dayEnd(?)
AND t.refFk IS NULL
2022-09-13 11:20:18 +00:00
GROUP BY t.id`, [toDate, toDate]);
2022-01-17 11:33:11 +00:00
await closure.start(tickets, response.locals);
await db.rawSql(`
UPDATE ticket t
JOIN ticketState ts ON t.id = ts.ticketFk
JOIN alertLevel al ON al.id = ts.alertLevel
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
JOIN zone z ON z.id = t.zoneFk
SET t.routeFk = NULL
WHERE DATE(t.shipped) BETWEEN DATE_ADD(?, INTERVAL -2 DAY)
AND util.dayEnd(?)
AND al.code NOT IN('DELIVERED','PACKED')
AND t.routeFk
2022-09-13 11:20:18 +00:00
AND z.name LIKE '%MADRID%'`, [toDate, toDate]);
response.status(200).json({
message: 'Success'
});
} catch (error) {
next(error);
}
};