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

74 lines
2.3 KiB
JavaScript

let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('updateDiscount', {
description: 'Changes the discount of a sale',
accessType: 'WRITE',
accepts: [{
arg: 'ticketFk',
type: 'number',
required: true,
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'
}
});
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`);
let model = Self.app.models;
let ticket = await model.Ticket.findById(ticketFk, {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
});
if (ticket.refFk)
throw new UserError(`The sales of this ticket can't be modified`);
let manaDiscount;
let buyerDiscount = await model.ComponentRate.findOne({where: {code: 'buyerDiscount'}});
let usesMana = await model.WorkerMana.findOne({where: {workerFk: ticket.client().salesPersonFk}, fields: 'amount'});
let componentId = buyerDiscount.id;
if (usesMana) {
manaDiscount = await model.ComponentRate.findOne({where: {code: 'mana'}});
componentId = manaDiscount.id;
}
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);
await model.SaleComponent.upsert({saleFk: sales[i].id, value: value, componentFk: componentId});
await model.Sale.update({id: sales[i].id}, {discount: sales[i].discount});
}
if (usesMana) {
query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [ticket.client().salesPersonFk]);
}
};
};