salix/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js

105 lines
3.5 KiB
JavaScript

const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
module.exports = Self => {
Self.remoteMethodCtx('importToNewRefundTicket', {
description: 'Imports lines from claimBeginning to a new ticket with specific shipped, landed dates, agency and company',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'the claim id',
http: {source: 'path'}
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/importToNewRefundTicket`,
verb: 'POST'
}
});
Self.importToNewRefundTicket = async(ctx, id) => {
const models = Self.app.models;
const token = ctx.req.accessToken;
const userId = token.userId;
const tx = await Self.beginTransaction({});
const filter = {
where: {id: id},
include: [
{
relation: 'ticket',
scope: {
fields: ['id', 'clientFk', 'warehouseFk', 'companyFk', 'addressFk']
}
}
]
};
const salesFilter = {
where: {claimFk: id},
include: [
{
relation: 'sale',
scope: {
fields: [
'id',
'itemFk',
'concept',
'price',
'discount',
'reserved',
'isPicked',
'created',
'priceFixed',
'isPriceFixed']
}
}
]
};
try {
let options = {transaction: tx};
const worker = await models.Worker.findOne({
where: {userFk: userId}
}, options);
const claim = await models.Claim.findOne(filter, options);
let stmts = [];
let stmt;
stmt = new ParameterizedSQL('CALL vn.refund(?, @result)', [
claim.ticketFk
]);
stmts.push(stmt);
let ticketIndex = stmts.push('SELECT @result vNewRefundTicket') - 1;
let sql = ParameterizedSQL.join(stmts, ';');
let result = await Self.rawStmt(sql, options);
let newRefundTicketId = result[ticketIndex][0].vNewRefundTicket;
const newRefundTicket = await models.Ticket.findById(newRefundTicketId, null, options);
const claimBeginnings = await models.ClaimBeginning.find(salesFilter, options);
await insertIntoClaimEnd(claimBeginnings, id, worker.id, options);
await tx.commit();
return newRefundTicket;
} catch (e) {
await tx.rollback();
throw e;
}
};
async function insertIntoClaimEnd(claimBeginnings, claimId, workerId, options) {
const formatedSales = [];
claimBeginnings.forEach(claimBeginning => {
let formatedSale = {
saleFk: claimBeginning.saleFk,
claimFk: claimId,
workerFk: workerId
};
formatedSales.push(formatedSale);
});
await Self.app.models.ClaimEnd.create(formatedSales, options);
}
};