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

76 lines
2.5 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
Self.remoteMethodCtx('makeInvoice', {
description: 'Make out an invoice from a ticket id',
accessType: 'WRITE',
accepts: [
{
arg: 'id',
type: 'string',
required: true,
description: 'Ticket id',
http: {source: 'path'}
}
],
returns: {
arg: 'data',
type: 'boolean',
root: true
},
http: {
path: `/:id/makeInvoice`,
verb: 'POST'
}
});
Self.makeInvoice = async(ctx, id) => {
let userId = ctx.req.accessToken.userId;
let $ = Self.app.models;
let options = {};
options.transaction = await Self.beginTransaction({});
try {
let ticket = await $.Ticket.findById(id, {fields: ['id', 'clientFk', 'companyFk']});
let clientCanBeInvoiced = await $.Client.canBeInvoiced(ticket.clientFk);
if (!clientCanBeInvoiced)
throw new UserError(`This client can't be invoiced`);
let ticketCanBeInvoiced = await $.Ticket.canBeInvoiced(ticket.id);
if (!ticketCanBeInvoiced)
throw new UserError(`This ticket can't be invoiced`);
let query = `SELECT vn.invoiceSerial(?, ?, ?) AS serial`;
let [result] = await Self.rawSql(query, [ticket.clientFk, ticket.companyFk, 'R'], options);
let serial = result.serial;
query = `CALL vn.invoiceFromTicket(?)`;
await Self.rawSql(query, [ticket.id], options);
query = `CALL vn.invoiceOutMake(?, ?, @invoiceId);
SELECT @invoiceId AS invoiceId;`;
result = await Self.rawSql(query, [serial, null], options);
let invoice = result[1][0].invoiceId;
if (serial != 'R' && invoice) {
query = `CALL vn.invoiceOutBooking(?)`;
await Self.rawSql(query, [invoice], options);
}
let user = await Self.app.models.Worker.findOne({where: {userFk: userId}});
query = `INSERT INTO printServerQueue(reportFk, param1, workerFk) VALUES (?, ?, ?)`;
await Self.rawSql(query, [3, invoice, user.id], options);
await options.transaction.commit();
return {invoiceFk: invoice, serial};
} catch (e) {
options.transaction.rollback();
throw e;
}
};
};