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

98 lines
3.1 KiB
JavaScript

let UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('updatePrice', {
description: 'Changes the price of a sale',
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: 'Number',
root: true
},
http: {
path: `/:id/updatePrice`,
verb: 'post'
}
});
Self.updatePrice = async(ctx, id, newPrice) => {
let models = Self.app.models;
let tx = await Self.beginTransaction({});
try {
let options = {transaction: tx};
let filter = {
include: {
relation: 'ticket',
scope: {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
fields: ['id', 'clientFk']
}
}
};
let sale = await models.Sale.findById(id, filter, options);
let isEditable = await models.Ticket.isEditable(ctx, 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 models.WorkerMana.findOne({where: {workerFk: salesPerson}, fields: 'amount'}, options);
let componentCode = usesMana ? 'mana' : 'buyerDiscount';
let discount = await models.ComponentRate.findOne({where: {code: componentCode}}, options);
let componentId = discount.id;
let componentValue = newPrice - sale.price;
let where = {
componentFk: componentId,
saleFk: id
};
let saleComponent = await models.SaleComponent.findOne({where}, options);
if (saleComponent) {
await models.SaleComponent.updateAll(where, {
value: saleComponent.value + componentValue
}, options);
} else {
await models.SaleComponent.create({
saleFk: id,
componentFk: componentId,
value: componentValue
}, options);
}
await sale.updateAttributes({price: newPrice}, options);
query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [salesPerson], options);
await tx.commit();
return sale;
} catch (error) {
await tx.rollback();
throw error;
}
};
};