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

105 lines
3.5 KiB
JavaScript
Raw Normal View History

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'
}
});
2019-01-16 11:55:38 +00:00
Self.importToNewRefundTicket = async(ctx, id) => {
2019-06-21 06:26:59 +00:00
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']
}
}
]
};
2019-06-21 06:26:59 +00:00
const salesFilter = {
where: {claimFk: id},
include: [
{
relation: 'sale',
scope: {
2019-06-21 06:26:59 +00:00
fields: [
'id',
'itemFk',
'concept',
'price',
'discount',
'reserved',
'isPicked',
'created',
'priceFixed',
'isPriceFixed']
}
}
]
};
try {
let options = {transaction: tx};
2019-06-21 06:26:59 +00:00
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();
2018-10-10 07:59:42 +00:00
return newRefundTicket;
} catch (e) {
await tx.rollback();
throw e;
}
};
async function insertIntoClaimEnd(claimBeginnings, claimId, workerId, options) {
2019-06-21 06:26:59 +00:00
const formatedSales = [];
claimBeginnings.forEach(claimBeginning => {
2019-06-21 06:26:59 +00:00
let formatedSale = {
saleFk: claimBeginning.saleFk,
2019-06-21 06:26:59 +00:00
claimFk: claimId,
workerFk: workerId
};
formatedSales.push(formatedSale);
});
await Self.app.models.ClaimEnd.create(formatedSales, options);
}
};