81 lines
2.4 KiB
JavaScript
81 lines
2.4 KiB
JavaScript
let UserError = require('vn-loopback/common/helpers').UserError;
|
|
let getFinalState = require('vn-loopback/common/helpers').getFinalState;
|
|
let isMultiple = require('vn-loopback/common/helpers').isMultiple;
|
|
|
|
module.exports = Self => {
|
|
Self.validate('isDefaultAddress', isActive,
|
|
{message: 'Unable to default a disabled consignee'}
|
|
);
|
|
|
|
function isActive(err) {
|
|
if (!this.isActive && this.isDefaultAddress) err();
|
|
}
|
|
|
|
Self.validateAsync('isEqualizated', cannotHaveET, {
|
|
message: 'Cannot check Equalization Tax in this NIF/CIF'
|
|
});
|
|
|
|
async function cannotHaveET(err, done) {
|
|
let client = await Self.app.models.Client.findById(this.clientFk);
|
|
let cannotHaveET;
|
|
if (client && client.fi) {
|
|
let tin = client.fi.toUpperCase();
|
|
cannotHaveET = /^[A-B]/.test(tin);
|
|
} else
|
|
cannotHaveET = false;
|
|
|
|
|
|
if (cannotHaveET && this.isEqualizated)
|
|
err();
|
|
done();
|
|
}
|
|
|
|
Self.beforeRemote('findById', function(ctx, modelInstance, next) {
|
|
ctx.args.filter = {
|
|
include: [{
|
|
relation: 'province',
|
|
scope: {
|
|
fields: ['id', 'name']
|
|
}
|
|
}, {
|
|
relation: 'agencyMode',
|
|
scope: {
|
|
fields: ['id', 'name']
|
|
}
|
|
}]
|
|
};
|
|
next();
|
|
});
|
|
|
|
// Helpers
|
|
|
|
Self.observe('before save', async function(ctx) {
|
|
if (isMultiple(ctx)) return;
|
|
|
|
let changes = ctx.data || ctx.instance;
|
|
let finalState = getFinalState(ctx);
|
|
|
|
if (changes.isActive == false && finalState.isDefaultAddress)
|
|
throw new UserError('The default consignee can not be unchecked');
|
|
|
|
if (changes.isDefaultAddress == true && finalState.isActive != false) {
|
|
let filter = {
|
|
clientFk: finalState.clientFk,
|
|
isDefaultAddress: {neq: false}
|
|
};
|
|
await Self.updateAll(filter, {isDefaultAddress: false});
|
|
}
|
|
|
|
if (ctx.isNewInstance == true) {
|
|
let filter = {
|
|
where: {
|
|
id: ctx.instance.clientFk
|
|
},
|
|
fields: ['isEqualizated']
|
|
};
|
|
let findOneResponse = await Self.app.models.Client.findOne(filter);
|
|
ctx.instance.isEqualizated = findOneResponse.isEqualizated;
|
|
}
|
|
});
|
|
};
|