72 lines
2.1 KiB
JavaScript
72 lines
2.1 KiB
JavaScript
let UserError = require('vn-loopback/util/user-error');
|
|
let getFinalState = require('vn-loopback/util/hook').getFinalState;
|
|
let isMultiple = require('vn-loopback/util/hook').isMultiple;
|
|
|
|
module.exports = Self => {
|
|
// Methods
|
|
require('../methods/address/createDefaultAddress')(Self);
|
|
require('../methods/address/filter')(Self);
|
|
|
|
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) {
|
|
const Client = Self.app.models.Client;
|
|
|
|
if (isMultiple(ctx)) return;
|
|
|
|
let transaction = {};
|
|
if (ctx.options && ctx.options.transaction)
|
|
transaction = ctx.options.transaction;
|
|
|
|
let changes = ctx.data || ctx.instance;
|
|
let finalState = getFinalState(ctx);
|
|
|
|
const client = await Client.findById(finalState.clientFk, {
|
|
fields: ['isEqualizated', 'defaultAddressFk']
|
|
}, {transaction});
|
|
|
|
if (changes.isActive == false && client.defaultAddressFk === finalState.id)
|
|
throw new UserError('The default consignee can not be unchecked');
|
|
|
|
// Propagate client isEqualizated to all addresses
|
|
if (ctx.isNewInstance == true)
|
|
ctx.instance.isEqualizated = client.isEqualizated;
|
|
});
|
|
};
|