From ed84aa46bd15364b6e0a31b8e4b03792c5f76849 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 5 Jan 2022 14:29:03 +0100 Subject: [PATCH] feat(client): add more condition for businessType Validation --- modules/client/back/models/client.js | 45 +++++++++++++++------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index dc32ac2c0..ea87a49ee 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -55,18 +55,6 @@ module.exports = Self => { with: /^[\w|.|-]+@[\w|-]+(\.[\w|-]+)*(,[\w|.|-]+@[\w|-]+(\.[\w|-]+)*)*$/ }); - Self.validateAsync('businessTypeFk', hasBusinessType, { - message: `The type of business must be filled in basic data` - }); - - async function hasBusinessType(err, done) { - const isWorker = await Self.app.models.UserAccount.findById(this.id); - - if (!this.businessTypeFk && !isWorker) - err(); - done(); - } - Self.validatesLengthOf('postcode', { allowNull: true, allowBlank: true, @@ -192,6 +180,24 @@ module.exports = Self => { return regexp.test(value); } + Self.observe('before save', async ctx => { + const changes = ctx.data || ctx.instance; + const orgData = ctx.currentInstance; + const hasChanges = orgData && changes; + + const businessTypeFk = changes && changes.businessTypeFk || orgData && orgData.businessTypeFk; + + const isTaxDataChecked = changes && changes.isTaxDataChecked || orgData && orgData.isTaxDataChecked; + const isTaxDataCheckedChanged = hasChanges && orgData.isTaxDataChecked != isTaxDataChecked; + + let isWorker = false; + if (!ctx.isNewInstance) + isWorker = await Self.app.models.UserAccount.findById(orgData.id); + + if (!businessTypeFk && !isTaxDataChecked && !isTaxDataCheckedChanged && !isWorker) + throw new UserError(`The type of business must be filled in basic data`); + }); + Self.observe('before save', async function(ctx) { const changes = ctx.data || ctx.instance; const orgData = ctx.currentInstance; @@ -209,7 +215,7 @@ module.exports = Self => { && orgData.isTaxDataChecked != isTaxDataChecked; if ((socialNameChanged || dataCheckedChanged) && !isAlpha(socialName)) - throw new UserError('The socialName has an invalid format'); + throw new UserError(`The socialName has an invalid format`); if (changes.salesPerson === null) { changes.credit = 0; @@ -377,14 +383,11 @@ module.exports = Self => { throw new UserError(`You don't have enough privileges to set this credit amount`); } - const client = await models.Client.findById(finalState.id, null, ctx.options); - if (client.businessTypeFk) { - await models.ClientCredit.create({ - amount: changes.credit, - clientFk: finalState.id, - workerFk: userId - }, ctx.options); - } + await models.ClientCredit.create({ + amount: changes.credit, + clientFk: finalState.id, + workerFk: userId + }, ctx.options); }; const app = require('vn-loopback/server/server');