const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('recalculatePrice', { description: 'Calculates the price of a sale and its components', accessType: 'WRITE', accepts: [{ arg: 'id', description: 'The sale id', type: 'number', required: true, http: {source: 'path'} }], returns: { type: 'Number', root: true }, http: { path: `/:id/recalculatePrice`, verb: 'post' } }); Self.recalculatePrice = async(ctx, id, options) => { const models = Self.app.models; const myOptions = {}; let tx; if (typeof options == 'object') Object.assign(myOptions, options); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } try { const sale = await Self.findById(id, null, myOptions); const isEditable = await models.Ticket.isEditable(ctx, sale.ticketFk, myOptions); if (!isEditable) throw new UserError(`The sales of this ticket can't be modified`); const canEditSale = await models.Sale.canEdit(ctx, [id], myOptions); if (!canEditSale) throw new UserError(`Sale(s) blocked, please contact production`); const recalculation = await Self.rawSql('CALL vn.sale_calculateComponent(?, null)', [id], myOptions); if (tx) await tx.commit(); return recalculation; } catch (e) { if (tx) await tx.rollback(); throw e; } }; };