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

85 lines
2.6 KiB
JavaScript

const {Email} = require('vn-print');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('sendCmrEmail', {
description: 'Sends the email with an cmr attached PDF',
accessType: 'WRITE',
accepts: [
{
arg: 'tickets',
type: ['number'],
required: true,
description: 'The ticket id',
}
],
http: {
path: '/sendCmrEmail',
verb: 'POST'
}
});
Self.sendCmrEmail = async function(ctx, tickets, options) {
const models = Self.app.models;
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
for (const ticketId of tickets) {
const ticket = await models.Ticket.findOne({
where: {
id: ticketId
},
include: [{
relation: 'client',
fields: ['email']
}]
}, myOptions);
const recipient = ticket.client().email;
if (!recipient)
throw new UserError('There is no assigned email for this client');
const dms = await Self.rawSql(`
SELECT d.id
FROM ticketDms td
JOIN dms d ON d.id = td.dmsFk
JOIN dmsType dt ON dt.id = d.dmsTypeFk
WHERE td.ticketFk = ?
AND dt.code = 'cmr'
`, [ticketId]);
if (!dms.length) throw new UserError('Cmr file does not exist');
const response = await models.Dms.downloadFile(ctx, dms[0].id);
const email = new Email('cmr', {
ticketId,
lang: ctx.req.getLocale(),
recipient
});
await email.send({
overrideAttachments: true,
attachments: [{
filename: `${ticket.$cmrFk}.pdf`,
content: response[0]
}]
});
}
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};