salix/modules/claim/back/models/claim-beginning.js

60 lines
2.1 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
const LoopBackContext = require('loopback-context');
module.exports = Self => {
require('../methods/claim-beginning/importToNewRefundTicket')(Self);
Self.validatesUniquenessOf('saleFk', {
message: `A claim with that sale already exists`
});
Self.observe('before save', async ctx => {
if (ctx.isNewInstance) {
const models = Self.app.models;
const options = ctx.options;
const instance = ctx.instance;
const ticket = await models.Sale.findById(instance.saleFk, {fields: ['ticketFk']}, options);
const claim = await models.Claim.findById(instance.claimFk, {fields: ['ticketFk']}, options);
if (ticket.ticketFk != claim.ticketFk)
throw new UserError(`Cannot create a new claimBeginning from a different ticket`);
}
await claimIsEditable(ctx);
});
Self.observe('before delete', async ctx => {
if (ctx.isNewInstance) return;
await claimIsEditable(ctx);
});
async function claimIsEditable(ctx) {
const loopBackContext = LoopBackContext.getCurrentContext();
const httpCtx = {req: loopBackContext.active};
const models = Self.app.models;
const myOptions = {};
if (ctx.options && ctx.options.transaction)
myOptions.transaction = ctx.options.transaction;
const claimBeginning = ctx.instance ?? await Self.findById(ctx.where.id);
const filter = {
where: {id: claimBeginning.claimFk},
include: [
{
relation: 'claimState',
scope: {
fields: ['id', 'code', 'description']
}
}
]
};
const [claim] = await models.Claim.find(filter, myOptions);
const isEditable = await models.ClaimState.isEditable(httpCtx, claim.claimState().id);
if (!isEditable)
throw new UserError(`The current claim can't be modified`);
}
};