refs #4927 changed hook for validateAsync
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Alexandre Riera 2023-01-20 10:03:00 +01:00
parent 8e256dac1b
commit f30b1ecff1
1 changed files with 27 additions and 14 deletions

View File

@ -113,24 +113,37 @@ module.exports = Self => {
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) {
const changes = ctx.data || ctx.instance;
const orgData = ctx.currentInstance;
const socialName = changes.name || orgData.name;
const hasChanges = orgData && changes;
const socialNameChanged = hasChanges
&& orgData.socialName != socialName;
if (hasChanges) {
const name = changes.name || orgData.name;
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.');
}
}
if ((socialNameChanged) && !isAlpha(socialName))
throw new UserError('The social name has an invalid format');
});
};