2018-11-22 13:12:52 +00:00
|
|
|
let UserError = require('../helpers').UserError;
|
|
|
|
let getFinalState = require('../helpers').getFinalState;
|
|
|
|
let isMultiple = require('../helpers').isMultiple;
|
2018-01-29 11:37:54 +00:00
|
|
|
|
2018-05-04 09:46:03 +00:00
|
|
|
module.exports = Self => {
|
2018-01-29 11:37:54 +00:00
|
|
|
Self.validate('isDefaultAddress', isActive,
|
2018-01-29 18:57:00 +00:00
|
|
|
{message: 'Unable to default a disabled consignee'}
|
2018-01-29 11:37:54 +00:00
|
|
|
);
|
2018-11-22 13:12:52 +00:00
|
|
|
|
2018-01-29 11:37:54 +00:00
|
|
|
function isActive(err) {
|
|
|
|
if (!this.isActive && this.isDefaultAddress) err();
|
|
|
|
}
|
|
|
|
|
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) {
|
|
|
|
if (isMultiple(ctx)) return;
|
|
|
|
|
|
|
|
let changes = ctx.data || ctx.instance;
|
|
|
|
let finalState = getFinalState(ctx);
|
|
|
|
|
|
|
|
if (changes.isActive == false && finalState.isDefaultAddress)
|
2018-01-29 18:57:00 +00:00
|
|
|
throw new UserError('The default consignee can not be unchecked');
|
2018-01-29 11:37:54 +00:00
|
|
|
|
2018-02-03 21:53:02 +00:00
|
|
|
if (changes.isDefaultAddress == true && finalState.isActive != false) {
|
2018-01-29 11:37:54 +00:00
|
|
|
let filter = {
|
|
|
|
clientFk: finalState.clientFk,
|
|
|
|
isDefaultAddress: {neq: false}
|
|
|
|
};
|
|
|
|
await Self.updateAll(filter, {isDefaultAddress: false});
|
|
|
|
}
|
2018-03-28 08:45:09 +00:00
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
2018-01-29 11:37:54 +00:00
|
|
|
});
|
|
|
|
};
|