87 lines
2.5 KiB
JavaScript
87 lines
2.5 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: 'Object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/changeState`,
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.changeState = async(ctx, params, 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 userId = ctx.req.accessToken.userId;
|
|
|
|
if (!params.stateFk && !params.code)
|
|
throw new UserError('State cannot be blank');
|
|
|
|
if (params.code) {
|
|
const state = await models.State.findOne({
|
|
where: {code: params.code},
|
|
fields: ['id']
|
|
}, myOptions);
|
|
|
|
params.stateFk = state.id;
|
|
}
|
|
|
|
if (!params.workerFk) {
|
|
const worker = await models.Worker.findOne({
|
|
where: {id: userId}
|
|
}, myOptions);
|
|
|
|
params.workerFk = worker.id;
|
|
}
|
|
|
|
const ticketState = await models.TicketState.findById(params.ticketFk, {
|
|
fields: ['stateFk']
|
|
}, myOptions);
|
|
|
|
let oldStateAllowed;
|
|
if (ticketState)
|
|
oldStateAllowed = await models.State.isEditable(ctx, ticketState.stateFk, myOptions);
|
|
const newStateAllowed = await models.State.isEditable(ctx, params.stateFk, myOptions);
|
|
|
|
const isAllowed = (!ticketState || oldStateAllowed == true) && newStateAllowed == true;
|
|
|
|
if (!isAllowed)
|
|
throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED');
|
|
|
|
const ticketTracking = await models.TicketTracking.create(params, myOptions);
|
|
|
|
if (tx) await tx.commit();
|
|
|
|
return ticketTracking;
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|