79 lines
2.2 KiB
JavaScript
79 lines
2.2 KiB
JavaScript
const UserError = require('vn-loopback/util/user-error');
|
|
const {Email} = require('vn-print');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethodCtx('invoiceEmail', {
|
|
description: 'Sends the invoice email with an attached PDF',
|
|
accessType: 'WRITE',
|
|
accepts: [
|
|
{
|
|
arg: 'reference',
|
|
type: 'string',
|
|
required: true,
|
|
http: {source: 'path'}
|
|
}, {
|
|
arg: 'recipient',
|
|
type: 'string',
|
|
description: 'The recipient email',
|
|
required: true,
|
|
}, {
|
|
arg: 'replyTo',
|
|
type: 'string',
|
|
description: 'The sender email to reply to',
|
|
required: false
|
|
}, {
|
|
arg: 'recipientId',
|
|
type: 'number',
|
|
description: 'The recipient id to send to the recipient preferred language',
|
|
required: false
|
|
}
|
|
],
|
|
returns: {
|
|
type: ['object'],
|
|
root: true
|
|
},
|
|
http: {
|
|
path: '/:reference/invoice-email',
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.invoiceEmail = async(ctx, reference) => {
|
|
const args = Object.assign({}, ctx.args);
|
|
const params = {
|
|
recipient: args.recipient,
|
|
lang: ctx.req.getLocale()
|
|
};
|
|
|
|
const invoiceOut = await Self.findOne({
|
|
where: {ref: reference}
|
|
});
|
|
|
|
delete args.ctx;
|
|
for (const param in args)
|
|
params[param] = args[param];
|
|
|
|
const email = new Email('invoice', params);
|
|
|
|
const [stream, ...headers] = await Self.download(ctx, invoiceOut.id);
|
|
const name = headers[1];
|
|
const fileName = name.replace(/filename="(.*)"/gm, '$1');
|
|
|
|
const mailOptions = {
|
|
overrideAttachments: true,
|
|
attachments: [
|
|
{
|
|
filename: fileName,
|
|
content: stream
|
|
}
|
|
]
|
|
};
|
|
|
|
try {
|
|
return email.send(mailOptions);
|
|
} catch (err) {
|
|
throw new UserError('Error when sending mail to client', 'mailNotSent');
|
|
}
|
|
};
|
|
};
|