76 lines
2.3 KiB
JavaScript
76 lines
2.3 KiB
JavaScript
let UserError = require('vn-loopback/common/helpers').UserError;
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethod('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'
|
|
}
|
|
});
|
|
|
|
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`);
|
|
|
|
return await model.Ticket.find({
|
|
where: {
|
|
id: params.ticketFk
|
|
},
|
|
include: [{
|
|
relation: 'client',
|
|
scope: {
|
|
fields: ['salesPersonFk']
|
|
}
|
|
}],
|
|
fields: ['id', 'clientFk']
|
|
});
|
|
};
|
|
|
|
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;
|
|
|
|
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}});
|
|
|
|
let componentToUse;
|
|
if (usesMana)
|
|
componentToUse = 37;
|
|
else
|
|
componentToUse = 34;
|
|
|
|
let value = (params.price - currentLine.price);
|
|
|
|
let query = `INSERT INTO vn.saleComponent(saleFk, componentFk, value)
|
|
VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE value = value + ?`;
|
|
|
|
await Self.rawSql(query, [params.id, componentToUse, value, value]);
|
|
|
|
await currentLine.updateAttributes({price: params.price});
|
|
|
|
query = `call vn.manaSpellersRequery(?)`;
|
|
await Self.rawSql(query, [ticket[0].client().salesPersonFk]);
|
|
};
|
|
};
|