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`); const userId = ctx.req.accessToken.userId; let usesMana = await models.WorkerMana.findOne({where: {workerFk: userId}, fields: 'amount'}, options); let componentCode = usesMana ? 'mana' : 'buyerDiscount'; let discount = await models.Component.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, [userId], options); await tx.commit(); return sale; } catch (error) { await tx.rollback(); throw error; } }; };