82 lines
2.4 KiB
JavaScript
82 lines
2.4 KiB
JavaScript
const UserError = require('vn-loopback/util/user-error');
|
|
const print = require('vn-print');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethodCtx('createPdf', {
|
|
description: 'Creates an invoice PDF',
|
|
accessType: 'WRITE',
|
|
accepts: [
|
|
{
|
|
arg: 'id',
|
|
type: 'number',
|
|
description: 'The invoice id',
|
|
http: {source: 'path'}
|
|
}
|
|
],
|
|
returns: {
|
|
type: 'object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/:id/createPdf`,
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.createPdf = async function(ctx, id, options) {
|
|
const models = Self.app.models;
|
|
const userId = ctx.req.accessToken.userId;
|
|
|
|
if (process.env.NODE_ENV == 'test')
|
|
throw new UserError(`Action not allowed on the test environment`);
|
|
|
|
let tx;
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
}
|
|
|
|
try {
|
|
const invoiceOut = await Self.findById(id, null, myOptions);
|
|
const hasInvoicing = await models.Account.hasRole(userId, 'invoicing', myOptions);
|
|
|
|
if (invoiceOut.hasPdf && !hasInvoicing)
|
|
throw new UserError(`You don't have enough privileges`);
|
|
|
|
await invoiceOut.updateAttributes({
|
|
hasPdf: true
|
|
}, myOptions);
|
|
|
|
const invoiceReport = new print.Report('invoice', {
|
|
reference: invoiceOut.ref,
|
|
recipientId: invoiceOut.clientFk
|
|
});
|
|
const stream = await invoiceReport.toPdfStream();
|
|
|
|
const issued = invoiceOut.issued;
|
|
const year = issued.getFullYear().toString();
|
|
const month = (issued.getMonth() + 1).toString();
|
|
const day = issued.getDate().toString();
|
|
|
|
const fileName = `${year}${invoiceOut.ref}.pdf`;
|
|
|
|
// Store invoice
|
|
print.storage.write(stream, {
|
|
type: 'invoice',
|
|
path: `${year}/${month}/${day}`,
|
|
fileName: fileName
|
|
});
|
|
|
|
if (tx) await tx.commit();
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|