84 lines
2.8 KiB
JavaScript
84 lines
2.8 KiB
JavaScript
const UserError = require('vn-loopback/util/user-error');
|
|
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
|
|
|
|
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) => {
|
|
const conn = Self.dataSource.connector;
|
|
let userId = ctx.req.accessToken.userId;
|
|
let models = Self.app.models;
|
|
let tx = await Self.beginTransaction({});
|
|
|
|
try {
|
|
let options = {transaction: tx};
|
|
|
|
let filter = {fields: ['id', 'clientFk', 'companyFk']};
|
|
let ticket = await models.Ticket.findById(id, filter, options);
|
|
|
|
let clientCanBeInvoiced = await models.Client.canBeInvoiced(ticket.clientFk);
|
|
if (!clientCanBeInvoiced)
|
|
throw new UserError(`This client can't be invoiced`);
|
|
|
|
let ticketCanBeInvoiced = await models.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;
|
|
let stmts = [];
|
|
|
|
stmt = new ParameterizedSQL('CALL vn.invoiceOut_newFromTicket(?, ?, ?, @invoiceId)', [
|
|
ticket.id,
|
|
serial,
|
|
null
|
|
]);
|
|
stmts.push(stmt);
|
|
|
|
let invoiceIndex = stmts.push(`SELECT @invoiceId AS invoiceId`) - 1;
|
|
|
|
let sql = ParameterizedSQL.join(stmts, ';');
|
|
result = await conn.executeStmt(sql);
|
|
let invoiceId = result[invoiceIndex][0].invoiceId;
|
|
if (serial != 'R' && invoiceId) {
|
|
query = `CALL vn.invoiceOutBooking(?)`;
|
|
await Self.rawSql(query, [invoiceId], options);
|
|
}
|
|
|
|
let user = await models.Worker.findOne({where: {userFk: userId}}, options);
|
|
|
|
query = `INSERT INTO printServerQueue(reportFk, param1, workerFk) VALUES (?, ?, ?)`;
|
|
await Self.rawSql(query, [3, invoiceId, user.id], options);
|
|
await tx.commit();
|
|
|
|
return {invoiceFk: invoiceId, serial};
|
|
} catch (e) {
|
|
await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|