salix/modules/claim/back/methods/claim/updateClaim.js

100 lines
3.1 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('updateClaim', {
description: 'Update a claim with privileges',
accepts: [{
arg: 'ctx',
type: 'Object',
http: {source: 'context'}
}, {
arg: 'id',
type: 'Number',
description: 'Claim id',
http: {source: 'path'}
},
{
arg: 'workerFk',
type: 'Number'
},
{
arg: 'claimStateFk',
type: 'Number'
},
{
arg: 'observation',
type: 'String'
},
{
arg: 'hasToPickUp',
type: 'boolean'
}],
returns: {
type: 'object',
root: true
},
http: {
verb: 'patch',
path: `/updateClaim/:id`
}
});
Self.updateClaim = async(ctx, id) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const args = ctx.args;
const $t = ctx.req.__; // $translate
const claim = await models.Claim.findById(id, {
include: {
relation: 'client',
scope: {
include: {
relation: 'salesPersonUser'
}
}
}
});
let changedHasToPickUp = false;
if (args.hasToPickUp)
changedHasToPickUp = true;
if (args.claimStateFk) {
const canUpdate = await canChangeState(ctx, claim.claimStateFk);
const hasRights = await canChangeState(ctx, args.claimStateFk);
const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant');
if (!canUpdate || !hasRights || changedHasToPickUp && !isSalesAssistant)
throw new UserError(`You don't have enough privileges to change that field`);
}
delete args.ctx;
const updatedClaim = await claim.updateAttributes(args);
// Get sales person from claim client
const salesPerson = claim.client().salesPersonUser();
if (salesPerson && changedHasToPickUp && updatedClaim.hasToPickUp) {
const origin = ctx.req.headers.origin;
const message = $t('Claim will be picked', {
claimId: claim.id,
clientName: claim.client().name,
claimUrl: `${origin}/#!/claim/${claim.id}/summary`
});
await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message);
}
return updatedClaim;
};
async function canChangeState(ctx, id) {
let models = Self.app.models;
let userId = ctx.req.accessToken.userId;
let state = await models.ClaimState.findById(id, {
include: {
relation: 'writeRole'
}
});
let stateRole = state.writeRole().name;
let canUpdate = await models.Account.hasRole(userId, stateRole);
return canUpdate;
}
};