2020-11-02 13:30:33 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
const validateTin = require('vn-loopback/util/validateTin');
|
|
|
|
|
2020-10-15 06:15:04 +00:00
|
|
|
module.exports = Self => {
|
|
|
|
require('../methods/supplier/filter')(Self);
|
2020-10-20 07:44:44 +00:00
|
|
|
require('../methods/supplier/getSummary')(Self);
|
2020-10-30 14:11:45 +00:00
|
|
|
require('../methods/supplier/updateFiscalData')(Self);
|
2020-11-02 13:30:33 +00:00
|
|
|
|
|
|
|
Self.validatesPresenceOf('name', {
|
|
|
|
message: 'The social name cannot be empty'
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.validatesUniquenessOf('name', {
|
|
|
|
message: 'The supplier name must be unique'
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.validatesPresenceOf('city', {
|
|
|
|
message: 'City cannot be empty'
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.validatesPresenceOf('nif', {
|
|
|
|
message: 'The nif cannot be empty'
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.validatesUniquenessOf('nif', {
|
|
|
|
message: 'TIN must be unique'
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.validateAsync('nif', tinIsValid, {
|
|
|
|
message: 'Invalid TIN'
|
|
|
|
});
|
|
|
|
|
2020-11-04 10:37:54 +00:00
|
|
|
Self.validatesLengthOf('postCode', {
|
|
|
|
allowNull: true,
|
|
|
|
allowBlank: true,
|
|
|
|
min: 3, max: 10
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.validateAsync('postCode', hasValidPostcode, {
|
|
|
|
message: `The postcode doesn't exist. Please enter a correct one`
|
|
|
|
});
|
|
|
|
|
|
|
|
async function hasValidPostcode(err, done) {
|
|
|
|
if (!this.postcode)
|
|
|
|
return done();
|
|
|
|
|
|
|
|
const models = Self.app.models;
|
|
|
|
const postcode = await models.Postcode.findById(this.postcode);
|
|
|
|
|
|
|
|
if (!postcode) err();
|
|
|
|
done();
|
|
|
|
}
|
|
|
|
|
2020-11-02 13:30:33 +00:00
|
|
|
async function tinIsValid(err, done) {
|
|
|
|
const filter = {
|
|
|
|
fields: ['code'],
|
|
|
|
where: {id: this.countryFk}
|
|
|
|
};
|
|
|
|
const country = await Self.app.models.Country.findOne(filter);
|
|
|
|
const code = country ? country.code.toLowerCase() : null;
|
|
|
|
|
|
|
|
if (!this.nif || !validateTin(this.nif, code))
|
|
|
|
err();
|
|
|
|
done();
|
|
|
|
}
|
|
|
|
|
|
|
|
function isAlpha(value) {
|
|
|
|
const regexp = new RegExp(/^[ñça-zA-Z0-9\s]*$/i);
|
|
|
|
|
|
|
|
return regexp.test(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
Self.observe('before save', async function(ctx) {
|
|
|
|
let changes = ctx.data || ctx.instance;
|
|
|
|
let orgData = ctx.currentInstance;
|
|
|
|
|
|
|
|
const socialName = changes.name || orgData.name;
|
|
|
|
const hasChanges = orgData && changes;
|
|
|
|
const socialNameChanged = hasChanges
|
|
|
|
&& orgData.socialName != socialName;
|
|
|
|
|
|
|
|
if ((socialNameChanged) && !isAlpha(socialName))
|
|
|
|
throw new UserError('The socialName has an invalid format');
|
|
|
|
});
|
2020-10-15 06:15:04 +00:00
|
|
|
};
|