2018-12-21 19:22:13 +00:00
|
|
|
let UserError = require('vn-loopback/common/helpers').UserError;
|
2018-08-02 07:49:00 +00:00
|
|
|
|
2018-06-28 13:27:29 +00:00
|
|
|
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'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2018-08-14 10:48:12 +00:00
|
|
|
Self.getTicket = async params => {
|
2018-06-28 13:27:29 +00:00
|
|
|
let model = Self.app.models;
|
|
|
|
let thisTicketIsEditable = await model.Ticket.isEditable(params.ticketFk);
|
|
|
|
|
|
|
|
if (!thisTicketIsEditable)
|
2018-08-02 07:49:00 +00:00
|
|
|
throw new UserError(`The sales of this ticket can't be modified`);
|
2018-06-28 13:27:29 +00:00
|
|
|
|
2018-08-14 10:48:12 +00:00
|
|
|
return await model.Ticket.find({
|
2018-06-28 13:27:29 +00:00
|
|
|
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-06-28 13:27:29 +00:00
|
|
|
|
2018-08-14 10:48:12 +00:00
|
|
|
let ticket = await Self.getTicket(params);
|
2018-06-28 13:27:29 +00:00
|
|
|
let usesMana = await model.WorkerMana.findOne({where: {workerFk: ticket[0].client().salesPersonFk}, fields: 'amount'});
|
2018-10-08 09:02:56 +00:00
|
|
|
let currentLine = await Self.app.models.Sale.findOne({where: {id: params.id}});
|
2018-06-28 13:27:29 +00:00
|
|
|
|
2018-08-14 10:48:12 +00:00
|
|
|
let componentToUse;
|
2018-06-28 13:27:29 +00:00
|
|
|
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]);
|
|
|
|
|
2018-10-08 09:02:56 +00:00
|
|
|
await currentLine.updateAttributes({price: params.price});
|
2018-08-14 10:48:12 +00:00
|
|
|
|
|
|
|
query = `call vn.manaSpellersRequery(?)`;
|
2018-06-28 13:27:29 +00:00
|
|
|
await Self.rawSql(query, [ticket[0].client().salesPersonFk]);
|
|
|
|
};
|
|
|
|
};
|