salix/modules/ticket/back/methods/ticket-tracking/changeState.js

64 lines
1.9 KiB
JavaScript

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 $ = Self.app.models;
if (!params.stateFk && !params.code)
throw new UserError('State cannot be blank');
if (params.code) {
let state = await $.State.findOne({where: {code: params.code}, fields: ['id']});
params.stateFk = state.id;
}
let isProduction = await $.Account.hasRole(userId, 'production');
let isSalesPerson = await $.Account.hasRole(userId, 'salesPerson');
let ticket = await $.TicketState.findById(
params.ticketFk,
{fields: ['stateFk']}
);
let oldState = await $.State.findById(ticket.stateFk);
let newState = await $.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 $.Worker.findOne({where: {userFk: userId}});
params.workerFk = worker.id;
}
return await $.TicketTracking.create(params);
};
};