This commit is contained in:
parent
8e256dac1b
commit
f30b1ecff1
|
@ -113,24 +113,37 @@ module.exports = Self => {
|
||||||
throw new UserError('You can not modify is pay method checked');
|
throw new UserError('You can not modify is pay method checked');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Self.validateAsync('name', 'countryFk', hasSupplierSameName, {
|
||||||
|
message: 'A supplier with the same name already exists. Change the country.'
|
||||||
|
});
|
||||||
|
|
||||||
|
async function hasSupplierSameName(err, done) {
|
||||||
|
if (!this.name || !this.countryFk) done();
|
||||||
|
const supplier = await Self.app.models.Supplier.findOne(
|
||||||
|
{
|
||||||
|
where: {
|
||||||
|
name: this.name,
|
||||||
|
countryFk: this.countryFk
|
||||||
|
},
|
||||||
|
fields: ['id']
|
||||||
|
});
|
||||||
|
|
||||||
|
if (supplier && supplier.id != this.id)
|
||||||
|
err();
|
||||||
|
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
|
||||||
Self.observe('before save', async function(ctx) {
|
Self.observe('before save', async function(ctx) {
|
||||||
const changes = ctx.data || ctx.instance;
|
const changes = ctx.data || ctx.instance;
|
||||||
const orgData = ctx.currentInstance;
|
const orgData = ctx.currentInstance;
|
||||||
|
|
||||||
|
const socialName = changes.name || orgData.name;
|
||||||
const hasChanges = orgData && changes;
|
const hasChanges = orgData && changes;
|
||||||
|
const socialNameChanged = hasChanges
|
||||||
|
&& orgData.socialName != socialName;
|
||||||
|
|
||||||
if (hasChanges) {
|
if ((socialNameChanged) && !isAlpha(socialName))
|
||||||
const name = changes.name || orgData.name;
|
throw new UserError('The social name has an invalid format');
|
||||||
const nameChanged = hasChanges && orgData.name != name;
|
|
||||||
const countryFk = changes.countryFk || orgData.countryFk;
|
|
||||||
const countryChanged = hasChanges && orgData.countryFk != countryFk;
|
|
||||||
|
|
||||||
if (nameChanged || countryChanged) {
|
|
||||||
if (!isAlpha(name)) throw new UserError('The social name has an invalid format');
|
|
||||||
|
|
||||||
const supplier = await Self.app.models.Supplier.findOne({where: {name, countryFk}, fields: ['id']});
|
|
||||||
if (supplier)
|
|
||||||
throw new UserError('A supplier with the same name already exists. Change the country.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
Loading…
Reference in New Issue