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

51 lines
1.9 KiB
JavaScript
Raw Normal View History

const UserError = require('../../../common/helpers').UserError;
let pick = require('object.pick');
let diff = require('object-diff');
2018-09-19 05:41:07 +00:00
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) => {
2018-09-19 05:41:07 +00:00
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);
2018-10-08 12:56:34 +00:00
let statesViables = ['Gestionado', 'Pendiente', 'Anulado'];
2018-09-19 05:41:07 +00:00
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);
};
};