salix/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js

86 lines
2.7 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('makePdfAndNotify', {
description: 'Create invoice PDF and send it to client',
accessType: 'WRITE',
accepts: [
{
arg: 'id',
type: 'number',
description: 'The invoice id',
required: true,
http: {source: 'path'}
}, {
arg: 'printerFk',
type: 'number',
description: 'The printer to print'
}
],
http: {
path: '/:id/makePdfAndNotify',
verb: 'POST'
}
});
Self.makePdfAndNotify = async function(ctx, id, printerFk, options) {
const models = Self.app.models;
options = typeof options == 'object'
? Object.assign({}, options) : {};
options.userId = ctx.req.accessToken.userId;
try {
await Self.makePdf(id, options);
} catch (err) {
throw new UserError('Error while generating PDF', 'pdfError');
}
const invoiceOut = await Self.findById(id, {
fields: ['ref', 'clientFk'],
include: {
relation: 'client',
scope: {
fields: ['id', 'email', 'isToBeMailed', 'salesPersonFk']
}
}
}, options);
const ref = invoiceOut.ref;
const client = invoiceOut.client();
if (client.isToBeMailed || !printerFk) {
try {
ctx.args = {
reference: ref,
recipientId: client.id,
recipient: client.email
};
await Self.invoiceEmail(ctx, ref);
} catch (err) {
const url = await Self.app.models.Url.getUrl();
const message = ctx.req.__('Mail not sent', {
clientId: client.id,
clientUrl: `${url}claim/${id}/summary`
});
const salesPersonId = client.salesPersonFk;
if (salesPersonId)
await models.Chat.sendCheckingPresence(ctx, salesPersonId, message);
throw new UserError('Error when sending mail to client', 'mailNotSent');
}
} else {
const query = `
CALL vn.report_print(
'invoice',
?,
account.myUser_getId(),
JSON_OBJECT('refFk', ?),
'normal'
);`;
await Self.rawSql(query, [printerFk, ref], options);
}
};
};