salix/services/loopback/common/methods/sale/updateDiscount.js

75 lines
2.4 KiB
JavaScript
Raw Normal View History

module.exports = Self => {
Self.remoteMethod('updateDiscount', {
description: 'Changes the discount of a sale',
accessType: '',
accepts: [{
arg: 'params',
type: 'object',
required: true,
description: 'sale ID, newDiscount, price',
http: {source: 'body'}
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/updateDiscount`,
verb: 'post'
}
});
Self.updateDiscount = async params => {
let model = Self.app.models;
let thisTicketIsEditable = await model.Ticket.isEditable(params.editLines[0].ticketFk);
if (!thisTicketIsEditable)
throw new Error(`The sales of this ticket can't be modified`);
let ticket = await model.Ticket.find({
where: {
id: params.editLines[0].ticketFk
},
include: [{
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
}],
fields: ['id', 'clientFk']
2018-07-13 10:37:58 +00:00
}).catch(e => {
console.log(e);
});
let componentToUse;
2018-07-13 10:37:58 +00:00
let usesMana = await model.WorkerMana.findOne({where: {workerFk: ticket[0].client().salesPersonFk}, fields: 'amount'}).catch(e => {
console.log(e);
});
if (usesMana)
componentToUse = 37;
else
componentToUse = 34;
for (let i = 0; i < params.editLines.length; i++) {
2018-07-13 10:37:58 +00:00
let currentLine = await model.Sale.findOne({where: {id: params.editLines[i].id}, fields: 'price'}).catch(e => {
console.log(e);
});
let value = (-currentLine.price * params.editLines[i].discount / 100);
2018-07-13 10:37:58 +00:00
await model.SaleComponent.upsert({saleFk: params.editLines[i].id, value: value, componentFk: componentToUse}).catch(e => {
console.log(e);
});
2018-07-13 10:37:58 +00:00
await model.Sale.update({id: params.editLines[i].id}, {discount: params.editLines[i].discount}).catch(e => {
console.log(e);
});
}
query = `
call vn.manaSpellersRequery(?)`;
2018-07-13 10:37:58 +00:00
await Self.rawSql(query, [ticket[0].client().salesPersonFk]).catch(e => {
console.log(e);
});
};
};