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

85 lines
2.7 KiB
JavaScript
Raw Normal View History

2018-12-27 11:54:16 +00:00
const UserError = require('vn-loopback/util/user-error');
2018-09-19 05:41:07 +00:00
module.exports = Self => {
Self.remoteMethodCtx('updateClaim', {
description: 'Update a claim with privileges',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'Claim id',
http: {source: 'path'}
}, {
arg: 'data',
2018-09-19 05:41:07 +00:00
type: 'object',
required: true,
description: 'Data to update on the model',
2018-09-19 05:41:07 +00:00
http: {source: 'body'}
}],
returns: {
type: 'object',
2018-09-19 05:41:07 +00:00
root: true
},
http: {
path: `/:id/updateClaim`,
2018-09-19 05:41:07 +00:00
verb: 'post'
}
});
Self.updateClaim = async(ctx, id, data) => {
2020-06-03 12:46:58 +00:00
const models = Self.app.models;
2020-06-04 06:21:08 +00:00
const userId = ctx.req.accessToken.userId;
2020-06-03 12:46:58 +00:00
const $t = ctx.req.__; // $translate
const claim = await models.Claim.findById(id, {
include: {
relation: 'client',
scope: {
include: {
relation: 'salesPerson'
}
}
}
});
2018-09-19 05:41:07 +00:00
2020-06-04 06:21:08 +00:00
const canUpdate = await canChangeState(ctx, claim.claimStateFk);
const hasRights = await canChangeState(ctx, data.claimStateFk);
const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant');
const changedHasToPickUp = claim.hasToPickUp != data.hasToPickUp;
2018-09-19 05:41:07 +00:00
2020-06-04 06:21:08 +00:00
if (!canUpdate || !hasRights || changedHasToPickUp && !isSalesAssistant)
throw new UserError(`You don't have enough privileges to change that field`);
2018-09-19 05:41:07 +00:00
2020-06-04 05:53:06 +00:00
const updatedClaim = await claim.updateAttributes(data);
2020-06-03 12:46:58 +00:00
// Get sales person from claim client
const salesPerson = claim.client().salesPerson();
2020-06-04 05:53:06 +00:00
if (salesPerson && updatedClaim.hasToPickUp) {
2020-06-03 12:46:58 +00:00
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);
}
2020-06-04 05:53:06 +00:00
return updatedClaim;
2018-09-19 05:41:07 +00:00
};
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;
}
2018-09-19 05:41:07 +00:00
};