salix/modules/ticket/back/methods/sale/updateDiscount.js

74 lines
2.3 KiB
JavaScript
Raw Normal View History

2018-12-27 11:54:16 +00:00
let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
2019-05-29 09:11:54 +00:00
Self.remoteMethod('updateDiscount', {
description: 'Changes the discount of a sale',
2019-05-22 10:35:24 +00:00
accessType: 'WRITE',
accepts: [{
2019-05-29 09:11:54 +00:00
arg: 'ticketFk',
type: 'number',
required: true,
2019-05-29 09:11:54 +00:00
description: 'ticket id',
}, {
arg: 'sales',
type: ['object'],
required: true,
description: 'sale ID, newDiscount, price, ticket',
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/updateDiscount`,
verb: 'post'
}
});
2019-05-29 09:11:54 +00:00
Self.updateDiscount = async(ticketFk, sales) => {
const validDiscounts = sales.every(sale => {
return !isNaN(sale.discount);
});
if (!validDiscounts)
throw new UserError(`The value should be a number`);
2018-07-13 13:21:37 +00:00
let model = Self.app.models;
2019-05-29 09:11:54 +00:00
let ticket = await model.Ticket.findById(ticketFk, {
2019-05-06 05:40:59 +00:00
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
2019-05-06 05:40:59 +00:00
},
});
if (ticket.refFk)
2019-03-06 07:54:56 +00:00
throw new UserError(`The sales of this ticket can't be modified`);
2019-05-29 09:11:54 +00:00
let manaDiscount;
let buyerDiscount = await model.ComponentRate.findOne({where: {code: 'buyerDiscount'}});
2019-05-06 05:40:59 +00:00
let usesMana = await model.WorkerMana.findOne({where: {workerFk: ticket.client().salesPersonFk}, fields: 'amount'});
2019-05-29 09:11:54 +00:00
let componentId = buyerDiscount.id;
if (usesMana) {
manaDiscount = await model.ComponentRate.findOne({where: {code: 'mana'}});
componentId = manaDiscount.id;
}
2019-05-29 09:11:54 +00:00
for (let i = 0; i < sales.length; i++) {
let currentLine = await model.Sale.findOne({where: {id: sales[i].id}, fields: 'price'});
let value = ((-currentLine.price * sales[i].discount) / 100);
2019-05-29 09:11:54 +00:00
await model.SaleComponent.upsert({saleFk: sales[i].id, value: value, componentFk: componentId});
2019-05-29 09:11:54 +00:00
await model.Sale.update({id: sales[i].id}, {discount: sales[i].discount});
}
2019-02-14 11:06:14 +00:00
if (usesMana) {
2019-05-29 09:11:54 +00:00
query = `call vn.manaSpellersRequery(?)`;
2019-05-06 05:40:59 +00:00
await Self.rawSql(query, [ticket.client().salesPersonFk]);
2019-02-14 11:06:14 +00:00
}
};
};