salix/services/loopback/common/methods/claim/updateClaim.js

51 lines
1.9 KiB
JavaScript

const UserError = require('../../../common/helpers').UserError;
let pick = require('object.pick');
let diff = require('object-diff');
module.exports = Self => {
Self.remoteMethodCtx('updateClaim', {
description: 'Update a claim with privileges',
accessType: 'WRITE',
accepts: [{
arg: 'params',
type: 'object',
required: true,
description: 'ticketFk, stateFk',
http: {source: 'body'}
}],
returns: {
type: 'string',
root: true
},
http: {
path: `/updateClaim`,
verb: 'post'
}
});
Self.updateClaim = async (ctx, params) => {
let models = Self.app.models;
let isSalesAssistant;
let token = ctx.req.accessToken;
let currentUserId = token && token.userId;
isSalesAssistant = await models.Account.hasRole(currentUserId, 'SalesAssistant');
if (!isSalesAssistant) {
let oldClaim = await models.Claim.findById(params.id);
let notModifiable = ['responsibility', 'isChargedToMana'];
let changedFields = diff(oldClaim, params);
let changedFieldsPicked = pick(changedFields, notModifiable);
let statesViables = ['Gestionado', 'Pendiente', 'Anulado'];
let oldState = await models.ClaimState.findOne({where: {id: oldClaim.claimStateFk}});
let newState = await models.ClaimState.findOne({where: {id: params.claimStateFk}});
let canChangeState = statesViables.includes(oldState.description)
&& statesViables.includes(newState.description);
if (Object.keys(changedFieldsPicked).length != 0 || !canChangeState)
throw new UserError(`You don't have enough privileges to change that field`);
}
return await Self.updateAll({id: params.id}, params);
};
};