salix/modules/ticket/back/methods/ticket/state.js

86 lines
2.7 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('state', {
description: 'Change the state of a ticket',
accessType: 'WRITE',
accepts: [
{
arg: 'data',
type: 'Object',
required: true,
http: {source: 'body'}
}
],
returns: {
type: 'Object',
root: true
},
http: {
path: `/state`,
verb: 'POST'
}
});
Self.state = 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 {
if (!params.stateFk && !params.code)
throw new UserError('State cannot be blank');
if (params.stateFk) {
const {code} = await models.State.findById(params.stateFk, {fields: ['code']}, myOptions);
params.code = code;
} else {
const {id} = await models.State.findOne({where: {code: params.code}}, myOptions);
params.stateFk = id;
}
if (!params.userFk) {
const worker = await models.Worker.findOne({
where: {id: ctx.req.accessToken.userId}
}, myOptions);
params.userFk = worker.id;
}
const ticketState = await models.TicketState.findById(params.ticketFk, {
fields: ['stateFk']
}, myOptions);
const oldStateAllowed = ticketState && await models.State.isEditable(ctx, ticketState.stateFk, myOptions);
const newStateAllowed = await models.State.isEditable(ctx, params.stateFk, myOptions);
if ((ticketState && !oldStateAllowed) || !newStateAllowed)
throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED');
await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [params.ticketFk, params.code], myOptions);
const ticketTracking = await models.TicketTracking.findOne({
where: {ticketFk: params.ticketFk},
order: 'id DESC',
limit: 1
}, myOptions);
await ticketTracking.updateAttribute('userFk', params.userFk, myOptions);
if (tx) await tx.commit();
return ticketTracking;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};