salix/modules/client/back/models/address.js

84 lines
2.5 KiB
JavaScript
Raw Normal View History

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;
module.exports = Self => {
2023-09-06 07:18:28 +00:00
require('../methods/address/getAddress')(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.validateAsync('postalCode', hasValidPostcode, {
2020-01-29 13:13:25 +00:00
message: `The postcode doesn't exist. Please enter a correct one`
});
async function hasValidPostcode(err, done) {
if (!this.postalCode)
return done();
const models = Self.app.models;
const postcode = await models.Postcode.findById(this.postalCode);
if (!postcode) err();
done();
}
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',
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;
});
};