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: 'string', 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; } let isProduction = await models.Account.hasRole(userId, 'production'); let isSalesPerson = await models.Account.hasRole(userId, 'salesPerson'); let ticket = await models.TicketState.findById( params.ticketFk, {fields: ['stateFk']} ); let oldState = await models.State.findById(ticket.stateFk); let newState = await models.State.findById(params.stateFk); let isAllowed = isProduction || isSalesPerson && oldState.isEditable() && newState.isEditable(); if (!isAllowed) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); if (newState.code != 'PICKER_DESIGNED') { let worker = await models.Worker.findOne({where: {userFk: userId}}); params.workerFk = worker.id; } return await models.TicketTracking.create(params); }; };