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

88 lines
2.5 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-04-02 12:36:49 +00:00
Self.remoteMethodCtx('updatePrice', {
description: 'Changes the discount of a sale',
accessType: '',
accepts: [{
arg: 'params',
type: 'object',
required: true,
description: 'sale ID, newPrice',
http: {source: 'body'}
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/updatePrice`,
verb: 'post'
}
});
2018-08-14 10:48:12 +00:00
Self.getTicket = async params => {
let model = Self.app.models;
let thisTicketIsEditable = await model.Ticket.isEditable(params.ticketFk);
if (!thisTicketIsEditable)
throw new UserError(`The sales of this ticket can't be modified`);
2018-08-14 10:48:12 +00:00
return await model.Ticket.find({
where: {
id: params.ticketFk
},
include: [{
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
}],
fields: ['id', 'clientFk']
});
2018-08-14 10:48:12 +00:00
};
Self.updatePrice = async params => {
if (isNaN(params.price))
throw new UserError(`The value should be a number`);
if (!params.price) params.price = 0;
let model = Self.app.models;
2018-08-14 10:48:12 +00:00
let ticket = await Self.getTicket(params);
let usesMana = await model.WorkerMana.findOne({where: {workerFk: ticket[0].client().salesPersonFk}, fields: 'amount'});
let currentLine = await Self.app.models.Sale.findOne({where: {id: params.id}});
2018-08-14 10:48:12 +00:00
let componentToUse;
if (usesMana)
componentToUse = 37;
else
componentToUse = 34;
let value = (params.price - currentLine.price);
2019-04-02 12:36:49 +00:00
let saleComponent = await Self.app.models.SaleComponent.findOne({
where: {
componentFk: componentToUse,
saleFk: params.id
}
});
2019-04-02 12:36:49 +00:00
if (saleComponent)
saleComponent.updateAttributes({value: saleComponent.value + value});
else {
await Self.app.models.SaleComponent.create({
saleFk: params.id,
componentFk: componentToUse,
value: value
});
}
await currentLine.updateAttributes({price: params.price});
2018-08-14 10:48:12 +00:00
query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [ticket[0].client().salesPersonFk]);
};
};