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

96 lines
3.1 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-05-29 10:41:26 +00:00
Self.remoteMethod('updatePrice', {
description: 'Changes the price of a sale',
2019-05-22 10:35:24 +00:00
accessType: 'WRITE',
accepts: [
{
arg: 'id',
description: 'The sale id',
type: 'number',
required: true,
http: {source: 'path'}
}, {
arg: 'newPrice',
description: 'The new price',
type: 'number',
required: true
}
],
returns: {
type: 'string',
root: true
},
http: {
path: `/:id/updatePrice`,
verb: 'post'
}
});
Self.updatePrice = async(id, newPrice) => {
let $ = Self.app.models;
let transaction = await Self.beginTransaction({});
let options = {transaction};
2018-08-14 10:48:12 +00:00
try {
let filter = {
fields: ['id', 'ticketFk', 'price'],
include: {
relation: 'ticket',
scope: {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
fields: ['id', 'clientFk']
}
}
};
let sale = await $.Sale.findById(id, filter, options);
let isEditable = await $.Ticket.isEditable(sale.ticketFk);
if (!isEditable)
throw new UserError(`The sales of this ticket can't be modified`);
let salesPerson = sale.ticket().client().salesPersonFk;
let usesMana = await $.WorkerMana.findOne({where: {workerFk: salesPerson}, fields: 'amount'}, options);
let componentCode = usesMana ? 'mana' : 'buyerDiscount';
let discount = await $.ComponentRate.findOne({where: {code: componentCode}}, options);
let componentId = discount.id;
let componentValue = newPrice - sale.price;
let where = {
2019-05-29 10:41:26 +00:00
componentFk: componentId,
saleFk: id
};
let saleComponent = await $.SaleComponent.findOne({where}, options);
if (saleComponent) {
await $.SaleComponent.updateAll(where, {
value: saleComponent.value + componentValue
}, options);
} else {
await $.SaleComponent.create({
saleFk: id,
componentFk: componentId,
value: componentValue
}, options);
}
2018-08-14 10:48:12 +00:00
await sale.updateAttributes({price: newPrice}, options);
2019-05-29 10:41:26 +00:00
query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [salesPerson], options);
2019-05-29 10:41:26 +00:00
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
};