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

64 lines
2.1 KiB
JavaScript

let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('updateDiscount', {
description: 'Changes the discount of a sale',
accessType: 'WRITE',
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(ctx, params) => {
if (isNaN(params.editLines[0].discount))
throw new UserError(`The value should be a number`);
let model = Self.app.models;
let ticket = await model.Ticket.findById(params.editLines[0].ticketFk, {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
});
if (ticket.refFk)
throw new UserError(`The sales of this ticket can't be modified`);
let componentToUse;
let usesMana = await model.WorkerMana.findOne({where: {workerFk: ticket.client().salesPersonFk}, fields: 'amount'});
if (usesMana)
componentToUse = 37;
else
componentToUse = 34;
for (let i = 0; i < params.editLines.length; i++) {
let currentLine = await model.Sale.findOne({where: {id: params.editLines[i].id}, fields: 'price'});
let value = ((-currentLine.price * params.editLines[i].discount) / 100);
await model.SaleComponent.upsert({saleFk: params.editLines[i].id, value: value, componentFk: componentToUse});
await model.Sale.update({id: params.editLines[i].id}, {discount: params.editLines[i].discount});
}
if (usesMana) {
query = `
call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [ticket.client().salesPersonFk]);
}
};
};