salix/modules/ticket/back/methods/ticket/saveCmr.js

84 lines
2.8 KiB
JavaScript

const {Readable} = require('stream');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('saveCmr', {
description: 'Save cmr',
accessType: 'WRITE',
accepts: [
{
arg: 'tickets',
type: ['number'],
required: true,
description: 'The tickets'
}
],
http: {
path: `/saveCmr`,
verb: 'POST'
}
});
Self.saveCmr = async(ctx, tickets, options) => {
const models = Self.app.models;
const myOptions = {userId: ctx.req.accessToken.userId};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const dmsTypeCmr = await models.DmsType.findOne({
where: {code: 'cmr'},
fields: ['id']
}, myOptions);
for (const ticketId of tickets) {
const ticket = await models.Ticket.findById(ticketId, myOptions);
if (ticket.cmrFk) {
const hasDmsCmr = await Self.rawSql(`
SELECT d.id
FROM ticketDms td
JOIN dms d ON d.id = td.dmsFk
WHERE td.ticketFk = ?
AND d.dmsTypeFk = ?
`, [ticketId, dmsTypeCmr.id]);
if (hasDmsCmr.length)
throw new UserError('This ticket already has a cmr saved');
ctx.args.id = ticket.cmrFk;
const response = await models.Route.cmr(ctx, myOptions);
const pdfStream = Readable.from(Buffer.from(response[0]));
const data = {
workerFk: ctx.req.accessToken.userId,
dmsTypeFk: dmsTypeCmr.id,
companyFk: ticket.companyFk,
warehouseFk: ticket.warehouseFk,
reference: ticket.id,
contentType: 'application/pdf',
hasFile: false
};
const dms = await models.Dms.createFromStream(data, 'pdf', pdfStream, myOptions);
await models.TicketDms.create({
ticketFk: ticketId,
dmsFk: dms.id
}, myOptions);
}
}
if (tx) await tx.commit();
return;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};