From 273db31c059892b99e18c89468ac371166845a18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Segarra=20Mart=C3=ADnez?= Date: Sat, 25 Nov 2023 21:11:06 +0100 Subject: [PATCH 01/26] refs #5858 feat: approach to print bad field in model --- loopback/locale/es.json | 28 ++- .../methods/client/body_model_validator.js | 41 ++++ .../back/methods/client/updateFiscalData.js | 196 ++++++++++-------- modules/client/back/models/client.js | 18 +- 4 files changed, 189 insertions(+), 94 deletions(-) create mode 100644 modules/client/back/methods/client/body_model_validator.js diff --git a/loopback/locale/es.json b/loopback/locale/es.json index a4de6f997..76b0d955c 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -1,4 +1,5 @@ { + "postalcode": "Código postal", "Phone format is invalid": "El formato del teléfono no es correcto", "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito", "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia", @@ -327,5 +328,28 @@ "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada", "User disabled": "Usuario desactivado", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima" -} + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", + "provinceFk must be unique": "provinceFk must be unique", + "fi cannot be empty": "fi cannot be empty", + "countryFk cannot be empty": "countryFk cannot be empty", + "Model is not valid": "El campo \" {{key}}\" no es válido", + "postcode": "Código postal", + "fi": "NIF/CIF", + "socialName": "Razón social", + "street":"Dirección fiscal", + "city":"Población", + "countryFk":"País", + "provinceFk":"Provincia", + "sageTaxTypeFk":"Tipo de impuesto Sage", + "sageTransactionTypeFk":"Tipo de transacción Sage", + "transferorFk":"", + "hasToInvoiceByAddress":"", + "isFreezed":"", + "isVies":"", + "isToBeMailed":"", + "isEqualizated":"", + "isTaxDataVerified":"", + "despiteOfClient":"", + "hasIncoterms":"", + "hasElectronicInvoice":"" +} \ No newline at end of file diff --git a/modules/client/back/methods/client/body_model_validator.js b/modules/client/back/methods/client/body_model_validator.js new file mode 100644 index 000000000..c451608e6 --- /dev/null +++ b/modules/client/back/methods/client/body_model_validator.js @@ -0,0 +1,41 @@ + +const isNotNull = value => value !== null && value !== undefined && value !== ''; +const validatorBodyModel = (model, body) => { + let isValid = true; + let tag = null; + Object.entries(body).forEach(([key, value]) => { + if (!isValid) return; + const bodyArg = model.find(m => m.arg === key); + if (!bodyArg) throw new Error('Property is not defined in this model'); + const {type} = bodyArg; + tag = key; + if (tag !== 'any') { + isValid = isNotNull(value); + return; + } + + switch (type) { + case 'number': + isValid = /^[0-9]*$/.test(value); + break; + + case 'boolean': + isValid = value instanceof Boolean; + break; + + case 'date': + isValid = (new Date(date) !== 'Invalid Date') && !isNaN(new Date(date)); + break; + + case 'string': + isValid = typeof value == 'string'; + break; + + default: + break; + } + }); + return {isValid, tag}; +}; + +module.exports = validatorBodyModel; diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 5fd886c32..c3b92f6b1 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -1,4 +1,95 @@ let UserError = require('vn-loopback/util/user-error'); +const validatorBodyModel = require('./body_model_validator'); +const BODY_MODEL = [ + { + arg: 'socialName', + type: 'string' + }, + { + arg: 'fi', + type: 'string' + }, + { + arg: 'street', + type: 'string' + }, + { + arg: 'postcode', + type: 'string' + }, + { + arg: 'city', + type: 'string' + }, + { + arg: 'countryFk', + type: 'number' + }, + { + arg: 'provinceFk', + type: 'number' + }, + { + arg: 'sageTaxTypeFk', + type: 'any' + }, + { + arg: 'sageTransactionTypeFk', + type: 'any' + }, + { + arg: 'transferorFk', + type: 'any' + }, + { + arg: 'hasToInvoiceByAddress', + type: 'boolean' + }, + { + arg: 'hasToInvoice', + type: 'boolean' + }, + { + arg: 'isActive', + type: 'boolean' + }, + { + arg: 'isFreezed', + type: 'boolean' + }, + { + arg: 'isVies', + type: 'boolean' + }, + { + arg: 'isToBeMailed', + type: 'boolean' + }, + { + arg: 'isEqualizated', + type: 'boolean' + }, + { + arg: 'isTaxDataVerified', + type: 'boolean' + }, + { + arg: 'isTaxDataChecked', + type: 'boolean' + }, + { + arg: 'despiteOfClient', + type: 'number' + }, + { + arg: 'hasIncoterms', + type: 'boolean' + }, + { + arg: 'hasElectronicInvoice', + type: 'boolean' + } +]; module.exports = Self => { Self.remoteMethod('updateFiscalData', { @@ -17,92 +108,9 @@ module.exports = Self => { http: {source: 'path'} }, { - arg: 'socialName', - type: 'string' - }, - { - arg: 'fi', - type: 'string' - }, - { - arg: 'street', - type: 'string' - }, - { - arg: 'postcode', - type: 'string' - }, - { - arg: 'city', - type: 'string' - }, - { - arg: 'countryFk', - type: 'number' - }, - { - arg: 'provinceFk', - type: 'number' - }, - { - arg: 'sageTaxTypeFk', - type: 'any' - }, - { - arg: 'sageTransactionTypeFk', - type: 'any' - }, - { - arg: 'transferorFk', - type: 'any' - }, - { - arg: 'hasToInvoiceByAddress', - type: 'boolean' - }, - { - arg: 'hasToInvoice', - type: 'boolean' - }, - { - arg: 'isActive', - type: 'boolean' - }, - { - arg: 'isFreezed', - type: 'boolean' - }, - { - arg: 'isVies', - type: 'boolean' - }, - { - arg: 'isToBeMailed', - type: 'boolean' - }, - { - arg: 'isEqualizated', - type: 'boolean' - }, - { - arg: 'isTaxDataVerified', - type: 'boolean' - }, - { - arg: 'isTaxDataChecked', - type: 'boolean' - }, - { - arg: 'despiteOfClient', - type: 'number' - }, - { - arg: 'hasIncoterms', - type: 'boolean' - }, - { - arg: 'hasElectronicInvoice', - type: 'boolean' + arg: 'data', + type: 'object', + http: {source: 'body'} } ], returns: { @@ -148,8 +156,22 @@ module.exports = Self => { // Remove unwanted properties delete args.ctx; delete args.id; + const {isValid, tag} = validatorBodyModel(BODY_MODEL, args.data); + if (!isValid) { + const key = $t(`${tag}`); + throw new Error($t('Model is not valid', {key}) + ); + } + // const isValid = client.isValid(async function(valid) { + // if (!valid) { + // cb(new ValidationError(client), client); + // return; + // } - const updatedClient = await client.updateAttributes(args, myOptions); + // // triggerSave(); + // }, args.data, myOptions); + // client.isValid(client.constructor.validations, client.data, {}); + const updatedClient = await client.updateAttributes(args.data, myOptions); if (tx) await tx.commit(); diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 72b702779..acb2780f8 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -10,18 +10,26 @@ module.exports = Self => { require('./client-methods')(Self); // Validations - + // Self.isValid(function(valid) { + // if (!valid) + // console.error(valid); // hash of errors {attr: [errmessage, errmessage, ...], attr: ...} + // }); Self.validatesPresenceOf('street', { message: 'Street cannot be empty' }); - Self.validatesPresenceOf('city', { - message: 'City cannot be empty' - }); - Self.validatesUniquenessOf('fi', { message: 'TIN must be unique' }); + Self.validatesPresenceOf('fi', { + message: 'fi cannot be empty' + }); + Self.validatesPresenceOf('provinceFk', { + message: 'fi cannot be empty' + }); + Self.validatesPresenceOf('countryFk', { + message: 'countryFk cannot be empty' + }); Self.validatesFormatOf('email', { message: 'Invalid email', From 626c000ebbe97e2480391963a47416dcd3cc2e3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20Segarra=20Mart=C3=ADnez?= Date: Sat, 25 Nov 2023 21:13:50 +0100 Subject: [PATCH 02/26] refs #5878 perf: add translation --- loopback/locale/es.json | 1 + 1 file changed, 1 insertion(+) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 76b0d955c..9a08ef561 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -333,6 +333,7 @@ "fi cannot be empty": "fi cannot be empty", "countryFk cannot be empty": "countryFk cannot be empty", "Model is not valid": "El campo \" {{key}}\" no es válido", + "Property is not defined in this model": "La propiedad que ha modificado no existe", "postcode": "Código postal", "fi": "NIF/CIF", "socialName": "Razón social", From 8b3565d885017cd3d294fa059e736fc315266fd7 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 08:07:19 +0100 Subject: [PATCH 03/26] refs #5878 test: add new tests --- .../methods/client/body_model_validator.js | 3 +- .../client/specs/bodyValidator.spec.js | 284 ++++++++++++++++++ .../client/specs/createWithUser.spec.js | 3 +- modules/client/back/models/client.js | 14 +- 4 files changed, 289 insertions(+), 15 deletions(-) create mode 100644 modules/client/back/methods/client/specs/bodyValidator.spec.js diff --git a/modules/client/back/methods/client/body_model_validator.js b/modules/client/back/methods/client/body_model_validator.js index c451608e6..999c32024 100644 --- a/modules/client/back/methods/client/body_model_validator.js +++ b/modules/client/back/methods/client/body_model_validator.js @@ -6,7 +6,8 @@ const validatorBodyModel = (model, body) => { Object.entries(body).forEach(([key, value]) => { if (!isValid) return; const bodyArg = model.find(m => m.arg === key); - if (!bodyArg) throw new Error('Property is not defined in this model'); + if (!bodyArg) return; + // throw new Error(`Property ${key} is not defined in this model`); const {type} = bodyArg; tag = key; if (tag !== 'any') { diff --git a/modules/client/back/methods/client/specs/bodyValidator.spec.js b/modules/client/back/methods/client/specs/bodyValidator.spec.js new file mode 100644 index 000000000..716597f10 --- /dev/null +++ b/modules/client/back/methods/client/specs/bodyValidator.spec.js @@ -0,0 +1,284 @@ +const validatorBodyModel = require('../body_model_validator'); + +describe('Validation Client Create', () => { + const newAccount = { + userName: 'Deadpool', + email: 'Deadpool@marvel.com', + fi: '16195279J', + name: 'Wade', + socialName: 'DEADPOOL MARVEL', + street: 'WALL STREET', + city: 'New York', + businessTypeFk: 'florist', + provinceFk: 1 + }; + const CLIENT_MODEL = [ + { + arg: 'socialName', + type: 'string' + }, + { + arg: 'fi', + type: 'string' + }, + { + arg: 'street', + type: 'string' + }, + { + arg: 'postcode', + type: 'string' + }, + { + arg: 'city', + type: 'string' + }, + { + arg: 'countryFk', + type: 'number' + }, + { + arg: 'provinceFk', + type: 'number' + }, + { + arg: 'sageTaxTypeFk', + type: 'any' + }, + { + arg: 'sageTransactionTypeFk', + type: 'any' + }, + { + arg: 'transferorFk', + type: 'any' + }, + { + arg: 'hasToInvoiceByAddress', + type: 'boolean' + }, + { + arg: 'hasToInvoice', + type: 'boolean' + }, + { + arg: 'isActive', + type: 'boolean' + }, + { + arg: 'isFreezed', + type: 'boolean' + }, + { + arg: 'isVies', + type: 'boolean' + }, + { + arg: 'isToBeMailed', + type: 'boolean' + }, + { + arg: 'isEqualizated', + type: 'boolean' + }, + { + arg: 'isTaxDataVerified', + type: 'boolean' + }, + { + arg: 'isTaxDataChecked', + type: 'boolean' + }, + { + arg: 'despiteOfClient', + type: 'number' + }, + { + arg: 'hasIncoterms', + type: 'boolean' + }, + { + arg: 'hasElectronicInvoice', + type: 'boolean' + } + ]; + it(`should not find Deadpool as he's not created yet`, async() => { + let isValid = false; + + isValid = validatorBodyModel(CLIENT_MODEL, newAccount).isValid; + + expect(isValid).toBeTrue(); + }); + + it('should create a new account', async() => { + let isValid = false; + + isValid = validatorBodyModel(CLIENT_MODEL, newAccount).isValid; + + expect(isValid).toBeTrue(); + }); + + it('should not be able to create a user if exists', async() => { + let isValid = false; + let error; + + isValid = validatorBodyModel(CLIENT_MODEL, newAccount).isValid; + + expect(isValid).toBeTrue(); + }); +}); +fdescribe('Validation Worker Create', () => { + const defaultWorker = { + // fi: '78457139E', + // name: 'DEFAULTERWORKER', + // firstName: 'DEFAULT', + // lastNames: 'WORKER', + // email: 'defaultWorker@mydomain.com', + // street: 'S/ DEFAULTWORKERSTREET', + // city: 'defaultWorkerCity', + // provinceFk: 1, + // countryFk: 1, + // companyFk: 442, + // postcode: '46680', + // phone: '123456789', + // code: 'DWW', + // bossFk: 9, + // birth: '2022-12-11T23:00:00.000Z', + // payMethodFk: 1, + // roleFk: 1 + }; + const WORKER_MODEL =[ + { + arg: 'fi', + type: 'string', + description: `The worker fi`, + required: true, + }, + { + arg: 'name', + type: 'string', + description: `The user name`, + required: true, + }, + { + arg: 'firstName', + type: 'string', + description: `The worker firstname`, + required: true, + }, + { + arg: 'lastNames', + type: 'string', + description: `The worker lastnames`, + required: true, + }, + { + arg: 'email', + type: 'string', + description: `The worker email`, + required: true, + }, + { + arg: 'street', + type: 'string', + description: `The worker address`, + required: true, + }, + { + arg: 'city', + type: 'string', + description: `The worker city`, + required: true, + }, + { + arg: 'provinceFk', + type: 'number', + description: `The worker province`, + required: true, + }, + { + arg: 'companyFk', + type: 'number', + description: `The worker company`, + required: true, + }, + { + arg: 'postcode', + type: 'string', + description: `The worker postcode`, + required: true, + }, + { + arg: 'phone', + type: 'string', + description: `The worker phone`, + required: true, + }, + { + arg: 'code', + type: 'string', + description: `The worker code`, + required: true, + }, + { + arg: 'bossFk', + type: 'number', + description: `The worker boss`, + required: true, + }, + { + arg: 'birth', + type: 'date', + description: `The worker birth`, + required: true, + }, + { + arg: 'payMethodFk', + type: 'number', + description: `The client payMethod`, + required: true, + }, + { + arg: 'iban', + type: 'string', + description: `The client iban`, + }, + { + arg: 'bankEntityFk', + type: 'number', + description: `The client bank entity`, + } + ]; + + it(`should not find worker as he's not created yet`, async() => { + let isValid = false; + + isValid = validatorBodyModel(WORKER_MODEL, defaultWorker).isValid; + + expect(isValid).toBeTrue(); + }); + + it('should create a new worker', async() => { + let isValid = false; + isValid = validatorBodyModel(WORKER_MODEL, defaultWorker).isValid; + + expect(isValid).toBeTrue(); + }); + + it('should update a new worker', async() => { + let isValid = false; + + isValid = validatorBodyModel(WORKER_MODEL, defaultWorker).isValid; + + expect(isValid).toBeTrue(); + }); + + it('should not be able to create a worker if exists', async() => { + let isValid = false; + let error; + + isValid = validatorBodyModel(WORKER_MODEL, defaultWorker).isValid; + + expect(isValid).toBeTrue(); + }); +}); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 03106acc1..cae38ad8c 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -11,7 +11,8 @@ describe('Client Create', () => { street: 'WALL STREET', city: 'New York', businessTypeFk: 'florist', - provinceFk: 1 + provinceFk: 1, + countryFk: 1 }; beforeAll(async() => { diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index acb2780f8..666f5ed32 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -10,10 +10,7 @@ module.exports = Self => { require('./client-methods')(Self); // Validations - // Self.isValid(function(valid) { - // if (!valid) - // console.error(valid); // hash of errors {attr: [errmessage, errmessage, ...], attr: ...} - // }); + Self.validatesPresenceOf('street', { message: 'Street cannot be empty' }); @@ -21,15 +18,6 @@ module.exports = Self => { Self.validatesUniquenessOf('fi', { message: 'TIN must be unique' }); - Self.validatesPresenceOf('fi', { - message: 'fi cannot be empty' - }); - Self.validatesPresenceOf('provinceFk', { - message: 'fi cannot be empty' - }); - Self.validatesPresenceOf('countryFk', { - message: 'countryFk cannot be empty' - }); Self.validatesFormatOf('email', { message: 'Invalid email', From f8bf2e02dec378af7bfea77c12a5c5b0f479f49e Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 08:12:00 +0100 Subject: [PATCH 04/26] refs #5878 test: fix --- loopback/locale/en.json | 12 +++++++++++- loopback/locale/es.json | 14 ++------------ .../methods/client/specs/createWithUser.spec.js | 3 +-- modules/client/back/models/client.js | 4 ++++ 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 949136459..634c04e03 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -197,5 +197,15 @@ "Booking completed": "Booking complete", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets", - "Try again": "Try again" + "Try again": "Try again", + "Property is not defined in this model": "La propiedad que ha modificado no existe", + "postcode": "Postcode", + "fi": "NIF/CIF", + "socialName": "Social name", + "street":"Street", + "city":"City", + "countryFk":"Country", + "provinceFk":"Province", + "sageTaxTypeFk":"Sage tax type", + "sageTransactionTypeFk":"Sage transaction type" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 9a08ef561..d07071068 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -342,15 +342,5 @@ "countryFk":"País", "provinceFk":"Provincia", "sageTaxTypeFk":"Tipo de impuesto Sage", - "sageTransactionTypeFk":"Tipo de transacción Sage", - "transferorFk":"", - "hasToInvoiceByAddress":"", - "isFreezed":"", - "isVies":"", - "isToBeMailed":"", - "isEqualizated":"", - "isTaxDataVerified":"", - "despiteOfClient":"", - "hasIncoterms":"", - "hasElectronicInvoice":"" -} \ No newline at end of file + "sageTransactionTypeFk":"Tipo de transacción Sage" +} diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index cae38ad8c..03106acc1 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -11,8 +11,7 @@ describe('Client Create', () => { street: 'WALL STREET', city: 'New York', businessTypeFk: 'florist', - provinceFk: 1, - countryFk: 1 + provinceFk: 1 }; beforeAll(async() => { diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 666f5ed32..72b702779 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -15,6 +15,10 @@ module.exports = Self => { message: 'Street cannot be empty' }); + Self.validatesPresenceOf('city', { + message: 'City cannot be empty' + }); + Self.validatesUniquenessOf('fi', { message: 'TIN must be unique' }); From 3822183095f3d8a9761108e785264c8f57160a3a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 10:46:36 +0100 Subject: [PATCH 05/26] refs #5878 test: improve bodyValidator fn --- .../client/specs/bodyValidator.spec.js | 134 +++++++++++++++++- 1 file changed, 132 insertions(+), 2 deletions(-) diff --git a/modules/client/back/methods/client/specs/bodyValidator.spec.js b/modules/client/back/methods/client/specs/bodyValidator.spec.js index 716597f10..f4c84975f 100644 --- a/modules/client/back/methods/client/specs/bodyValidator.spec.js +++ b/modules/client/back/methods/client/specs/bodyValidator.spec.js @@ -1,5 +1,136 @@ +/* eslint-disable jasmine/no-spec-dupes */ const validatorBodyModel = require('../body_model_validator'); +fdescribe('Validation Model', () => { + describe('should be number', () => { + it('success', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'number' + }], {property: 1}); + + expect(isValid).toBeTrue(); + }); + + it('fail', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'number' + + }], {property: null}); + + expect(isValid).toBeFalse(); + }); + }); + + describe('should be string', () => { + it('success as number', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'string' + + }], {property: '1234'}); + + expect(isValid).toBeTrue(); + }); + + it('success as string', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'string' + + }], {property: 'null'}); + + expect(isValid).toBeTrue(); + }); + + it('fail', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'string' + + }], {property: null}); + + expect(isValid).toBeFalse(); + }); + }); + + describe('should be date', () => { + it('success', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'date' + + }], {property: new Date()}); + + expect(isValid).toBeTrue(); + }); + + it('fail', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'date' + + }], {property: null}); + + expect(isValid).toBeFalse(); + }); + }); + + describe('should be boolean', () => { + it('success as true', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'boolean' + + }], {property: true}); + + expect(isValid).toBeTrue(); + }); + + it('success as false', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'boolean' + + }], {property: false}); + + expect(isValid).toBeTrue(); + }); + + it('fail', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'boolean' + + }], {property: null}); + + expect(isValid).toBeFalse(); + }); + }); + + describe('should be any', () => { + it('success', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'any' + + }], {property: '1234'}); + + expect(isValid).toBeTrue(); + }); + + it('fail', () => { + let {isValid} = validatorBodyModel([{ + arg: 'property', + type: 'any' + + }], {property: null}); + + expect(isValid).toBeFalse(); + }); + }); +}); describe('Validation Client Create', () => { const newAccount = { userName: 'Deadpool', @@ -120,7 +251,6 @@ describe('Validation Client Create', () => { it('should not be able to create a user if exists', async() => { let isValid = false; - let error; isValid = validatorBodyModel(CLIENT_MODEL, newAccount).isValid; @@ -147,7 +277,7 @@ fdescribe('Validation Worker Create', () => { // payMethodFk: 1, // roleFk: 1 }; - const WORKER_MODEL =[ + const WORKER_MODEL = [ { arg: 'fi', type: 'string', From 334c5f03a5e5ce83e1da625945891ee510f6f264 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 10:47:49 +0100 Subject: [PATCH 06/26] refs #5878 feat: validate params in supplier model --- .../back/methods/client/updateFiscalData.js | 4 +- .../back/methods/supplier/updateFiscalData.js | 137 ++++++++++-------- 2 files changed, 76 insertions(+), 65 deletions(-) diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index c3b92f6b1..c87eba6be 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -128,9 +128,7 @@ module.exports = Self => { let tx; const myOptions = {}; const models = Self.app.models; - const args = ctx.args; - const userId = ctx.req.accessToken.userId; - const $t = ctx.req.__; + const {args, req: {__: $t}} = ctx; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/supplier/back/methods/supplier/updateFiscalData.js b/modules/supplier/back/methods/supplier/updateFiscalData.js index 271ed8769..c0f0be14c 100644 --- a/modules/supplier/back/methods/supplier/updateFiscalData.js +++ b/modules/supplier/back/methods/supplier/updateFiscalData.js @@ -1,3 +1,65 @@ +const validatorBodyModel = require('../../../../client/back/methods/client/body_model_validator'); + +const BODY_MODEL = [{ + arg: 'name', + type: 'string' +}, +{ + arg: 'nif', + type: 'string' +}, +{ + arg: 'account', + type: 'any' +}, +{ + arg: 'sageTaxTypeFk', + type: 'any' +}, +{ + arg: 'sageWithholdingFk', + type: 'any' +}, +{ + arg: 'sageTransactionTypeFk', + type: 'any' +}, +{ + arg: 'postCode', + type: 'any' +}, +{ + arg: 'street', + type: 'any' +}, +{ + arg: 'city', + type: 'string' +}, +{ + arg: 'provinceFk', + type: 'any' +}, +{ + arg: 'countryFk', + type: 'any' +}, +{ + arg: 'supplierActivityFk', + type: 'string' +}, +{ + arg: 'healthRegister', + type: 'string' +}, +{ + arg: 'isVies', + type: 'boolean' +}, +{ + arg: 'isTrucker', + type: 'boolean' +}]; module.exports = Self => { Self.remoteMethod('updateFiscalData', { description: 'Updates fiscal data of a supplier', @@ -14,65 +76,11 @@ module.exports = Self => { http: {source: 'path'} }, { - arg: 'name', - type: 'string' - }, - { - arg: 'nif', - type: 'string' - }, - { - arg: 'account', - type: 'any' - }, - { - arg: 'sageTaxTypeFk', - type: 'any' - }, - { - arg: 'sageWithholdingFk', - type: 'any' - }, - { - arg: 'sageTransactionTypeFk', - type: 'any' - }, - { - arg: 'postCode', - type: 'any' - }, - { - arg: 'street', - type: 'any' - }, - { - arg: 'city', - type: 'string' - }, - { - arg: 'provinceFk', - type: 'any' - }, - { - arg: 'countryFk', - type: 'any' - }, - { - arg: 'supplierActivityFk', - type: 'string' - }, - { - arg: 'healthRegister', - type: 'string' - }, - { - arg: 'isVies', - type: 'boolean' - }, - { - arg: 'isTrucker', - type: 'boolean' - }], + arg: 'data', + type: 'object', + http: {source: 'body'} + } + ], returns: { arg: 'res', type: 'string', @@ -86,13 +94,18 @@ module.exports = Self => { Self.updateFiscalData = async(ctx, supplierId) => { const models = Self.app.models; - const args = ctx.args; + const {args} = ctx; const supplier = await models.Supplier.findById(supplierId); // Remove unwanted properties delete args.ctx; delete args.id; - - return supplier.updateAttributes(args); + const {isValid, tag} = validatorBodyModel(BODY_MODEL, args.data); + if (!isValid) { + const key = $t(`${tag}`); + throw new Error($t('Model is not valid', {key}) + ); + } + return supplier.updateAttributes(args.data); }; }; From aa5218fb1a2f259aef1bd3a23129a735e44d8ffc Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 15:06:39 +0100 Subject: [PATCH 07/26] refs #5878 feat: supplier translations --- loopback/locale/en.json | 8 +++++++- loopback/locale/es.json | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 634c04e03..90b6f4edd 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -200,12 +200,18 @@ "Try again": "Try again", "Property is not defined in this model": "La propiedad que ha modificado no existe", "postcode": "Postcode", + "postCode": "Postcode", "fi": "NIF/CIF", + "nif": "NIF/CIF", + "Account": "Account", "socialName": "Social name", "street":"Street", "city":"City", "countryFk":"Country", "provinceFk":"Province", + "supplierFk":"Supplier", + "healthRegister":"Health register", "sageTaxTypeFk":"Sage tax type", - "sageTransactionTypeFk":"Sage transaction type" + "sageTransactionTypeFk":"Sage transaction type", + "sageWithholdingFk": "Sage with holding" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index d07071068..6ce4f72bc 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -335,12 +335,18 @@ "Model is not valid": "El campo \" {{key}}\" no es válido", "Property is not defined in this model": "La propiedad que ha modificado no existe", "postcode": "Código postal", + "postCode": "Código postal", "fi": "NIF/CIF", + "nif": "NIF/CIF", + "Account": "Cuenta", "socialName": "Razón social", "street":"Dirección fiscal", "city":"Población", "countryFk":"País", "provinceFk":"Provincia", + "supplierFk":"Actividad del proveedor", + "healthRegister":"Registro sanitario", "sageTaxTypeFk":"Tipo de impuesto Sage", - "sageTransactionTypeFk":"Tipo de transacción Sage" + "sageTransactionTypeFk":"Tipo de transacción Sage", + "sageWithholdingFk" : "Sage con tenencia" } From f09e249348b1fee96cabb7328bf09f1f8e6f98fd Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 15:06:55 +0100 Subject: [PATCH 08/26] refs #5878 feat: remove conditions --- modules/supplier/back/models/supplier.js | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 5cf357c13..fbe74286a 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -17,17 +17,13 @@ module.exports = Self => { message: 'The social name cannot be empty' }); - if (this.city) { - Self.validatesPresenceOf('city', { - message: 'City cannot be empty' - }); - } + Self.validatesPresenceOf('city', { + message: 'City cannot be empty' + }); - if (this.nif) { - Self.validatesPresenceOf('nif', { - message: 'The nif cannot be empty' - }); - } + Self.validatesPresenceOf('nif', { + message: 'The nif cannot be empty' + }); Self.validatesUniquenessOf('nif', { message: 'TIN must be unique' From ce3da6841c9169de93214fbf1996038ccf98fec4 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 27 Nov 2023 15:07:14 +0100 Subject: [PATCH 09/26] refs #5878 feat: new middleware to validate body --- loopback/server/middleware.json | 3 +- loopback/server/middleware/validate-model.js | 33 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 loopback/server/middleware/validate-model.js diff --git a/loopback/server/middleware.json b/loopback/server/middleware.json index 31a2f113b..f06395e89 100644 --- a/loopback/server/middleware.json +++ b/loopback/server/middleware.json @@ -35,11 +35,12 @@ } }, "auth:after": { + "./middleware/validate-model": {}, "./middleware/current-user": {}, "./middleware/salix-version": {} }, "parse": { - "body-parser#json":{} + "body-parser#json":{} }, "routes": { "loopback#rest": { diff --git a/loopback/server/middleware/validate-model.js b/loopback/server/middleware/validate-model.js new file mode 100644 index 000000000..7c1538190 --- /dev/null +++ b/loopback/server/middleware/validate-model.js @@ -0,0 +1,33 @@ +const {models} = require('vn-loopback/server/server'); +const validatorBodyModel = require('../../../modules/client/back/methods/client/body_model_validator'); +const makeSingular = s => { + if (s == null || s.length == 0) + return s; + + return s.substring(0, s.length - 1); +}; +function blobToB64(data) { + return new Uint8Array(data).reduce(function(data, byte) { + return data + String.fromCharCode(byte); + }, ''); +} +module.exports = function(options) { + return function(req, res, next) { + const {method, originalUrl} = req; + if (['GET', 'DELETE'].includes(method)) return next(); + let [module, id, path] = originalUrl.split('api/')[1].split('/'); + + let model = models[module]; + if (!model) { + module = makeSingular(module); + model = models[module]; + } + const properties = model.definition.rawProperties; + const data = JSON.parse(blobToB64(req.readableBuffer.tail.data)); + let isValid = validatorBodyModel(properties, data); + + if (!isValid.isValid) + next(); + return next(); + }; +}; From 0a76b6843fc774112a94a14ca528d162edea11e1 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 29 Nov 2023 15:02:44 +0100 Subject: [PATCH 10/26] refs #5878 feat: approach error-handler middleware --- loopback/locale/es.json | 8 ++++++-- loopback/server/middleware/error-handler.js | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 6ce4f72bc..cf5998e9d 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -334,7 +334,6 @@ "countryFk cannot be empty": "countryFk cannot be empty", "Model is not valid": "El campo \" {{key}}\" no es válido", "Property is not defined in this model": "La propiedad que ha modificado no existe", - "postcode": "Código postal", "postCode": "Código postal", "fi": "NIF/CIF", "nif": "NIF/CIF", @@ -348,5 +347,10 @@ "healthRegister":"Registro sanitario", "sageTaxTypeFk":"Tipo de impuesto Sage", "sageTransactionTypeFk":"Tipo de transacción Sage", - "sageWithholdingFk" : "Sage con tenencia" + "sageWithholdingFk" : "Sage con tenencia", + "Cannot past travels with entries": "No se pueden pasar envíos con entradas", + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", + "Field are invalid": "El campo {{tag}} no es válido", + "postcode": "Código postal" } + diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index 725826ae7..0c53d9e8b 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -1,6 +1,9 @@ const UserError = require('../../util/user-error'); const logToConsole = require('strong-error-handler/lib/logger'); - +const validations = [{ + validation: message => String(message).startsWith('Value is not'), + message: ({__: $t, body}) => $t('Field are invalid', {tag: $t(Object.keys(body)[0])}) +}]; module.exports = function() { return function(err, req, res, next) { // Thrown user errors @@ -10,6 +13,16 @@ module.exports = function() { } // Validation errors + if (err.statusCode == 400) { + try { + validations.forEach(validation => { + err.message = validation.validation(err.message) && validation.message(req); + }); + + return next(err); + } catch (e) { + } + } if (err.statusCode == 422) { try { let code; From e5e97a047f4b993f2ce6d637ac1941406d017419 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 29 Nov 2023 15:03:09 +0100 Subject: [PATCH 11/26] refs #5878 perf: front validations --- front/core/components/watcher/locale/es.yml | 4 +++- front/core/components/watcher/watcher.js | 6 ++++-- loopback/locale/es.json | 5 ++--- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/front/core/components/watcher/locale/es.yml b/front/core/components/watcher/locale/es.yml index 5d25752b4..37113b871 100644 --- a/front/core/components/watcher/locale/es.yml +++ b/front/core/components/watcher/locale/es.yml @@ -1,4 +1,6 @@ Are you sure exit without saving?: ¿Seguro que quieres salir sin guardar? Unsaved changes will be lost: Los cambios que no hayas guardado se perderán No changes to save: No hay cambios que guardar -Some fields are invalid: Algunos campos no son válidos \ No newline at end of file +Field are invalid: El campo {{tag}} no es válido +Some fields are invalid: Algunos campos no son válidos + diff --git a/front/core/components/watcher/watcher.js b/front/core/components/watcher/watcher.js index 8b52be69c..5e3069e02 100644 --- a/front/core/components/watcher/watcher.js +++ b/front/core/components/watcher/watcher.js @@ -317,8 +317,10 @@ export default class Watcher extends Component { * Checks if the form is valid. */ isInvalid() { - if (this.form && this.form.$invalid) - throw new UserError('Some fields are invalid'); + if (this.form && this.form.$invalid) { + const tag = Object.values(this.form.$error)[0][0].$$attr.label; + throw new UserError(this.$t('Field are invalid', {tag: this.$t(tag)})); + } } /** diff --git a/loopback/locale/es.json b/loopback/locale/es.json index cf5998e9d..8a5f4db9f 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -335,6 +335,7 @@ "Model is not valid": "El campo \" {{key}}\" no es válido", "Property is not defined in this model": "La propiedad que ha modificado no existe", "postCode": "Código postal", + "postcode": "Código postal", "fi": "NIF/CIF", "nif": "NIF/CIF", "Account": "Cuenta", @@ -350,7 +351,5 @@ "sageWithholdingFk" : "Sage con tenencia", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", - "Field are invalid": "El campo {{tag}} no es válido", - "postcode": "Código postal" + "Field are invalid": "El campo {{tag}} no es válido" } - From 94147bd2b27b1869dcea72736002a20787fc9bb4 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 11 Dec 2023 07:36:39 +0100 Subject: [PATCH 12/26] refs #5858 feat: handle Error from middleware --- front/core/components/watcher/locale/es.yml | 2 - front/core/components/watcher/watcher.js | 6 +- loopback/locale/es.json | 2 +- loopback/server/middleware.json | 1 - loopback/server/middleware/error-handler.js | 42 +- loopback/server/middleware/validate-model.js | 33 -- .../methods/client/body_model_validator.js | 42 -- .../client/specs/bodyValidator.spec.js | 414 ------------------ .../back/methods/client/updateFiscalData.js | 200 ++++----- .../back/methods/supplier/updateFiscalData.js | 137 +++--- 10 files changed, 195 insertions(+), 684 deletions(-) delete mode 100644 loopback/server/middleware/validate-model.js delete mode 100644 modules/client/back/methods/client/body_model_validator.js delete mode 100644 modules/client/back/methods/client/specs/bodyValidator.spec.js diff --git a/front/core/components/watcher/locale/es.yml b/front/core/components/watcher/locale/es.yml index 37113b871..83553d20d 100644 --- a/front/core/components/watcher/locale/es.yml +++ b/front/core/components/watcher/locale/es.yml @@ -1,6 +1,4 @@ Are you sure exit without saving?: ¿Seguro que quieres salir sin guardar? Unsaved changes will be lost: Los cambios que no hayas guardado se perderán No changes to save: No hay cambios que guardar -Field are invalid: El campo {{tag}} no es válido Some fields are invalid: Algunos campos no son válidos - diff --git a/front/core/components/watcher/watcher.js b/front/core/components/watcher/watcher.js index 5e3069e02..8b52be69c 100644 --- a/front/core/components/watcher/watcher.js +++ b/front/core/components/watcher/watcher.js @@ -317,10 +317,8 @@ export default class Watcher extends Component { * Checks if the form is valid. */ isInvalid() { - if (this.form && this.form.$invalid) { - const tag = Object.values(this.form.$error)[0][0].$$attr.label; - throw new UserError(this.$t('Field are invalid', {tag: this.$t(tag)})); - } + if (this.form && this.form.$invalid) + throw new UserError('Some fields are invalid'); } /** diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 8a5f4db9f..83dc81d77 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -351,5 +351,5 @@ "sageWithholdingFk" : "Sage con tenencia", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", - "Field are invalid": "El campo {{tag}} no es válido" + "Field are invalid": "El campo '{{tag}}' no es válido" } diff --git a/loopback/server/middleware.json b/loopback/server/middleware.json index f06395e89..cfc693217 100644 --- a/loopback/server/middleware.json +++ b/loopback/server/middleware.json @@ -35,7 +35,6 @@ } }, "auth:after": { - "./middleware/validate-model": {}, "./middleware/current-user": {}, "./middleware/salix-version": {} }, diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index 0c53d9e8b..e0d32d209 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -1,8 +1,36 @@ + const UserError = require('../../util/user-error'); const logToConsole = require('strong-error-handler/lib/logger'); const validations = [{ validation: message => String(message).startsWith('Value is not'), - message: ({__: $t, body}) => $t('Field are invalid', {tag: $t(Object.keys(body)[0])}) + message: ({__: $t}, _tag) => + $t('Field are invalid', {tag: $t(_tag)}), + handleError: ({method, originalUrl, body}) => { + const {models} = require('vn-loopback/server/server'); + let tag = null; + try { + let [module, id, path] = originalUrl.split('api/')[1].split('/'); + + let model = models[module]; + if (!model) { + module = module.substring(0, module.length - 1); + model = models[module]; + } + if (!model) throw new UserError(''); + const {accepts} = model.sharedClass.methods().find(method => method.name === path); + for (const [key, value] of Object.entries(body)) { + const accept = accepts.find(acc => acc.arg === key); + if (!value && accept.type !== 'any') { + tag = key; + break; + } + } + return tag; + } catch (error) { + throw new Error(error); + } + } + }]; module.exports = function() { return function(err, req, res, next) { @@ -16,7 +44,17 @@ module.exports = function() { if (err.statusCode == 400) { try { validations.forEach(validation => { - err.message = validation.validation(err.message) && validation.message(req); + if (validation.validation(err.message)) { + const error = validation.handleError(req); + if (error) + err.message = validation.message(req, error); + // const tag = handleNullProperty(req); + // if (tag) { + // const message = validation.message(req); + // } + // const tag = validateModel(req); + // if (tag) validation.message(req); + } }); return next(err); diff --git a/loopback/server/middleware/validate-model.js b/loopback/server/middleware/validate-model.js deleted file mode 100644 index 7c1538190..000000000 --- a/loopback/server/middleware/validate-model.js +++ /dev/null @@ -1,33 +0,0 @@ -const {models} = require('vn-loopback/server/server'); -const validatorBodyModel = require('../../../modules/client/back/methods/client/body_model_validator'); -const makeSingular = s => { - if (s == null || s.length == 0) - return s; - - return s.substring(0, s.length - 1); -}; -function blobToB64(data) { - return new Uint8Array(data).reduce(function(data, byte) { - return data + String.fromCharCode(byte); - }, ''); -} -module.exports = function(options) { - return function(req, res, next) { - const {method, originalUrl} = req; - if (['GET', 'DELETE'].includes(method)) return next(); - let [module, id, path] = originalUrl.split('api/')[1].split('/'); - - let model = models[module]; - if (!model) { - module = makeSingular(module); - model = models[module]; - } - const properties = model.definition.rawProperties; - const data = JSON.parse(blobToB64(req.readableBuffer.tail.data)); - let isValid = validatorBodyModel(properties, data); - - if (!isValid.isValid) - next(); - return next(); - }; -}; diff --git a/modules/client/back/methods/client/body_model_validator.js b/modules/client/back/methods/client/body_model_validator.js deleted file mode 100644 index 999c32024..000000000 --- a/modules/client/back/methods/client/body_model_validator.js +++ /dev/null @@ -1,42 +0,0 @@ - -const isNotNull = value => value !== null && value !== undefined && value !== ''; -const validatorBodyModel = (model, body) => { - let isValid = true; - let tag = null; - Object.entries(body).forEach(([key, value]) => { - if (!isValid) return; - const bodyArg = model.find(m => m.arg === key); - if (!bodyArg) return; - // throw new Error(`Property ${key} is not defined in this model`); - const {type} = bodyArg; - tag = key; - if (tag !== 'any') { - isValid = isNotNull(value); - return; - } - - switch (type) { - case 'number': - isValid = /^[0-9]*$/.test(value); - break; - - case 'boolean': - isValid = value instanceof Boolean; - break; - - case 'date': - isValid = (new Date(date) !== 'Invalid Date') && !isNaN(new Date(date)); - break; - - case 'string': - isValid = typeof value == 'string'; - break; - - default: - break; - } - }); - return {isValid, tag}; -}; - -module.exports = validatorBodyModel; diff --git a/modules/client/back/methods/client/specs/bodyValidator.spec.js b/modules/client/back/methods/client/specs/bodyValidator.spec.js deleted file mode 100644 index f4c84975f..000000000 --- a/modules/client/back/methods/client/specs/bodyValidator.spec.js +++ /dev/null @@ -1,414 +0,0 @@ -/* eslint-disable jasmine/no-spec-dupes */ -const validatorBodyModel = require('../body_model_validator'); -fdescribe('Validation Model', () => { - describe('should be number', () => { - it('success', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'number' - - }], {property: 1}); - - expect(isValid).toBeTrue(); - }); - - it('fail', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'number' - - }], {property: null}); - - expect(isValid).toBeFalse(); - }); - }); - - describe('should be string', () => { - it('success as number', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'string' - - }], {property: '1234'}); - - expect(isValid).toBeTrue(); - }); - - it('success as string', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'string' - - }], {property: 'null'}); - - expect(isValid).toBeTrue(); - }); - - it('fail', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'string' - - }], {property: null}); - - expect(isValid).toBeFalse(); - }); - }); - - describe('should be date', () => { - it('success', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'date' - - }], {property: new Date()}); - - expect(isValid).toBeTrue(); - }); - - it('fail', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'date' - - }], {property: null}); - - expect(isValid).toBeFalse(); - }); - }); - - describe('should be boolean', () => { - it('success as true', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'boolean' - - }], {property: true}); - - expect(isValid).toBeTrue(); - }); - - it('success as false', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'boolean' - - }], {property: false}); - - expect(isValid).toBeTrue(); - }); - - it('fail', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'boolean' - - }], {property: null}); - - expect(isValid).toBeFalse(); - }); - }); - - describe('should be any', () => { - it('success', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'any' - - }], {property: '1234'}); - - expect(isValid).toBeTrue(); - }); - - it('fail', () => { - let {isValid} = validatorBodyModel([{ - arg: 'property', - type: 'any' - - }], {property: null}); - - expect(isValid).toBeFalse(); - }); - }); -}); -describe('Validation Client Create', () => { - const newAccount = { - userName: 'Deadpool', - email: 'Deadpool@marvel.com', - fi: '16195279J', - name: 'Wade', - socialName: 'DEADPOOL MARVEL', - street: 'WALL STREET', - city: 'New York', - businessTypeFk: 'florist', - provinceFk: 1 - }; - const CLIENT_MODEL = [ - { - arg: 'socialName', - type: 'string' - }, - { - arg: 'fi', - type: 'string' - }, - { - arg: 'street', - type: 'string' - }, - { - arg: 'postcode', - type: 'string' - }, - { - arg: 'city', - type: 'string' - }, - { - arg: 'countryFk', - type: 'number' - }, - { - arg: 'provinceFk', - type: 'number' - }, - { - arg: 'sageTaxTypeFk', - type: 'any' - }, - { - arg: 'sageTransactionTypeFk', - type: 'any' - }, - { - arg: 'transferorFk', - type: 'any' - }, - { - arg: 'hasToInvoiceByAddress', - type: 'boolean' - }, - { - arg: 'hasToInvoice', - type: 'boolean' - }, - { - arg: 'isActive', - type: 'boolean' - }, - { - arg: 'isFreezed', - type: 'boolean' - }, - { - arg: 'isVies', - type: 'boolean' - }, - { - arg: 'isToBeMailed', - type: 'boolean' - }, - { - arg: 'isEqualizated', - type: 'boolean' - }, - { - arg: 'isTaxDataVerified', - type: 'boolean' - }, - { - arg: 'isTaxDataChecked', - type: 'boolean' - }, - { - arg: 'despiteOfClient', - type: 'number' - }, - { - arg: 'hasIncoterms', - type: 'boolean' - }, - { - arg: 'hasElectronicInvoice', - type: 'boolean' - } - ]; - it(`should not find Deadpool as he's not created yet`, async() => { - let isValid = false; - - isValid = validatorBodyModel(CLIENT_MODEL, newAccount).isValid; - - expect(isValid).toBeTrue(); - }); - - it('should create a new account', async() => { - let isValid = false; - - isValid = validatorBodyModel(CLIENT_MODEL, newAccount).isValid; - - expect(isValid).toBeTrue(); - }); - - it('should not be able to create a user if exists', async() => { - let isValid = false; - - isValid = validatorBodyModel(CLIENT_MODEL, newAccount).isValid; - - expect(isValid).toBeTrue(); - }); -}); -fdescribe('Validation Worker Create', () => { - const defaultWorker = { - // fi: '78457139E', - // name: 'DEFAULTERWORKER', - // firstName: 'DEFAULT', - // lastNames: 'WORKER', - // email: 'defaultWorker@mydomain.com', - // street: 'S/ DEFAULTWORKERSTREET', - // city: 'defaultWorkerCity', - // provinceFk: 1, - // countryFk: 1, - // companyFk: 442, - // postcode: '46680', - // phone: '123456789', - // code: 'DWW', - // bossFk: 9, - // birth: '2022-12-11T23:00:00.000Z', - // payMethodFk: 1, - // roleFk: 1 - }; - const WORKER_MODEL = [ - { - arg: 'fi', - type: 'string', - description: `The worker fi`, - required: true, - }, - { - arg: 'name', - type: 'string', - description: `The user name`, - required: true, - }, - { - arg: 'firstName', - type: 'string', - description: `The worker firstname`, - required: true, - }, - { - arg: 'lastNames', - type: 'string', - description: `The worker lastnames`, - required: true, - }, - { - arg: 'email', - type: 'string', - description: `The worker email`, - required: true, - }, - { - arg: 'street', - type: 'string', - description: `The worker address`, - required: true, - }, - { - arg: 'city', - type: 'string', - description: `The worker city`, - required: true, - }, - { - arg: 'provinceFk', - type: 'number', - description: `The worker province`, - required: true, - }, - { - arg: 'companyFk', - type: 'number', - description: `The worker company`, - required: true, - }, - { - arg: 'postcode', - type: 'string', - description: `The worker postcode`, - required: true, - }, - { - arg: 'phone', - type: 'string', - description: `The worker phone`, - required: true, - }, - { - arg: 'code', - type: 'string', - description: `The worker code`, - required: true, - }, - { - arg: 'bossFk', - type: 'number', - description: `The worker boss`, - required: true, - }, - { - arg: 'birth', - type: 'date', - description: `The worker birth`, - required: true, - }, - { - arg: 'payMethodFk', - type: 'number', - description: `The client payMethod`, - required: true, - }, - { - arg: 'iban', - type: 'string', - description: `The client iban`, - }, - { - arg: 'bankEntityFk', - type: 'number', - description: `The client bank entity`, - } - ]; - - it(`should not find worker as he's not created yet`, async() => { - let isValid = false; - - isValid = validatorBodyModel(WORKER_MODEL, defaultWorker).isValid; - - expect(isValid).toBeTrue(); - }); - - it('should create a new worker', async() => { - let isValid = false; - isValid = validatorBodyModel(WORKER_MODEL, defaultWorker).isValid; - - expect(isValid).toBeTrue(); - }); - - it('should update a new worker', async() => { - let isValid = false; - - isValid = validatorBodyModel(WORKER_MODEL, defaultWorker).isValid; - - expect(isValid).toBeTrue(); - }); - - it('should not be able to create a worker if exists', async() => { - let isValid = false; - let error; - - isValid = validatorBodyModel(WORKER_MODEL, defaultWorker).isValid; - - expect(isValid).toBeTrue(); - }); -}); diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index c87eba6be..5fd886c32 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -1,95 +1,4 @@ let UserError = require('vn-loopback/util/user-error'); -const validatorBodyModel = require('./body_model_validator'); -const BODY_MODEL = [ - { - arg: 'socialName', - type: 'string' - }, - { - arg: 'fi', - type: 'string' - }, - { - arg: 'street', - type: 'string' - }, - { - arg: 'postcode', - type: 'string' - }, - { - arg: 'city', - type: 'string' - }, - { - arg: 'countryFk', - type: 'number' - }, - { - arg: 'provinceFk', - type: 'number' - }, - { - arg: 'sageTaxTypeFk', - type: 'any' - }, - { - arg: 'sageTransactionTypeFk', - type: 'any' - }, - { - arg: 'transferorFk', - type: 'any' - }, - { - arg: 'hasToInvoiceByAddress', - type: 'boolean' - }, - { - arg: 'hasToInvoice', - type: 'boolean' - }, - { - arg: 'isActive', - type: 'boolean' - }, - { - arg: 'isFreezed', - type: 'boolean' - }, - { - arg: 'isVies', - type: 'boolean' - }, - { - arg: 'isToBeMailed', - type: 'boolean' - }, - { - arg: 'isEqualizated', - type: 'boolean' - }, - { - arg: 'isTaxDataVerified', - type: 'boolean' - }, - { - arg: 'isTaxDataChecked', - type: 'boolean' - }, - { - arg: 'despiteOfClient', - type: 'number' - }, - { - arg: 'hasIncoterms', - type: 'boolean' - }, - { - arg: 'hasElectronicInvoice', - type: 'boolean' - } -]; module.exports = Self => { Self.remoteMethod('updateFiscalData', { @@ -108,9 +17,92 @@ module.exports = Self => { http: {source: 'path'} }, { - arg: 'data', - type: 'object', - http: {source: 'body'} + arg: 'socialName', + type: 'string' + }, + { + arg: 'fi', + type: 'string' + }, + { + arg: 'street', + type: 'string' + }, + { + arg: 'postcode', + type: 'string' + }, + { + arg: 'city', + type: 'string' + }, + { + arg: 'countryFk', + type: 'number' + }, + { + arg: 'provinceFk', + type: 'number' + }, + { + arg: 'sageTaxTypeFk', + type: 'any' + }, + { + arg: 'sageTransactionTypeFk', + type: 'any' + }, + { + arg: 'transferorFk', + type: 'any' + }, + { + arg: 'hasToInvoiceByAddress', + type: 'boolean' + }, + { + arg: 'hasToInvoice', + type: 'boolean' + }, + { + arg: 'isActive', + type: 'boolean' + }, + { + arg: 'isFreezed', + type: 'boolean' + }, + { + arg: 'isVies', + type: 'boolean' + }, + { + arg: 'isToBeMailed', + type: 'boolean' + }, + { + arg: 'isEqualizated', + type: 'boolean' + }, + { + arg: 'isTaxDataVerified', + type: 'boolean' + }, + { + arg: 'isTaxDataChecked', + type: 'boolean' + }, + { + arg: 'despiteOfClient', + type: 'number' + }, + { + arg: 'hasIncoterms', + type: 'boolean' + }, + { + arg: 'hasElectronicInvoice', + type: 'boolean' } ], returns: { @@ -128,7 +120,9 @@ module.exports = Self => { let tx; const myOptions = {}; const models = Self.app.models; - const {args, req: {__: $t}} = ctx; + const args = ctx.args; + const userId = ctx.req.accessToken.userId; + const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); @@ -154,22 +148,8 @@ module.exports = Self => { // Remove unwanted properties delete args.ctx; delete args.id; - const {isValid, tag} = validatorBodyModel(BODY_MODEL, args.data); - if (!isValid) { - const key = $t(`${tag}`); - throw new Error($t('Model is not valid', {key}) - ); - } - // const isValid = client.isValid(async function(valid) { - // if (!valid) { - // cb(new ValidationError(client), client); - // return; - // } - // // triggerSave(); - // }, args.data, myOptions); - // client.isValid(client.constructor.validations, client.data, {}); - const updatedClient = await client.updateAttributes(args.data, myOptions); + const updatedClient = await client.updateAttributes(args, myOptions); if (tx) await tx.commit(); diff --git a/modules/supplier/back/methods/supplier/updateFiscalData.js b/modules/supplier/back/methods/supplier/updateFiscalData.js index c0f0be14c..271ed8769 100644 --- a/modules/supplier/back/methods/supplier/updateFiscalData.js +++ b/modules/supplier/back/methods/supplier/updateFiscalData.js @@ -1,65 +1,3 @@ -const validatorBodyModel = require('../../../../client/back/methods/client/body_model_validator'); - -const BODY_MODEL = [{ - arg: 'name', - type: 'string' -}, -{ - arg: 'nif', - type: 'string' -}, -{ - arg: 'account', - type: 'any' -}, -{ - arg: 'sageTaxTypeFk', - type: 'any' -}, -{ - arg: 'sageWithholdingFk', - type: 'any' -}, -{ - arg: 'sageTransactionTypeFk', - type: 'any' -}, -{ - arg: 'postCode', - type: 'any' -}, -{ - arg: 'street', - type: 'any' -}, -{ - arg: 'city', - type: 'string' -}, -{ - arg: 'provinceFk', - type: 'any' -}, -{ - arg: 'countryFk', - type: 'any' -}, -{ - arg: 'supplierActivityFk', - type: 'string' -}, -{ - arg: 'healthRegister', - type: 'string' -}, -{ - arg: 'isVies', - type: 'boolean' -}, -{ - arg: 'isTrucker', - type: 'boolean' -}]; module.exports = Self => { Self.remoteMethod('updateFiscalData', { description: 'Updates fiscal data of a supplier', @@ -76,11 +14,65 @@ module.exports = Self => { http: {source: 'path'} }, { - arg: 'data', - type: 'object', - http: {source: 'body'} - } - ], + arg: 'name', + type: 'string' + }, + { + arg: 'nif', + type: 'string' + }, + { + arg: 'account', + type: 'any' + }, + { + arg: 'sageTaxTypeFk', + type: 'any' + }, + { + arg: 'sageWithholdingFk', + type: 'any' + }, + { + arg: 'sageTransactionTypeFk', + type: 'any' + }, + { + arg: 'postCode', + type: 'any' + }, + { + arg: 'street', + type: 'any' + }, + { + arg: 'city', + type: 'string' + }, + { + arg: 'provinceFk', + type: 'any' + }, + { + arg: 'countryFk', + type: 'any' + }, + { + arg: 'supplierActivityFk', + type: 'string' + }, + { + arg: 'healthRegister', + type: 'string' + }, + { + arg: 'isVies', + type: 'boolean' + }, + { + arg: 'isTrucker', + type: 'boolean' + }], returns: { arg: 'res', type: 'string', @@ -94,18 +86,13 @@ module.exports = Self => { Self.updateFiscalData = async(ctx, supplierId) => { const models = Self.app.models; - const {args} = ctx; + const args = ctx.args; const supplier = await models.Supplier.findById(supplierId); // Remove unwanted properties delete args.ctx; delete args.id; - const {isValid, tag} = validatorBodyModel(BODY_MODEL, args.data); - if (!isValid) { - const key = $t(`${tag}`); - throw new Error($t('Model is not valid', {key}) - ); - } - return supplier.updateAttributes(args.data); + + return supplier.updateAttributes(args); }; }; From f9ea77fa39f3e26603ea14bf1e54cffb0036bcfe Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 11 Dec 2023 07:38:42 +0100 Subject: [PATCH 13/26] refs #5858 perf: change UserError message --- loopback/server/middleware/error-handler.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index e0d32d209..076122aa0 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -16,7 +16,7 @@ const validations = [{ module = module.substring(0, module.length - 1); model = models[module]; } - if (!model) throw new UserError(''); + if (!model) throw new Error('No matching model found'); const {accepts} = model.sharedClass.methods().find(method => method.name === path); for (const [key, value] of Object.entries(body)) { const accept = accepts.find(acc => acc.arg === key); From c8ca855ba960172ffef6eba0146ee0804be83aa5 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 11 Dec 2023 07:54:37 +0100 Subject: [PATCH 14/26] refs #5858 perf: revert changes --- modules/supplier/back/models/supplier.js | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index fbe74286a..5cf357c13 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -17,13 +17,17 @@ module.exports = Self => { message: 'The social name cannot be empty' }); - Self.validatesPresenceOf('city', { - message: 'City cannot be empty' - }); + if (this.city) { + Self.validatesPresenceOf('city', { + message: 'City cannot be empty' + }); + } - Self.validatesPresenceOf('nif', { - message: 'The nif cannot be empty' - }); + if (this.nif) { + Self.validatesPresenceOf('nif', { + message: 'The nif cannot be empty' + }); + } Self.validatesUniquenessOf('nif', { message: 'TIN must be unique' From fb524e2f14d21946e0954786a2d57b46ba97cfc0 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 14 Dec 2023 11:58:42 +0100 Subject: [PATCH 15/26] refs #5878 perf: handleError --- loopback/locale/es.json | 28 +++++----- loopback/server/middleware/error-handler.js | 57 ++++++++++++++++++--- 2 files changed, 66 insertions(+), 19 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 83dc81d77..b5bf25bcc 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -335,21 +335,23 @@ "Model is not valid": "El campo \" {{key}}\" no es válido", "Property is not defined in this model": "La propiedad que ha modificado no existe", "postCode": "Código postal", - "postcode": "Código postal", + "postcode": "Código postal", "fi": "NIF/CIF", "nif": "NIF/CIF", - "Account": "Cuenta", + "Account": "Cuenta", "socialName": "Razón social", - "street":"Dirección fiscal", - "city":"Población", - "countryFk":"País", - "provinceFk":"Provincia", - "supplierFk":"Actividad del proveedor", - "healthRegister":"Registro sanitario", - "sageTaxTypeFk":"Tipo de impuesto Sage", - "sageTransactionTypeFk":"Tipo de transacción Sage", - "sageWithholdingFk" : "Sage con tenencia", + "street": "Dirección fiscal", + "city": "Población", + "countryFk": "País", + "provinceFk": "Provincia", + "supplierFk": "Actividad del proveedor", + "healthRegister": "Registro sanitario", + "sageTaxTypeFk": "Tipo de impuesto Sage", + "sageTransactionTypeFk": "Tipo de transacción Sage", + "sageWithholdingFk": "Sage con tenencia", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", - "Field are invalid": "El campo '{{tag}}' no es válido" -} + "Field are invalid": "El campo '{{tag}}' no es válido", + "additionalData": "additionalData", + "isToBeMailed": "isToBeMailed" +} \ No newline at end of file diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index 076122aa0..b0b4cb55a 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -1,15 +1,26 @@ const UserError = require('../../util/user-error'); const logToConsole = require('strong-error-handler/lib/logger'); +function isJsonString(str) { + try { + let json = JSON.parse(str); + return (typeof json === 'object'); + } catch (e) { + return false; + } +} const validations = [{ validation: message => String(message).startsWith('Value is not'), message: ({__: $t}, _tag) => $t('Field are invalid', {tag: $t(_tag)}), - handleError: ({method, originalUrl, body}) => { + handleError: ({method: verb, originalUrl, body}) => { const {models} = require('vn-loopback/server/server'); let tag = null; try { - let [module, id, path] = originalUrl.split('api/')[1].split('/'); + let [module, ...path] = originalUrl.split('?')[0].split('api/')[1]; + path = path.join('/'); + // let module = url.split('/')[0]; + // let [id, path] = url.substring(url.indexOf('/') + 1).split('/'); let model = models[module]; if (!model) { @@ -17,12 +28,46 @@ const validations = [{ model = models[module]; } if (!model) throw new Error('No matching model found'); - const {accepts} = model.sharedClass.methods().find(method => method.name === path); + const currentMethod = model.sharedClass.methods().find(method => { + const methodMatch = [method.http].flat().filter(el => el.verb === verb.toLowerCase()); + if (methodMatch.length > 0) { + const http = methodMatch.find(el => el.path.endsWith(path)); + if (http) + return method; + } + } + ); + const {accepts} = currentMethod; for (const [key, value] of Object.entries(body)) { const accept = accepts.find(acc => acc.arg === key); - if (!value && accept.type !== 'any') { - tag = key; - break; + if (accept.type !== 'any') { + let isValid = false; + if (value) { + switch (accept.type) { + case 'object': + isValid = isJsonString(value); + break; + case 'number': + isValid = /^[0-9]*$/.test(value); + break; + + case 'boolean': + isValid = value instanceof Boolean; + break; + + case 'date': + isValid = (new Date(date) !== 'Invalid Date') && !isNaN(new Date(date)); + break; + + case 'string': + isValid = typeof value == 'string'; + break; + } + } + if (!value || !isValid) { + tag = key; + break; + } } } return tag; From 8d5e174a6441736ec3a73e7826650d217a45ffed Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 15 Dec 2023 12:39:48 +0100 Subject: [PATCH 16/26] refs #5878 perf: move validation to other folder --- loopback/server/middleware/error-handler.js | 83 +------------------ loopback/server/middleware/value-is-not.js | 89 +++++++++++++++++++++ 2 files changed, 92 insertions(+), 80 deletions(-) create mode 100644 loopback/server/middleware/value-is-not.js diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index b0b4cb55a..73441f862 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -1,81 +1,10 @@ const UserError = require('../../util/user-error'); const logToConsole = require('strong-error-handler/lib/logger'); -function isJsonString(str) { - try { - let json = JSON.parse(str); - return (typeof json === 'object'); - } catch (e) { - return false; - } -} +const valueIsNot = require('./value-is-not'); + const validations = [{ - validation: message => String(message).startsWith('Value is not'), - message: ({__: $t}, _tag) => - $t('Field are invalid', {tag: $t(_tag)}), - handleError: ({method: verb, originalUrl, body}) => { - const {models} = require('vn-loopback/server/server'); - let tag = null; - try { - let [module, ...path] = originalUrl.split('?')[0].split('api/')[1]; - path = path.join('/'); - // let module = url.split('/')[0]; - // let [id, path] = url.substring(url.indexOf('/') + 1).split('/'); - - let model = models[module]; - if (!model) { - module = module.substring(0, module.length - 1); - model = models[module]; - } - if (!model) throw new Error('No matching model found'); - const currentMethod = model.sharedClass.methods().find(method => { - const methodMatch = [method.http].flat().filter(el => el.verb === verb.toLowerCase()); - if (methodMatch.length > 0) { - const http = methodMatch.find(el => el.path.endsWith(path)); - if (http) - return method; - } - } - ); - const {accepts} = currentMethod; - for (const [key, value] of Object.entries(body)) { - const accept = accepts.find(acc => acc.arg === key); - if (accept.type !== 'any') { - let isValid = false; - if (value) { - switch (accept.type) { - case 'object': - isValid = isJsonString(value); - break; - case 'number': - isValid = /^[0-9]*$/.test(value); - break; - - case 'boolean': - isValid = value instanceof Boolean; - break; - - case 'date': - isValid = (new Date(date) !== 'Invalid Date') && !isNaN(new Date(date)); - break; - - case 'string': - isValid = typeof value == 'string'; - break; - } - } - if (!value || !isValid) { - tag = key; - break; - } - } - } - return tag; - } catch (error) { - throw new Error(error); - } - } - + ...valueIsNot }]; module.exports = function() { return function(err, req, res, next) { @@ -93,12 +22,6 @@ module.exports = function() { const error = validation.handleError(req); if (error) err.message = validation.message(req, error); - // const tag = handleNullProperty(req); - // if (tag) { - // const message = validation.message(req); - // } - // const tag = validateModel(req); - // if (tag) validation.message(req); } }); diff --git a/loopback/server/middleware/value-is-not.js b/loopback/server/middleware/value-is-not.js new file mode 100644 index 000000000..ef2e2513f --- /dev/null +++ b/loopback/server/middleware/value-is-not.js @@ -0,0 +1,89 @@ +module.exports = { + validation: message => String(message).startsWith('Value is not'), + message: ({__: $t}, _tag) => + $t('Field are invalid', {tag: $t(_tag)}), + handleError: ({method: verb, originalUrl, body}) => { + const {models} = require('vn-loopback/server/server'); + let tag = null; + let module = null; + let path = null; + let hasId = false; + try { + if (originalUrl.includes('?')) + originalUrl = originalUrl.split('?')[0]; + + originalUrl = originalUrl.split('api/')[1]; + [module, ...path] = originalUrl.split('/'); + hasId = path.length > 1; + // let module = url.split('/')[0]; + // let [id, path] = url.substring(url.indexOf('/') + 1).split('/'); + + let model = models[module]; + if (!model) { + module = module.substring(0, module.length - 1); + model = models[module]; + } + if (!model) throw new Error('No matching model found'); + const currentMethod = model.sharedClass.methods().find(method => { + const methodMatch = [method.http].flat().find(el => { + let isValid = false; + if (el.verb === verb.toLowerCase()) { + if (hasId) + isValid = el.path.replace(':id', path[0]) === '/' + path.join('/'); + else + isValid = el.path.endsWith(path[0]); + } + return isValid; + }); + if (methodMatch) + return method; + } + ); + const {accepts} = currentMethod; + for (const [key, value] of Object.entries(body)) { + const accept = accepts.find(acc => acc.arg === key); + if (accept.type !== 'any') { + let isValid = false; + if (value) { + switch (accept.type) { + case 'object': + isValid = isJsonString(value); + break; + case 'number': + isValid = /^[0-9]*$/.test(value); + break; + + case 'boolean': + isValid = value instanceof Boolean; + break; + + case 'date': + isValid = (new Date(date) !== 'Invalid Date') && !isNaN(new Date(date)); + break; + + case 'string': + isValid = typeof value == 'string'; + break; + } + } + if (!value || !isValid) { + tag = key; + break; + } + } + } + return tag; + } catch (error) { + throw new Error(error); + } + } + +}; +function isJsonString(str) { + try { + let json = JSON.parse(str); + return (typeof json === 'object'); + } catch (e) { + return false; + } +} From d864dfd899ea56f5a5f19ba2f65de4619cdf6656 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 20 Dec 2023 06:45:40 +0100 Subject: [PATCH 17/26] refs #5878 test: init test --- .../middleware/specs/value-is-not.spec.js | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 loopback/server/middleware/specs/value-is-not.spec.js diff --git a/loopback/server/middleware/specs/value-is-not.spec.js b/loopback/server/middleware/specs/value-is-not.spec.js new file mode 100644 index 000000000..b9d15f2aa --- /dev/null +++ b/loopback/server/middleware/specs/value-is-not.spec.js @@ -0,0 +1,47 @@ +const valueIsNot = require('../value-is-not'); + +fdescribe('Value is not', () => { + const i18n = require('i18n'); + + const userId = 9; + const ctx = { + req: { + + accessToken: {userId: userId}, + headers: {origin: 'http://localhost:5000'}, + } + }; + + it('UpdateFiscalData endpoint', () => { + let messageError = 'Value is not number'; + const tag = 'provinceFk'; + try { + expect(valueIsNot.validation(messageError)).toBeTrue(); + expect(valueIsNot.message(i18n, tag)).toEqual('El campo \'Provincia\' no es válido'); + const data = { + method: 'POST', + originalUrl: 'updateFiscalData', + body: { + [tag]: null + } + }; + const result = valueIsNot.handleError(data); + + expect(result).toEqual(tag); + } catch (error) { + expect(error).toBeDefined(); + } + }); + + describe('OsTicket', () => { + let messageError = 'Value is not number'; + it('sendToSupport endpoint', () => { + try { + expect(valueIsNot.validation(messageError)).toBeTrue(); + expect(valueIsNot.message(ctx, 'provinceFk')).toEqual('El campo "Provincia" no es válido'); + } catch (error) { + expect(error).toBeDefined(); + } + }); + }); +}); From ec9e1e6d430427cafbdf788ce97df600963eb297 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 21 Dec 2023 13:06:32 +0100 Subject: [PATCH 18/26] refs #5878 test: update test --- .../middleware/specs/value-is-not.spec.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/loopback/server/middleware/specs/value-is-not.spec.js b/loopback/server/middleware/specs/value-is-not.spec.js index b9d15f2aa..9382ba14b 100644 --- a/loopback/server/middleware/specs/value-is-not.spec.js +++ b/loopback/server/middleware/specs/value-is-not.spec.js @@ -12,7 +12,7 @@ fdescribe('Value is not', () => { } }; - it('UpdateFiscalData endpoint', () => { + fit('UpdateFiscalData endpoint', () => { let messageError = 'Value is not number'; const tag = 'provinceFk'; try { @@ -20,7 +20,7 @@ fdescribe('Value is not', () => { expect(valueIsNot.message(i18n, tag)).toEqual('El campo \'Provincia\' no es válido'); const data = { method: 'POST', - originalUrl: 'updateFiscalData', + originalUrl: '/api/updateFiscalData', body: { [tag]: null } @@ -34,11 +34,22 @@ fdescribe('Value is not', () => { }); describe('OsTicket', () => { - let messageError = 'Value is not number'; + let messageError = 'Value is not object'; + const tag = 'additionalData'; it('sendToSupport endpoint', () => { try { expect(valueIsNot.validation(messageError)).toBeTrue(); - expect(valueIsNot.message(ctx, 'provinceFk')).toEqual('El campo "Provincia" no es válido'); + expect(valueIsNot.message(i18n, tag)).toEqual(`El campo '${tag}' no es válido`); + const data = { + method: 'POST', + originalUrl: '/api/OsTickets/send-to-support?access_token=DEFAULT_TOKEN', + body: { + [tag]: '{ \'foo\': 42 }' + } + }; + const result = valueIsNot.handleError(data); + + expect(result).toEqual(tag); } catch (error) { expect(error).toBeDefined(); } From d98885192618f066f9e6a769166149fa89c9d13c Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 2 Jan 2024 10:20:47 +0100 Subject: [PATCH 19/26] refs #5878 feat: use back/locale --- loopback/server/middleware/error-handler.js | 2 +- .../middleware/specs/value-is-not.spec.js | 15 ++--- loopback/server/middleware/value-is-not.js | 61 ++++++++++++++----- 3 files changed, 55 insertions(+), 23 deletions(-) diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index 73441f862..954fb1056 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -21,7 +21,7 @@ module.exports = function() { if (validation.validation(err.message)) { const error = validation.handleError(req); if (error) - err.message = validation.message(req, error); + err.message = validation.message(error, req); } }); diff --git a/loopback/server/middleware/specs/value-is-not.spec.js b/loopback/server/middleware/specs/value-is-not.spec.js index 9382ba14b..4d65ddf56 100644 --- a/loopback/server/middleware/specs/value-is-not.spec.js +++ b/loopback/server/middleware/specs/value-is-not.spec.js @@ -17,17 +17,18 @@ fdescribe('Value is not', () => { const tag = 'provinceFk'; try { expect(valueIsNot.validation(messageError)).toBeTrue(); - expect(valueIsNot.message(i18n, tag)).toEqual('El campo \'Provincia\' no es válido'); const data = { - method: 'POST', - originalUrl: '/api/updateFiscalData', + method: 'PATCH', + originalUrl: '/api/supplier/updateFiscalData', body: { [tag]: null - } + }, + __: i18n }; const result = valueIsNot.handleError(data); - expect(result).toEqual(tag); + expect(result.tag).toEqual(tag); + expect(valueIsNot.message(result, i18n)).toEqual('El campo \'provincia\' no es válido'); } catch (error) { expect(error).toBeDefined(); } @@ -39,7 +40,6 @@ fdescribe('Value is not', () => { it('sendToSupport endpoint', () => { try { expect(valueIsNot.validation(messageError)).toBeTrue(); - expect(valueIsNot.message(i18n, tag)).toEqual(`El campo '${tag}' no es válido`); const data = { method: 'POST', originalUrl: '/api/OsTickets/send-to-support?access_token=DEFAULT_TOKEN', @@ -49,7 +49,8 @@ fdescribe('Value is not', () => { }; const result = valueIsNot.handleError(data); - expect(result).toEqual(tag); + expect(result.tag).toEqual(tag); + expect(valueIsNot.message(tag, i18n)).toEqual(`El campo '${tag}' no es válido`); } catch (error) { expect(error).toBeDefined(); } diff --git a/loopback/server/middleware/value-is-not.js b/loopback/server/middleware/value-is-not.js index ef2e2513f..3bd4a65d3 100644 --- a/loopback/server/middleware/value-is-not.js +++ b/loopback/server/middleware/value-is-not.js @@ -1,11 +1,26 @@ +const SLASH = '/'; +const path = require('path'); +const glob = require('glob'); +const modulesPath = `modules/**/back/locale/**/**.yml`; +const pathResolve = path.resolve(modulesPath); +const modelsLocale = glob.sync(pathResolve, {}).map((f, data) => { + const file = require(f); + const model = f.substring(f.indexOf('modules'), f.indexOf('back') - 1).split(SLASH)[1]; + const locale = path.parse(f).base.split('.')[0]; + return [keyMap(model, locale), file.columns]; +} +); +const mapLocale = new Map(modelsLocale); + module.exports = { validation: message => String(message).startsWith('Value is not'), - message: ({__: $t}, _tag) => - $t('Field are invalid', {tag: $t(_tag)}), - handleError: ({method: verb, originalUrl, body}) => { + message: ({tagValue}, {__: $t}) => + $t('Field are invalid', {tag: tagValue}), + handleError: ({method: verb, originalUrl, body, __: $t}) => { const {models} = require('vn-loopback/server/server'); let tag = null; let module = null; + let moduleOriginal = null; let path = null; let hasId = false; try { @@ -13,34 +28,42 @@ module.exports = { originalUrl = originalUrl.split('?')[0]; originalUrl = originalUrl.split('api/')[1]; - [module, ...path] = originalUrl.split('/'); + [module, ...path] = originalUrl.split(SLASH); hasId = path.length > 1; - // let module = url.split('/')[0]; - // let [id, path] = url.substring(url.indexOf('/') + 1).split('/'); + moduleOriginal = module; let model = models[module]; + // Capitalize + if (!model) { + module = module.charAt(0).toUpperCase() + module.slice(1); + model = models[module]; + } + // Singular if (!model) { module = module.substring(0, module.length - 1); model = models[module]; } if (!model) throw new Error('No matching model found'); const currentMethod = model.sharedClass.methods().find(method => { - const methodMatch = [method.http].flat().find(el => { + const methodMatch = [method.http].flat().filter(el => el.verb === verb.toLowerCase()).find(el => { let isValid = false; - if (el.verb === verb.toLowerCase()) { - if (hasId) - isValid = el.path.replace(':id', path[0]) === '/' + path.join('/'); - else - isValid = el.path.endsWith(path[0]); - } + if (hasId) + isValid = el.path.replace(':id', path[0]) === SLASH + path.join(SLASH); + else + isValid = el.path.endsWith(path[0]); return isValid; }); if (methodMatch) return method; } ); + if (!currentMethod) throw new Error('No matching currentMethod found'); const {accepts} = currentMethod; for (const [key, value] of Object.entries(body)) { + if (!value) { + tag = key; + break; + } const accept = accepts.find(acc => acc.arg === key); if (accept.type !== 'any') { let isValid = false; @@ -66,19 +89,27 @@ module.exports = { break; } } - if (!value || !isValid) { + if (!isValid) { tag = key; break; } } } - return tag; + if (tag) { + const tagValue = mapLocale.get(keyMap(moduleOriginal, $t.getLocale()))[tag]; + return {tag, tagValue}; + } } catch (error) { throw new Error(error); } } }; + +function keyMap(model, local, connector = '_') { + return `${model}${connector}${local}`; +} + function isJsonString(str) { try { let json = JSON.parse(str); From d9527a5ec0c5202f2123ee83b71bf09b5bc9b1b9 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 2 Jan 2024 10:46:33 +0100 Subject: [PATCH 20/26] refs #5878 perf: remove bad translations --- back/methods/vn-user/renew-token.js | 1 - loopback/locale/en.json | 18 +----------------- loopback/locale/es.json | 23 +---------------------- 3 files changed, 2 insertions(+), 40 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 194747949..28289aa2e 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -1,4 +1,3 @@ -const UserError = require('vn-loopback/util/user-error'); const {models} = require('vn-loopback/server/server'); const handlePromiseLogout = (Self, {id}, courtesyTime) => { diff --git a/loopback/locale/en.json b/loopback/locale/en.json index a94717b4f..8fc968e74 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -200,22 +200,6 @@ "keepPrice": "keepPrice", "Cannot past travels with entries": "Cannot past travels with entries", "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}", - "Try again": "Try again", - "Property is not defined in this model": "La propiedad que ha modificado no existe", - "postcode": "Postcode", - "postCode": "Postcode", - "fi": "NIF/CIF", - "nif": "NIF/CIF", - "Account": "Account", - "socialName": "Social name", - "street":"Street", - "city":"City", - "countryFk":"Country", - "provinceFk":"Province", - "supplierFk":"Supplier", - "healthRegister":"Health register", - "sageTaxTypeFk":"Sage tax type", - "sageTransactionTypeFk":"Sage transaction type", - "sageWithholdingFk": "Sage with holding" + "Try again": "Try again" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 6c9528193..fad630bbe 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -332,26 +332,5 @@ "provinceFk must be unique": "provinceFk must be unique", "fi cannot be empty": "fi cannot be empty", "countryFk cannot be empty": "countryFk cannot be empty", - "Model is not valid": "El campo \" {{key}}\" no es válido", - "Property is not defined in this model": "La propiedad que ha modificado no existe", - "postCode": "Código postal", - "postcode": "Código postal", - "fi": "NIF/CIF", - "nif": "NIF/CIF", - "Account": "Cuenta", - "socialName": "Razón social", - "street": "Dirección fiscal", - "city": "Población", - "countryFk": "País", - "provinceFk": "Provincia", - "supplierFk": "Actividad del proveedor", - "healthRegister": "Registro sanitario", - "sageTaxTypeFk": "Tipo de impuesto Sage", - "sageTransactionTypeFk": "Tipo de transacción Sage", - "sageWithholdingFk": "Sage con tenencia", - "Cannot past travels with entries": "No se pueden pasar envíos con entradas", - "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", - "Field are invalid": "El campo '{{tag}}' no es válido", - "additionalData": "additionalData", - "isToBeMailed": "isToBeMailed" + "Field are invalid": "El campo '{{tag}}' no es válido" } From 40a269c358e542b3762f7468964bc8e3f5a09400 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jan 2024 07:38:18 +0100 Subject: [PATCH 21/26] refs #5878 perf: handle when locale not founded --- loopback/server/middleware/error-handler.js | 4 +--- loopback/server/middleware/value-is-not.js | 11 +++++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index 954fb1056..94c30597b 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -32,8 +32,7 @@ module.exports = function() { if (err.statusCode == 422) { try { let code; - let messages = err.details.messages; - for (code in messages) break; + let {messages} = err.details; err.message = req.__(messages[code][0]); return next(err); } catch (e) {} @@ -44,7 +43,6 @@ module.exports = function() { return next(new UserError(req.__(err.sqlMessage))); // Logs error to console - let env = process.env.NODE_ENV; let useCustomLogging = env && env != 'development' && (!err.statusCode || err.statusCode >= 500); diff --git a/loopback/server/middleware/value-is-not.js b/loopback/server/middleware/value-is-not.js index 3bd4a65d3..388545a9f 100644 --- a/loopback/server/middleware/value-is-not.js +++ b/loopback/server/middleware/value-is-not.js @@ -1,11 +1,13 @@ const SLASH = '/'; +const MODULES = 'modules'; +const BACK = 'back'; const path = require('path'); const glob = require('glob'); -const modulesPath = `modules/**/back/locale/**/**.yml`; +const modulesPath = `${MODULES}/**/${BACK}/locale/**/**.yml`; const pathResolve = path.resolve(modulesPath); -const modelsLocale = glob.sync(pathResolve, {}).map((f, data) => { +const modelsLocale = glob.sync(pathResolve, {}).map(f => { const file = require(f); - const model = f.substring(f.indexOf('modules'), f.indexOf('back') - 1).split(SLASH)[1]; + const model = f.substring(f.indexOf(MODULES), f.indexOf(BACK) - 1).split(SLASH)[1]; const locale = path.parse(f).base.split('.')[0]; return [keyMap(model, locale), file.columns]; } @@ -96,7 +98,8 @@ module.exports = { } } if (tag) { - const tagValue = mapLocale.get(keyMap(moduleOriginal, $t.getLocale()))[tag]; + let tagValue = mapLocale.get(keyMap(moduleOriginal, $t.getLocale()))[tag]; + if (!tagValue) tagValue = tag; return {tag, tagValue}; } } catch (error) { From 2c91b5b701b8c9550dad694a6176e8075de12a68 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jan 2024 11:53:00 +0100 Subject: [PATCH 22/26] refs #5878 perf: change require file --- loopback/server/middleware/value-is-not.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loopback/server/middleware/value-is-not.js b/loopback/server/middleware/value-is-not.js index 388545a9f..09c4ac7a8 100644 --- a/loopback/server/middleware/value-is-not.js +++ b/loopback/server/middleware/value-is-not.js @@ -12,6 +12,7 @@ const modelsLocale = glob.sync(pathResolve, {}).map(f => { return [keyMap(model, locale), file.columns]; } ); +const {models} = require('vn-loopback/server/server'); const mapLocale = new Map(modelsLocale); module.exports = { @@ -19,7 +20,6 @@ module.exports = { message: ({tagValue}, {__: $t}) => $t('Field are invalid', {tag: tagValue}), handleError: ({method: verb, originalUrl, body, __: $t}) => { - const {models} = require('vn-loopback/server/server'); let tag = null; let module = null; let moduleOriginal = null; From c11bcbebeed90d54de36d06ea215c20dbb2fa521 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 10 Jan 2024 14:51:59 +0100 Subject: [PATCH 23/26] refs #5878 perf: handle when create customer --- loopback/server/middleware/error-handler.js | 14 ++--- loopback/server/middleware/value-invalid.js | 58 +++++++++++++++++++++ loopback/server/middleware/value-is-not.js | 25 ++------- loopback/util/map-locales.js | 23 ++++++++ 4 files changed, 92 insertions(+), 28 deletions(-) create mode 100644 loopback/server/middleware/value-invalid.js create mode 100644 loopback/util/map-locales.js diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index 94c30597b..e274396a6 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -2,10 +2,12 @@ const UserError = require('../../util/user-error'); const logToConsole = require('strong-error-handler/lib/logger'); const valueIsNot = require('./value-is-not'); +const valueInvalid = require('./value-invalid'); -const validations = [{ - ...valueIsNot -}]; +const validations = [ + valueIsNot, + valueInvalid +]; module.exports = function() { return function(err, req, res, next) { // Thrown user errors @@ -15,11 +17,11 @@ module.exports = function() { } // Validation errors - if (err.statusCode == 400) { + if ([400, 422].includes(err.statusCode)) { try { validations.forEach(validation => { if (validation.validation(err.message)) { - const error = validation.handleError(req); + const error = validation.handleError(req, err); if (error) err.message = validation.message(error, req); } @@ -28,8 +30,6 @@ module.exports = function() { return next(err); } catch (e) { } - } - if (err.statusCode == 422) { try { let code; let {messages} = err.details; diff --git a/loopback/server/middleware/value-invalid.js b/loopback/server/middleware/value-invalid.js new file mode 100644 index 000000000..962aa9e1f --- /dev/null +++ b/loopback/server/middleware/value-invalid.js @@ -0,0 +1,58 @@ +const SLASH = '/'; +const $t = require('i18n'); +const {models} = require('vn-loopback/server/server'); +const mapLocale = require('../../util/map-locales'); + + +module.exports = { + validation: message => String(message).includes('is not valid'), + message: ({tagValue}, {__: $t}) => + $t('Field are invalid', {tag: tagValue}), + handleError: ({method: verb, originalUrl, body}, err) => { + let tag = null; + let module = null; + let moduleOriginal = null; + let path = null; + try { + if (originalUrl.includes('?')) + originalUrl = originalUrl.split('?')[0]; + + originalUrl = originalUrl.split('api/')[1]; + [module, ...path] = originalUrl.split(SLASH); + + moduleOriginal = module; + let model = models[module]; + // Capitalize + if (!model) { + module = module.charAt(0).toUpperCase() + module.slice(1); + model = models[module]; + } + // Singular + if (!model) { + module = module.substring(0, module.length - 1); + model = models[module]; + } + if (!model) throw new Error('No matching model found'); + tag = Object.keys(err.details.codes)[0]; + if (tag) { + let tagValue = mapLocale[$t.getLocale()][tag]; + if (!tagValue) tagValue = tag; + return {tag, tagValue}; + } + } catch (error) { + throw new Error(error); + } + } + +}; + + + +function isJsonString(str) { + try { + let json = JSON.parse(str); + return (typeof json === 'object'); + } catch (e) { + return false; + } +} diff --git a/loopback/server/middleware/value-is-not.js b/loopback/server/middleware/value-is-not.js index 09c4ac7a8..021af3fb9 100644 --- a/loopback/server/middleware/value-is-not.js +++ b/loopback/server/middleware/value-is-not.js @@ -1,28 +1,15 @@ const SLASH = '/'; -const MODULES = 'modules'; -const BACK = 'back'; -const path = require('path'); -const glob = require('glob'); -const modulesPath = `${MODULES}/**/${BACK}/locale/**/**.yml`; -const pathResolve = path.resolve(modulesPath); -const modelsLocale = glob.sync(pathResolve, {}).map(f => { - const file = require(f); - const model = f.substring(f.indexOf(MODULES), f.indexOf(BACK) - 1).split(SLASH)[1]; - const locale = path.parse(f).base.split('.')[0]; - return [keyMap(model, locale), file.columns]; -} -); const {models} = require('vn-loopback/server/server'); -const mapLocale = new Map(modelsLocale); +const $t = require('i18n'); +const mapLocale = require('../../util/map-locales'); module.exports = { validation: message => String(message).startsWith('Value is not'), message: ({tagValue}, {__: $t}) => $t('Field are invalid', {tag: tagValue}), - handleError: ({method: verb, originalUrl, body, __: $t}) => { + handleError: ({method: verb, originalUrl, body}) => { let tag = null; let module = null; - let moduleOriginal = null; let path = null; let hasId = false; try { @@ -33,7 +20,6 @@ module.exports = { [module, ...path] = originalUrl.split(SLASH); hasId = path.length > 1; - moduleOriginal = module; let model = models[module]; // Capitalize if (!model) { @@ -98,7 +84,7 @@ module.exports = { } } if (tag) { - let tagValue = mapLocale.get(keyMap(moduleOriginal, $t.getLocale()))[tag]; + let tagValue = mapLocale[$t.getLocale()][tag]; if (!tagValue) tagValue = tag; return {tag, tagValue}; } @@ -109,9 +95,6 @@ module.exports = { }; -function keyMap(model, local, connector = '_') { - return `${model}${connector}${local}`; -} function isJsonString(str) { try { diff --git a/loopback/util/map-locales.js b/loopback/util/map-locales.js new file mode 100644 index 000000000..692de3f23 --- /dev/null +++ b/loopback/util/map-locales.js @@ -0,0 +1,23 @@ +const SLASH = '/'; +const MODULES = 'modules'; +const BACK = 'back'; +const path = require('path'); +const glob = require('glob'); +const modulesPath = `${MODULES}/**/${BACK}/locale/**/**.yml`; +const pathResolve = path.resolve(modulesPath); + +const modelsLocale = glob.sync(pathResolve, {}).reduce((acc, f) => { + const file = require(f); + const model = f.substring(f.indexOf(MODULES), f.indexOf(BACK) - 1).split(SLASH)[1]; + const locale = path.parse(f).base.split('.')[0]; + + if (!acc[locale]) acc[locale] = {}; + acc[locale] = Object.assign(acc[locale], file.columns); + return acc; +}, {} +); +function keyMap(model, local, connector = '_') { + return `${model}${connector}${local}`; +} +module.exports =modelsLocale; + From 0ca0ea804cc0388004cceb2ff0c50b89c797de50 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 15 Jan 2024 10:51:24 +0100 Subject: [PATCH 24/26] refs #5878 feat mapMethods approach --- loopback/server/middleware/error-handler.js | 7 ++++--- loopback/util/map-methods.js | 12 ++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 loopback/util/map-methods.js diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index e274396a6..10c0bc635 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -1,12 +1,13 @@ -const UserError = require('../../util/user-error'); +const UserError = require('vn-loopback/util/user-error'); const logToConsole = require('strong-error-handler/lib/logger'); const valueIsNot = require('./value-is-not'); const valueInvalid = require('./value-invalid'); - +const mapMethods = require('vn-loopback/util/map-methods') const validations = [ valueIsNot, - valueInvalid + valueInvalid, + mapMethods ]; module.exports = function() { return function(err, req, res, next) { diff --git a/loopback/util/map-methods.js b/loopback/util/map-methods.js new file mode 100644 index 000000000..2858cd61d --- /dev/null +++ b/loopback/util/map-methods.js @@ -0,0 +1,12 @@ +const SLASH = '/'; +const MODULES = 'modules'; +const BACK = 'back'; + +const app = require('vn-loopback/server/server'); + +const modelsMethods = app; +function keyMap(model, local, connector = '_') { + return `${model}${connector}${local}`; +} +module.exports = modelsMethods; + From 9a6af6fe835aa6d8672f820cf805fd164e605aff Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 14 Feb 2024 10:13:45 +0100 Subject: [PATCH 25/26] refs #5878 feat: add glob dependency --- package.json | 1 + pnpm-lock.yaml | 22 ++++------------------ 2 files changed, 5 insertions(+), 18 deletions(-) diff --git a/package.json b/package.json index 5970e68fb..ffcd353b2 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "form-data": "^4.0.0", "fs-extra": "^5.0.0", "ftps": "^1.2.0", + "glob": "^10.3.10", "gm": "^1.25.0", "got": "^10.7.0", "helmet": "^3.21.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 221008dd9..291a41fd1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,6 +29,9 @@ dependencies: ftps: specifier: ^1.2.0 version: 1.2.0 + glob: + specifier: ^10.3.10 + version: 10.3.10 gm: specifier: ^1.25.0 version: 1.25.0 @@ -1622,7 +1625,6 @@ packages: strip-ansi-cjs: /strip-ansi@6.0.1 wrap-ansi: 8.1.0 wrap-ansi-cjs: /wrap-ansi@7.0.0 - dev: true /@istanbuljs/load-nyc-config@1.1.0: resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} @@ -1910,7 +1912,6 @@ packages: resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} requiresBuild: true - dev: true optional: true /@puppeteer/browsers@1.9.1: @@ -3024,7 +3025,6 @@ packages: /ansi-regex@6.0.1: resolution: {integrity: sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==} engines: {node: '>=12'} - dev: true /ansi-styles@2.2.1: resolution: {integrity: sha512-kmCevFghRiWM7HB5zTPULl4r9bVFSWjz62MhqizDGUrq2NWuNMQyuv4tHHoKJHs69M/MF64lEcHdYIocrdWQYA==} @@ -3046,7 +3046,6 @@ packages: /ansi-styles@6.2.1: resolution: {integrity: sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==} engines: {node: '>=12'} - dev: true /ansi-wrap@0.1.0: resolution: {integrity: sha512-ZyznvL8k/FZeQHr2T6LzcJ/+vBApDnMNZvfVFy3At0knswWd6rJ3/0Hhmpu8oqa6C92npmozs890sX9Dl6q+Qw==} @@ -5204,7 +5203,6 @@ packages: /eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} - dev: true /ecc-jsbn@0.1.2: resolution: {integrity: sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==} @@ -5263,7 +5261,6 @@ packages: /emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} - dev: true /emojis-list@3.0.0: resolution: {integrity: sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==} @@ -6099,7 +6096,6 @@ packages: dependencies: cross-spawn: 7.0.3 signal-exit: 4.1.0 - dev: true /forever-agent@0.6.1: resolution: {integrity: sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==} @@ -6493,7 +6489,6 @@ packages: minimatch: 9.0.3 minipass: 7.0.4 path-scurry: 1.10.1 - dev: true /glob@3.2.11: resolution: {integrity: sha512-hVb0zwEZwC1FXSKRPFTeOtN7AArJcJlI6ULGLtrstaswKNlrTJqAA+1lYlSUop4vjA423xlBzqfVS3iWGlqJ+g==} @@ -6508,7 +6503,7 @@ packages: fs.realpath: 1.0.0 inflight: 1.0.6 inherits: 2.0.4 - minimatch: 3.0.8 + minimatch: 3.1.2 once: 1.4.0 path-is-absolute: 1.0.1 dev: true @@ -8002,7 +7997,6 @@ packages: '@isaacs/cliui': 8.0.2 optionalDependencies: '@pkgjs/parseargs': 0.11.0 - dev: true /jade@0.26.3: resolution: {integrity: sha512-mkk3vzUHFjzKjpCXeu+IjXeZD+QOTjUUdubgmHtHTDwvAO2ZTkMTTVrapts5CWz3JvJryh/4KWZpjeZrCepZ3A==} @@ -9251,7 +9245,6 @@ packages: /lru-cache@10.2.0: resolution: {integrity: sha512-2bIM8x+VAf6JT4bKAljS1qUWgMsqZRPGJS6FSahIMPVvctcNhyVp7AJu7quxOW9jwkryBReKZY5tY5JYv2n/7Q==} engines: {node: 14 || >=16.14} - dev: true /lru-cache@2.7.3: resolution: {integrity: sha512-WpibWJ60c3AgAz8a2iYErDrcT2C7OmKnsWhIcHOjkUHFjkXncJhtLxNSqUmxRxRunpb5I8Vprd7aNSd2NtksJQ==} @@ -9657,7 +9650,6 @@ packages: engines: {node: '>=16 || 14 >=14.17'} dependencies: brace-expansion: 2.0.1 - dev: true /minimist-options@4.1.0: resolution: {integrity: sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A==} @@ -9747,7 +9739,6 @@ packages: /minipass@7.0.4: resolution: {integrity: sha512-jYofLM5Dam9279rdkWzqHozUo4ybjdZmCsDHePy5V/PbBcVMiSZR97gmAy45aqi8CK1lG2ECd356FU86avfwUQ==} engines: {node: '>=16 || 14 >=14.17'} - dev: true /minizlib@1.3.3: resolution: {integrity: sha512-6ZYMOEnmVsdCeTJVE0W9ZD+pVnE8h9Hma/iOwwRDsdQoePpoX56/8B6z3P9VNwppJuBKNRuFDRNRqRWexT9G9Q==} @@ -10843,7 +10834,6 @@ packages: dependencies: lru-cache: 10.2.0 minipass: 7.0.4 - dev: true /path-to-regexp@0.1.7: resolution: {integrity: sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==} @@ -12166,7 +12156,6 @@ packages: /signal-exit@4.1.0: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} - dev: true /simple-concat@1.0.1: resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} @@ -12623,7 +12612,6 @@ packages: eastasianwidth: 0.2.0 emoji-regex: 9.2.2 strip-ansi: 7.1.0 - dev: true /string_decoder@0.10.31: resolution: {integrity: sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==} @@ -12670,7 +12658,6 @@ packages: engines: {node: '>=12'} dependencies: ansi-regex: 6.0.1 - dev: true /strip-bom@2.0.0: resolution: {integrity: sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==} @@ -14164,7 +14151,6 @@ packages: ansi-styles: 6.2.1 string-width: 5.1.2 strip-ansi: 7.1.0 - dev: true /wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} From 5918c14d41259e9989b63c8a36f0e23612cf5d69 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 14 Feb 2024 10:14:54 +0100 Subject: [PATCH 26/26] refs #5878 feat: replace by any --- modules/client/back/methods/client/updateFiscalData.js | 10 +++++----- .../supplier/back/methods/supplier/updateFiscalData.js | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 5fd886c32..6ef9f0b38 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -26,11 +26,11 @@ module.exports = Self => { }, { arg: 'street', - type: 'string' + type: 'any' }, { arg: 'postcode', - type: 'string' + type: 'any' }, { arg: 'city', @@ -38,11 +38,11 @@ module.exports = Self => { }, { arg: 'countryFk', - type: 'number' + type: 'any' }, { arg: 'provinceFk', - type: 'number' + type: 'any' }, { arg: 'sageTaxTypeFk', @@ -94,7 +94,7 @@ module.exports = Self => { }, { arg: 'despiteOfClient', - type: 'number' + type: 'any' }, { arg: 'hasIncoterms', diff --git a/modules/supplier/back/methods/supplier/updateFiscalData.js b/modules/supplier/back/methods/supplier/updateFiscalData.js index c0b860983..713b97cd4 100644 --- a/modules/supplier/back/methods/supplier/updateFiscalData.js +++ b/modules/supplier/back/methods/supplier/updateFiscalData.js @@ -46,10 +46,10 @@ module.exports = Self => { type: 'any' }, { arg: 'supplierActivityFk', - type: 'string' + type: 'any' }, { arg: 'healthRegister', - type: 'string' + type: 'any' }, { arg: 'isVies', type: 'boolean'