2018-12-27 11:54:16 +00:00
|
|
|
let UserError = require('vn-loopback/util/user-error');
|
|
|
|
let getFinalState = require('vn-loopback/util/hook').getFinalState;
|
|
|
|
let isMultiple = require('vn-loopback/util/hook').isMultiple;
|
2018-01-29 11:37:54 +00:00
|
|
|
|
2018-05-04 09:46:03 +00:00
|
|
|
module.exports = Self => {
|
2019-02-28 07:55:34 +00:00
|
|
|
// Methods
|
|
|
|
require('../methods/address/createDefaultAddress')(Self);
|
2018-01-29 11:37:54 +00:00
|
|
|
|
2018-11-22 13:12:52 +00:00
|
|
|
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);
|
2018-11-29 10:08:26 +00:00
|
|
|
let cannotHaveET;
|
|
|
|
if (client && client.fi) {
|
|
|
|
let tin = client.fi.toUpperCase();
|
|
|
|
cannotHaveET = /^[A-B]/.test(tin);
|
|
|
|
} else
|
|
|
|
cannotHaveET = false;
|
|
|
|
|
2018-11-22 13:12:52 +00:00
|
|
|
|
|
|
|
if (cannotHaveET && this.isEqualizated)
|
|
|
|
err();
|
|
|
|
done();
|
|
|
|
}
|
|
|
|
|
2018-01-29 11:37:54 +00:00
|
|
|
Self.beforeRemote('findById', function(ctx, modelInstance, next) {
|
|
|
|
ctx.args.filter = {
|
|
|
|
include: [{
|
|
|
|
relation: 'province',
|
|
|
|
scope: {
|
|
|
|
fields: ['id', 'name']
|
|
|
|
}
|
|
|
|
}, {
|
2018-02-28 11:07:56 +00:00
|
|
|
relation: 'agencyMode',
|
2018-01-29 11:37:54 +00:00
|
|
|
scope: {
|
|
|
|
fields: ['id', 'name']
|
|
|
|
}
|
|
|
|
}]
|
|
|
|
};
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
|
|
|
// Helpers
|
|
|
|
|
|
|
|
Self.observe('before save', async function(ctx) {
|
2019-02-28 07:55:34 +00:00
|
|
|
const Client = Self.app.models.Client;
|
|
|
|
|
2018-01-29 11:37:54 +00:00
|
|
|
if (isMultiple(ctx)) return;
|
|
|
|
|
2019-02-28 07:55:34 +00:00
|
|
|
let transaction = {};
|
|
|
|
if (ctx.options && ctx.options.transaction)
|
|
|
|
transaction = ctx.options.transaction;
|
|
|
|
|
2018-01-29 11:37:54 +00:00
|
|
|
let changes = ctx.data || ctx.instance;
|
|
|
|
let finalState = getFinalState(ctx);
|
|
|
|
|
2019-02-28 07:55:34 +00:00
|
|
|
const client = await Client.findById(finalState.clientFk, {
|
|
|
|
fields: ['isEqualizated', 'defaultAddressFk']
|
|
|
|
}, {transaction});
|
2018-01-29 11:37:54 +00:00
|
|
|
|
2019-02-28 07:55:34 +00:00
|
|
|
if (changes.isActive == false && client.defaultAddressFk === finalState.id)
|
|
|
|
throw new UserError('The default consignee can not be unchecked');
|
2018-03-28 08:45:09 +00:00
|
|
|
|
2019-02-28 07:55:34 +00:00
|
|
|
// Propagate client isEqualizated to all addresses
|
|
|
|
if (ctx.isNewInstance == true)
|
|
|
|
ctx.instance.isEqualizated = client.isEqualizated;
|
2018-01-29 11:37:54 +00:00
|
|
|
});
|
|
|
|
};
|