90 lines
2.7 KiB
JavaScript
90 lines
2.7 KiB
JavaScript
const {Email} = require('vn-print');
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethodCtx('cmrEmail', {
|
|
description: 'Sends the email with an cmr attached PDF',
|
|
accessType: 'WRITE',
|
|
accepts: [
|
|
{
|
|
arg: 'tickets',
|
|
type: ['number'],
|
|
required: true,
|
|
description: 'The ticket id',
|
|
}
|
|
],
|
|
http: {
|
|
path: '/cmrEmail',
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.cmrEmail = 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 models.TicketDms.findOne({
|
|
where: {ticketFk: ticketId},
|
|
include: [{
|
|
relation: 'dms',
|
|
fields: ['id'],
|
|
scope: {
|
|
relation: 'dmsType',
|
|
scope: {
|
|
where: {code: 'cmr'}
|
|
}
|
|
}
|
|
}]
|
|
}, myOptions);
|
|
|
|
if (!dms) throw new UserError('Cmr file does not exist');
|
|
|
|
const response = await models.Dms.downloadFile(ctx, dms.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;
|
|
}
|
|
};
|
|
};
|