const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('changeState', { description: 'Change the state of a ticket', accessType: 'WRITE', accepts: [ { arg: 'data', description: 'Model instance data', type: 'Object', required: true, http: {source: 'body'} } ], returns: { type: 'Object', root: true }, http: { path: `/changeState`, verb: 'POST' } }); Self.changeState = async(ctx, params) => { let userId = ctx.req.accessToken.userId; let models = Self.app.models; if (!params.stateFk && !params.code) throw new UserError('State cannot be blank'); if (params.code) { let state = await models.State.findOne({where: {code: params.code}, fields: ['id']}); params.stateFk = state.id; } if (!params.workerFk) { let worker = await models.Worker.findOne({where: {userFk: userId}}); params.workerFk = worker.id; } let ticketState = await models.TicketState.findById( params.ticketFk, {fields: ['stateFk']} ); let oldStateAllowed; if (ticketState) oldStateAllowed = await models.State.isEditable(ctx, ticketState.stateFk); let newStateAllowed = await models.State.isEditable(ctx, params.stateFk); let isAllowed = (!ticketState || oldStateAllowed == true) && newStateAllowed == true; if (!isAllowed) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); return models.TicketTracking.create(params); }; };