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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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/78] 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 7ea1fbfb260184dbb9fcf5c7c0ceedb82c04f814 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 18 Jan 2024 15:09:52 +0100 Subject: [PATCH 25/78] refs #5509 feat: entryDms funcionality --- db/changes/240401/00-entryDms.sql | 87 +++++++++++++++++++ db/dump/fixtures.sql | 10 ++- .../back/methods/entry-dms/removeFile.js | 53 +++++++++++ .../back/methods/entry-dms/uploadFile.js | 86 ++++++++++++++++++ modules/entry/back/models/entry-dms.js | 11 +++ modules/entry/back/models/entry-dms.json | 28 ++++++ 6 files changed, 273 insertions(+), 2 deletions(-) create mode 100644 db/changes/240401/00-entryDms.sql create mode 100644 modules/entry/back/methods/entry-dms/removeFile.js create mode 100644 modules/entry/back/methods/entry-dms/uploadFile.js create mode 100644 modules/entry/back/models/entry-dms.js create mode 100644 modules/entry/back/models/entry-dms.json diff --git a/db/changes/240401/00-entryDms.sql b/db/changes/240401/00-entryDms.sql new file mode 100644 index 000000000..5dab74de9 --- /dev/null +++ b/db/changes/240401/00-entryDms.sql @@ -0,0 +1,87 @@ +CREATE OR REPLACE TABLE `vn`.`entryDms` ( + `entryFk` int(11) NOT NULL, + `dmsFk` int(11) NOT NULL, + `editorFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`entryFk`,`dmsFk`), + KEY `gestdoc_id` (`dmsFk`), + KEY `entryDms_editor` (`editorFk`), + CONSTRAINT `entryDms_dms` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `entryDms_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), + CONSTRAINT `entryDms_entry` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +DROP TRIGGER IF EXISTS `vn`.`entryDms_beforeInsert`; +USE `vn`; + +DELIMITER $$ +$$ +CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_beforeInsert` + BEFORE INSERT ON `entryDms` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS `vn`.`entryDms_beforeUpdate`; +USE `vn`; + +DELIMITER $$ +$$ +CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_beforeUpdate` + BEFORE UPDATE ON `entryDms` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS `vn`.`entryDms_beforeDelete`; +USE `vn`; + +DELIMITER $$ +$$ +CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_beforeDelete` + BEFORE DELETE ON `entryDms` + FOR EACH ROW +BEGIN + UPDATE dms + SET dmsTypeFk = (SELECT id + FROM dmsType + WHERE `code` = 'trash' + ) + WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) + FROM entryDms + WHERE dmsFk = OLD.dmsFk + ) ; +END $$ +DELIMITER ; + +DROP TRIGGER IF EXISTS `vn`.`entryDms_afterDelete`; +USE `vn`; + +DELIMITER $$ +$$ +CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_afterDelete` + AFTER DELETE ON `entryDms` + FOR EACH ROW +BEGIN + INSERT INTO entryLog + SET `action` = 'delete', + `changedModel` = 'entryDms', + `changedModelId` = OLD.entryFk, + `userFk` = account.myUser_getId(); +END $$ +DELIMITER ; + + +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('WorkerDms', '*', '*', 'ALLOW', 'ROLE', 'employee'), + ('EntryDms', '*', '*', 'ALLOW', 'ROLE', 'employee'), + ('Entry', 'uploadFile', 'WRITE', 'ALLOW', 'ROLE', 'employee'); + +UPDATE `salix`.`ACL` + SET accessType = '*' + WHERE model = 'ClientDms' + AND property = '*'; diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index b243692bb..b962abfed 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2387,7 +2387,8 @@ INSERT INTO `vn`.`dmsType`(`id`, `name`, `path`, `readRoleFk`, `writeRoleFk`, `c (17, 'cmr', 'cmr', NULL, NULL, 'cmr'), (18, 'dua', 'dua', NULL, NULL, 'dua'), (19, 'inmovilizado', 'inmovilizado', NULL, NULL, 'fixedAssets'), - (20, 'Reclamación', 'reclamacion', 1, 1, 'claim'); + (20, 'Reclamación', 'reclamacion', 1, 1, 'claim'), + (21, 'Entrada', 'entrada', 1, 1, 'entry'); INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `warehouseFk`, `companyFk`, `hardCopyNumber`, `hasFile`, `reference`, `description`, `created`) VALUES @@ -2398,7 +2399,8 @@ INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `wa (5, 5, '5.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'travel: 1', 'dmsForThermograph', util.VN_CURDATE()), (6, 5, '6.txt', 'text/plain', 5, 1, 442, NULL, TRUE, 'NotExists', 'DoesNotExists', util.VN_CURDATE()), (7, 20, '7.jpg', 'image/jpeg', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()), - (8, 20, '8.mp4', 'video/mp4', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()); + (8, 20, '8.mp4', 'video/mp4', 9, 1, 442, NULL, FALSE, '1', 'TICKET ID DEL CLIENTE BRUCE WAYNE ID 1101', util.VN_CURDATE()), + (9, 21, '7.jpg', 'image/jpeg', 9, 1, 442, NULL, FALSE, '1', 'ENTRADA ID 1', util.VN_CURDATE()); INSERT INTO `vn`.`claimDms`(`claimFk`, `dmsFk`) VALUES @@ -3043,3 +3045,7 @@ INSERT INTO `vn`.`clientSms` (`id`, `clientFk`, `smsFk`, `ticketFk`) (4, 1103, 4, 32), (13, 1101, 1, NULL), (14, 1101, 4, 27); + +INSERT INTO `vn`.`entryDms`(`entryFk`, `dmsFk`, `editorFk`) + VALUES + (1, 9, 9); diff --git a/modules/entry/back/methods/entry-dms/removeFile.js b/modules/entry/back/methods/entry-dms/removeFile.js new file mode 100644 index 000000000..677e627a6 --- /dev/null +++ b/modules/entry/back/methods/entry-dms/removeFile.js @@ -0,0 +1,53 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('removeFile', { + description: 'Removes a claim document', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'number', + description: 'The document id', + http: {source: 'path'} + }, + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/removeFile`, + verb: 'POST' + } + }); + + Self.removeFile = async(ctx, id, options) => { + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const targetEntryDms = await Self.findById(id, null, myOptions); + const targetDms = await Self.app.models.Dms.removeFile(ctx, targetEntryDms.dmsFk, myOptions); + + if (!targetDms || ! targetEntryDms) + throw new UserError('Try again'); + + const entryDmsDestroyed = await targetEntryDms.destroy(myOptions); + + if (tx) await tx.commit(); + + return entryDmsDestroyed; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; + diff --git a/modules/entry/back/methods/entry-dms/uploadFile.js b/modules/entry/back/methods/entry-dms/uploadFile.js new file mode 100644 index 000000000..fe0cfab5f --- /dev/null +++ b/modules/entry/back/methods/entry-dms/uploadFile.js @@ -0,0 +1,86 @@ + +module.exports = Self => { + Self.remoteMethodCtx('uploadFile', { + description: 'Upload and attach a file', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + description: 'The claim id', + http: {source: 'path'} + }, + { + arg: 'warehouseId', + type: 'number', + description: 'The warehouse id', + required: true + }, + { + arg: 'companyId', + type: 'number', + description: 'The company id', + required: true + }, + { + arg: 'dmsTypeId', + type: 'number', + description: 'The dms type id', + required: true + }, + { + arg: 'reference', + type: 'string', + required: true + }, + { + arg: 'description', + type: 'string', + required: true + }, + { + arg: 'hasFile', + type: 'boolean', + description: 'True if has an attached file', + required: true + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/uploadFile`, + verb: 'POST' + } + }); + + Self.uploadFile = async(ctx, id, options) => { + const {Dms, EntryDms} = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const uploadedFiles = await Dms.uploadFile(ctx, myOptions); + + const promises = uploadedFiles.map(dms => EntryDms.create({ + entryFk: id, + dmsFk: dms.id + }, myOptions)); + await Promise.all(promises); + + if (tx) await tx.commit(); + + return uploadedFiles; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/entry/back/models/entry-dms.js b/modules/entry/back/models/entry-dms.js new file mode 100644 index 000000000..b00337968 --- /dev/null +++ b/modules/entry/back/models/entry-dms.js @@ -0,0 +1,11 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + require('../methods/entry-dms/removeFile')(Self); + + Self.rewriteDbError(function(err) { + if (err.code === 'ER_DUP_ENTRY') + return new UserError('This document already exists on this entry'); + return err; + }); +}; diff --git a/modules/entry/back/models/entry-dms.json b/modules/entry/back/models/entry-dms.json new file mode 100644 index 000000000..c43443c85 --- /dev/null +++ b/modules/entry/back/models/entry-dms.json @@ -0,0 +1,28 @@ +{ + "name": "EntryDms", + "base": "Loggable", + "options": { + "mysql": { + "table": "entryDms" + } + }, + "properties": { + "dmsFk": { + "type": "number", + "id": true, + "required": true + } + }, + "relations": { + "entry": { + "type": "belongsTo", + "model": "Entry", + "foreignKey": "entryFk" + }, + "dms": { + "type": "belongsTo", + "model": "Dms", + "foreignKey": "dmsFk" + } + } +} From f4dc596e97f40b0149c6e18a03f8c7012c34b743 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 29 Jan 2024 15:13:56 +0100 Subject: [PATCH 26/78] refs 5509 feat: add triggers, downloadFile --- .../vn/triggers/entryDms_afterDelete.sql | 12 ++++ .../vn/triggers/entryDms_beforeInsert.sql | 8 +++ .../vn/triggers/entryDms_beforeUpdate.sql | 8 +++ loopback/locale/es.json | 5 +- loopback/server/datasources.json | 14 +++++ .../back/methods/entry-dms/downloadFile.js | 59 +++++++++++++++++++ modules/entry/back/model-config.json | 3 + .../entry/back/models/entry-container.json | 10 ++++ 8 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 db/routines/vn/triggers/entryDms_afterDelete.sql create mode 100644 db/routines/vn/triggers/entryDms_beforeInsert.sql create mode 100644 db/routines/vn/triggers/entryDms_beforeUpdate.sql create mode 100644 modules/entry/back/methods/entry-dms/downloadFile.js create mode 100644 modules/entry/back/models/entry-container.json diff --git a/db/routines/vn/triggers/entryDms_afterDelete.sql b/db/routines/vn/triggers/entryDms_afterDelete.sql new file mode 100644 index 000000000..9ae8e7058 --- /dev/null +++ b/db/routines/vn/triggers/entryDms_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_afterDelete` + AFTER DELETE ON `entryDms` + FOR EACH ROW +BEGIN + INSERT INTO entryLog + SET `action` = 'delete', + `changedModel` = 'EntryDms', + `changedModelId` = OLD.entryFk, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/entryDms_beforeInsert.sql b/db/routines/vn/triggers/entryDms_beforeInsert.sql new file mode 100644 index 000000000..4f9550f48 --- /dev/null +++ b/db/routines/vn/triggers/entryDms_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_beforeInsert` + BEFORE INSERT ON `entryDms` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/entryDms_beforeUpdate.sql b/db/routines/vn/triggers/entryDms_beforeUpdate.sql new file mode 100644 index 000000000..ecc047029 --- /dev/null +++ b/db/routines/vn/triggers/entryDms_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_beforeUpdate` + BEFORE UPDATE ON `entryDms` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 5555ef8b0..8ee683e62 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -72,7 +72,7 @@ "The secret can't be blank": "La contraseña no puede estar en blanco", "We weren't able to send this SMS": "No hemos podido enviar el SMS", "This client can't be invoiced": "Este cliente no puede ser facturado", - "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", + "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", "This ticket can't be invoiced": "Este ticket no puede ser facturado", "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", "This ticket can not be modified": "Este ticket no puede ser modificado", @@ -336,5 +336,6 @@ "Incorrect pin": "Pin incorrecto.", "You already have the mailAlias": "Ya tienes este alias de correo", "The alias cant be modified": "Este alias de correo no puede ser modificado", - "No tickets to invoice": "No hay tickets para facturar" + "No tickets to invoice": "No hay tickets para facturar", + "this warehouse has not dms": "El Almacén no acepta documentos" } diff --git a/loopback/server/datasources.json b/loopback/server/datasources.json index aadee048c..608479b4b 100644 --- a/loopback/server/datasources.json +++ b/loopback/server/datasources.json @@ -103,6 +103,20 @@ "video/mp4" ] }, + "entryStorage": { + "name": "entryStorage", + "connector": "loopback-component-storage", + "provider": "filesystem", + "root": "./storage/dms", + "maxFileSize": "31457280", + "allowedContentTypes": [ + "image/png", + "image/jpeg", + "image/jpg", + "image/webp", + "video/mp4" + ] + }, "accessStorage": { "name": "accessStorage", "connector": "loopback-component-storage", diff --git a/modules/entry/back/methods/entry-dms/downloadFile.js b/modules/entry/back/methods/entry-dms/downloadFile.js new file mode 100644 index 000000000..a4f10f9dc --- /dev/null +++ b/modules/entry/back/methods/entry-dms/downloadFile.js @@ -0,0 +1,59 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('downloadFile', { + description: 'Get the entry file', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'Number', + description: 'The document id', + http: {source: 'path'} + } + ], + returns: [ + { + arg: 'body', + type: 'file', + root: true + }, + { + arg: 'Content-Type', + type: 'String', + http: {target: 'header'} + }, + { + arg: 'Content-Disposition', + type: 'String', + http: {target: 'header'} + } + ], + http: { + path: `/:id/downloadFile`, + verb: 'GET' + } + }); + + Self.downloadFile = async function(ctx, id) { + const models = Self.app.models; + const EntryContainer = models.EntryContainer; + const dms = await models.Dms.findById(id); + const pathHash = EntryContainer.getHash(dms.id); + try { + await EntryContainer.getFile(pathHash, dms.file); + } catch (e) { + if (e.code != 'ENOENT') + throw e; + + const error = new UserError(`File doesn't exists`); + error.statusCode = 404; + + throw error; + } + + const stream = EntryContainer.downloadStream(pathHash, dms.file); + + return [stream, dms.contentType, `filename="${dms.file}"`]; + }; +}; diff --git a/modules/entry/back/model-config.json b/modules/entry/back/model-config.json index ca4472c8c..d6736052b 100644 --- a/modules/entry/back/model-config.json +++ b/modules/entry/back/model-config.json @@ -2,6 +2,9 @@ "Entry": { "dataSource": "vn" }, + "EntryContainer": { + "dataSource": "entryStorage" + }, "Buy": { "dataSource": "vn" }, diff --git a/modules/entry/back/models/entry-container.json b/modules/entry/back/models/entry-container.json new file mode 100644 index 000000000..a60c272fa --- /dev/null +++ b/modules/entry/back/models/entry-container.json @@ -0,0 +1,10 @@ +{ + "name": "EntryContainer", + "base": "Container", + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} From b54827a2ad86ee499bba5d3a54d04363aa45fae0 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 8 Feb 2024 07:23:42 +0100 Subject: [PATCH 27/78] refs #5509 feat(EntryDms): add download & upload file --- modules/entry/back/model-config.json | 3 +++ modules/entry/back/models/entry-dms.js | 2 ++ modules/entry/back/models/entry-dms.json | 5 ++++- 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/modules/entry/back/model-config.json b/modules/entry/back/model-config.json index d6736052b..7b6e23685 100644 --- a/modules/entry/back/model-config.json +++ b/modules/entry/back/model-config.json @@ -2,6 +2,9 @@ "Entry": { "dataSource": "vn" }, + "EntryDms": { + "dataSource": "vn" + }, "EntryContainer": { "dataSource": "entryStorage" }, diff --git a/modules/entry/back/models/entry-dms.js b/modules/entry/back/models/entry-dms.js index b00337968..219f4fcf5 100644 --- a/modules/entry/back/models/entry-dms.js +++ b/modules/entry/back/models/entry-dms.js @@ -2,6 +2,8 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { require('../methods/entry-dms/removeFile')(Self); + require('../methods/entry-dms/downloadFile')(Self); + require('../methods/entry-dms/uploadFile')(Self); Self.rewriteDbError(function(err) { if (err.code === 'ER_DUP_ENTRY') diff --git a/modules/entry/back/models/entry-dms.json b/modules/entry/back/models/entry-dms.json index c43443c85..5bb3194c2 100644 --- a/modules/entry/back/models/entry-dms.json +++ b/modules/entry/back/models/entry-dms.json @@ -1,6 +1,9 @@ { "name": "EntryDms", - "base": "Loggable", + "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "entryDms" From 5f60f2a00e5ad227541c9682386223c828e7787f Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 12 Feb 2024 15:04:49 +0100 Subject: [PATCH 28/78] refs #5509 feat(EntryDms): add fixtures --- db/dump/fixtures.before.sql | 3 +- db/versions/10841-orangeGalax/00-entryDms.sql | 73 +------------------ .../10841-orangeGalax/00-entryDmsType.vn.sql | 2 + 3 files changed, 8 insertions(+), 70 deletions(-) create mode 100644 db/versions/10841-orangeGalax/00-entryDmsType.vn.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 0b0e53612..66cb59e9d 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -2408,7 +2408,8 @@ INSERT INTO `vn`.`dmsType`(`id`, `name`, `readRoleFk`, `writeRoleFk`, `code`) (17, 'cmr', NULL, NULL, 'cmr'), (18, 'dua', NULL, NULL, 'dua'), (19, 'inmovilizado', NULL, NULL, 'fixedAssets'), - (20, 'Reclamación', 1, 1, 'claim'); + (20, 'Reclamación', 1, 1, 'claim'), + (21, 'Entrada', 1, 1, 'entry'); INSERT INTO `vn`.`dms`(`id`, `dmsTypeFk`, `file`, `contentType`, `workerFk`, `warehouseFk`, `companyFk`, `hardCopyNumber`, `hasFile`, `reference`, `description`, `created`) VALUES diff --git a/db/versions/10841-orangeGalax/00-entryDms.sql b/db/versions/10841-orangeGalax/00-entryDms.sql index 2d078d255..d8c495d6d 100644 --- a/db/versions/10841-orangeGalax/00-entryDms.sql +++ b/db/versions/10841-orangeGalax/00-entryDms.sql @@ -10,78 +10,13 @@ CREATE OR REPLACE TABLE `vn`.`entryDms` ( CONSTRAINT `entryDms_entry` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; --- DROP TRIGGER IF EXISTS `vn`.`entryDms_beforeInsert`; --- USE `vn`; - --- DELIMITER $$ --- $$ --- CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_beforeInsert` --- BEFORE INSERT ON `entryDms` --- FOR EACH ROW --- BEGIN --- SET NEW.editorFk = account.myUser_getId(); --- END $$ --- DELIMITER ; - --- DROP TRIGGER IF EXISTS `vn`.`entryDms_beforeUpdate`; --- USE `vn`; - --- DELIMITER $$ --- $$ --- CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_beforeUpdate` --- BEFORE UPDATE ON `entryDms` --- FOR EACH ROW --- BEGIN --- SET NEW.editorFk = account.myUser_getId(); --- END $$ --- DELIMITER ; - --- DROP TRIGGER IF EXISTS `vn`.`entryDms_beforeDelete`; --- USE `vn`; - --- DELIMITER $$ --- $$ --- CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_beforeDelete` --- BEFORE DELETE ON `entryDms` --- FOR EACH ROW --- BEGIN --- UPDATE dms --- SET dmsTypeFk = (SELECT id --- FROM dmsType --- WHERE `code` = 'trash' --- ) --- WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) --- FROM entryDms --- WHERE dmsFk = OLD.dmsFk --- ) ; --- END $$ --- DELIMITER ; - --- DROP TRIGGER IF EXISTS `vn`.`entryDms_afterDelete`; --- USE `vn`; - --- DELIMITER $$ --- $$ --- CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`entryDms_afterDelete` --- AFTER DELETE ON `entryDms` --- FOR EACH ROW --- BEGIN --- INSERT INTO entryLog --- SET `action` = 'delete', --- `changedModel` = 'entryDms', --- `changedModelId` = OLD.entryFk, --- `userFk` = account.myUser_getId(); --- END $$ --- DELIMITER ; - - INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('WorkerDms', '*', '*', 'ALLOW', 'ROLE', 'employee'), ('EntryDms', '*', '*', 'ALLOW', 'ROLE', 'employee'), ('Entry', 'uploadFile', 'WRITE', 'ALLOW', 'ROLE', 'employee'); --- UPDATE `salix`.`ACL` --- SET accessType = '*' --- WHERE model = 'ClientDms' --- AND property = '*'; +UPDATE `salix`.`ACL` + SET accessType = '*' + WHERE model = 'ClientDms' + AND property = '*'; diff --git a/db/versions/10841-orangeGalax/00-entryDmsType.vn.sql b/db/versions/10841-orangeGalax/00-entryDmsType.vn.sql new file mode 100644 index 000000000..d408ab827 --- /dev/null +++ b/db/versions/10841-orangeGalax/00-entryDmsType.vn.sql @@ -0,0 +1,2 @@ +INSERT INTO `vn`.`dmsType` (code, name, path__, writeRoleFk, readRoleFk, monthToDelete) + VALUES('entry', 'Entrada', '', 1, 1, NULL); From 35df439f14f61e22b6acfbf30ea9ffee2893faf7 Mon Sep 17 00:00:00 2001 From: josepd Date: Tue, 13 Feb 2024 13:19:26 +0100 Subject: [PATCH 29/78] refs#6721 MetodoPagoActivarTrabajadores --- db/routines/vn/procedures/worker_updateBusiness.sql | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/db/routines/vn/procedures/worker_updateBusiness.sql b/db/routines/vn/procedures/worker_updateBusiness.sql index 274bc3ec0..76c8c9cbb 100644 --- a/db/routines/vn/procedures/worker_updateBusiness.sql +++ b/db/routines/vn/procedures/worker_updateBusiness.sql @@ -23,6 +23,12 @@ BEGIN IF vOldBusinessFk IS NULL THEN CALL account.account_enable(vSelf); + + UPDATE client c + JOIN payMethod pm ON pm.code = 'bankDraft' + SET c.payMethodFk = pm.id + WHERE c.id = vSelf + AND c.iban; END IF; END$$ DELIMITER ; From 9a6af6fe835aa6d8672f820cf805fd164e605aff Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 14 Feb 2024 10:13:45 +0100 Subject: [PATCH 30/78] 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 31/78] 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' From 728224cad9c18b7258739d20e874ee9178e523e6 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 20 Feb 2024 13:04:45 +0100 Subject: [PATCH 32/78] refs #5858 fix accepts --- .../back/methods/client/updateFiscalData.js | 10 +++++----- .../methods/supplier/specs/newSupplier.spec.js | 3 ++- .../back/methods/supplier/updateFiscalData.js | 4 ++-- .../supplier/back/models/specs/supplier.spec.js | 9 ++++++--- modules/supplier/back/models/supplier.js | 16 ++++++---------- 5 files changed, 21 insertions(+), 21 deletions(-) diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 5fd886c32..8fe92ecd0 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -22,7 +22,7 @@ module.exports = Self => { }, { arg: 'fi', - type: 'string' + type: 'any' }, { arg: 'street', @@ -30,19 +30,19 @@ module.exports = Self => { }, { arg: 'postcode', - type: 'string' + type: 'any' }, { arg: 'city', - type: 'string' + type: 'any' }, { arg: 'countryFk', - type: 'number' + type: 'any' }, { arg: 'provinceFk', - type: 'number' + type: 'any' }, { arg: 'sageTaxTypeFk', diff --git a/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js b/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js index 0e7fa0e34..2b36de5e2 100644 --- a/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js +++ b/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js @@ -26,7 +26,8 @@ describe('Supplier newSupplier()', () => { const options = {transaction: tx}; ctx.args = { name: 'NEWSUPPLIER', - nif: '12345678Z' + nif: '12345678Z', + city: 'Gotham' }; const result = await models.Supplier.newSupplier(ctx, options); 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' diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index 3f40ce58b..05d78240d 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -129,10 +129,13 @@ describe('loopback model Supplier', () => { const options = {transaction: tx}; try { - const newSupplier = await models.Supplier.create({name: 'ALFRED PENNYWORTH'}, options); - const fetchedSupplier = await models.Supplier.findById(newSupplier.id, null, options); + const newSupplier = { + name: 'ALFRED PENNYWORTH', nif: '87805752D', city: 'Gotham' + }; + const supplierCreated = await models.Supplier.create(newSupplier, options); + const fetchedSupplier = await models.Supplier.findById(supplierCreated.id, null, options); - expect(Number(fetchedSupplier.account)).toEqual(4100000000 + newSupplier.id); + expect(Number(fetchedSupplier.account)).toEqual(4100000000 + supplierCreated.id); await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 0ac389074..2d3ffef3e 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 8514a23f9c8069461d8034ebc5bbcc88678532c4 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 20 Feb 2024 13:18:37 +0100 Subject: [PATCH 33/78] refs #5858 fix conflicts --- loopback/locale/en.json | 8 -------- loopback/locale/es.json | 18 ------------------ 2 files changed, 26 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 9d7d2b75f..2187371cd 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -203,19 +203,11 @@ "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}}", -<<<<<<< HEAD -======= - "Try again": "Try again", ->>>>>>> 5918c14d41259e9989b63c8a36f0e23612cf5d69 "Incorrect pin": "Incorrect pin.", "The notification subscription of this worker cant be modified": "The notification subscription of this worker cant be modified", "Name should be uppercase": "Name should be uppercase", "You cannot update these fields": "You cannot update these fields", -<<<<<<< HEAD "CountryFK cannot be empty": "Country cannot be empty", "You are not allowed to modify the alias": "You are not allowed to modify the alias", "You already have the mailAlias": "You already have the mailAlias" -======= - "CountryFK cannot be empty": "Country cannot be empty" ->>>>>>> 5918c14d41259e9989b63c8a36f0e23612cf5d69 } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index f4aca18d4..d51dcb88d 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -1,8 +1,4 @@ { -<<<<<<< HEAD -======= - "postalcode": "Código postal", ->>>>>>> 5918c14d41259e9989b63c8a36f0e23612cf5d69 "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", @@ -143,11 +139,7 @@ "Claim state has changed to": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *{{newState}}*", "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", -<<<<<<< HEAD "Distance must be lesser than 4000": "La distancia debe ser inferior a 4000", -======= - "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000", ->>>>>>> 5918c14d41259e9989b63c8a36f0e23612cf5d69 "This ticket is deleted": "Este ticket está eliminado", "Unable to clone this travel": "No ha sido posible clonar este travel", "This thermograph id already exists": "La id del termógrafo ya existe", @@ -341,28 +333,18 @@ "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", "This claim has been updated": "La reclamación con Id: {{claimId}}, ha sido actualizada", "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada", -<<<<<<< HEAD - "Incorrect pin": "Pin incorrecto", - "You already have the mailAlias": "Ya tienes este alias de correo", - "The alias cant be modified": "Este alias de correo no puede ser modificado", -======= "Field are invalid": "El campo '{{tag}}' no es válido", "Incorrect pin": "Pin incorrecto.", "You already have the mailAlias": "Ya tienes este alias de correo", "The alias cant be modified": "Este alias de correo no puede ser modificado", "No tickets to invoice": "No hay tickets para facturar", ->>>>>>> 5918c14d41259e9989b63c8a36f0e23612cf5d69 "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado", "Name should be uppercase": "El nombre debe ir en mayúscula", "Bank entity must be specified": "La entidad bancaria es obligatoria", "An email is necessary": "Es necesario un email", "You cannot update these fields": "No puedes actualizar estos campos", "CountryFK cannot be empty": "El país no puede estar vacío", -<<<<<<< HEAD "Cmr file does not exist": "El archivo del cmr no existe", "You are not allowed to modify the alias": "No estás autorizado a modificar el alias", "No tickets to invoice": "No hay tickets para facturar" -======= - "Cmr file does not exist": "El archivo del cmr no existe" ->>>>>>> 5918c14d41259e9989b63c8a36f0e23612cf5d69 } From f3f0360059601b8c35cf31a01dd1ba0f31441910 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 20 Feb 2024 13:19:31 +0100 Subject: [PATCH 34/78] refs #5858 fix conflicts --- loopback/locale/es.json | 1 - 1 file changed, 1 deletion(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index d51dcb88d..247e0baae 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -346,5 +346,4 @@ "CountryFK cannot be empty": "El país no puede estar vacío", "Cmr file does not exist": "El archivo del cmr no existe", "You are not allowed to modify the alias": "No estás autorizado a modificar el alias", - "No tickets to invoice": "No hay tickets para facturar" } From 62ccbb30741f26b8d01e504ef76e7e24ea61943e Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 20 Feb 2024 13:45:10 +0100 Subject: [PATCH 35/78] refs #5858 fix error --- loopback/server/middleware/error-handler.js | 28 ++++----------------- 1 file changed, 5 insertions(+), 23 deletions(-) diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index dcce7d54a..cc7b81618 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -1,14 +1,7 @@ -const SalixError = require('vn-loopback/util/salixError'); -const UserError = require('vn-loopback/util/user-error'); +const SalixError = require('../../util/salixError'); +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 mapMethods = require('vn-loopback/util/map-methods'); -const validations = [ - valueIsNot, - valueInvalid, - mapMethods -]; + module.exports = function() { return function(err, req, res, next) { // Thrown user errors @@ -18,19 +11,7 @@ module.exports = function() { } // Validation errors - if ([400, 422].includes(err.statusCode)) { - try { - validations.forEach(validation => { - if (validation.validation(err.message)) { - const error = validation.handleError(req, err); - if (error) - err.message = validation.message(error, req); - } - }); - - return next(err); - } catch (e) { - } + if (err.statusCode == 422) { try { let code; let {messages} = err.details; @@ -45,6 +26,7 @@ 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); From e7f8b7282bb4ed7794bfb949fbaaa81b752b046c Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 20 Feb 2024 13:48:31 +0100 Subject: [PATCH 36/78] refs #5858 remove clean pr --- .../middleware/specs/value-is-not.spec.js | 59 ---------- loopback/server/middleware/value-invalid.js | 58 ---------- loopback/server/middleware/value-is-not.js | 106 ------------------ loopback/util/map-locales.js | 23 ---- loopback/util/map-methods.js | 12 -- 5 files changed, 258 deletions(-) delete mode 100644 loopback/server/middleware/specs/value-is-not.spec.js delete mode 100644 loopback/server/middleware/value-invalid.js delete mode 100644 loopback/server/middleware/value-is-not.js delete mode 100644 loopback/util/map-locales.js delete mode 100644 loopback/util/map-methods.js diff --git a/loopback/server/middleware/specs/value-is-not.spec.js b/loopback/server/middleware/specs/value-is-not.spec.js deleted file mode 100644 index 4d65ddf56..000000000 --- a/loopback/server/middleware/specs/value-is-not.spec.js +++ /dev/null @@ -1,59 +0,0 @@ -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'}, - } - }; - - fit('UpdateFiscalData endpoint', () => { - let messageError = 'Value is not number'; - const tag = 'provinceFk'; - try { - expect(valueIsNot.validation(messageError)).toBeTrue(); - const data = { - method: 'PATCH', - originalUrl: '/api/supplier/updateFiscalData', - body: { - [tag]: null - }, - __: i18n - }; - const result = valueIsNot.handleError(data); - - expect(result.tag).toEqual(tag); - expect(valueIsNot.message(result, i18n)).toEqual('El campo \'provincia\' no es válido'); - } catch (error) { - expect(error).toBeDefined(); - } - }); - - describe('OsTicket', () => { - let messageError = 'Value is not object'; - const tag = 'additionalData'; - it('sendToSupport endpoint', () => { - try { - expect(valueIsNot.validation(messageError)).toBeTrue(); - 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.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-invalid.js b/loopback/server/middleware/value-invalid.js deleted file mode 100644 index 962aa9e1f..000000000 --- a/loopback/server/middleware/value-invalid.js +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100644 index 021af3fb9..000000000 --- a/loopback/server/middleware/value-is-not.js +++ /dev/null @@ -1,106 +0,0 @@ -const SLASH = '/'; -const {models} = require('vn-loopback/server/server'); -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}) => { - 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(SLASH); - hasId = path.length > 1; - - 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().filter(el => el.verb === verb.toLowerCase()).find(el => { - let isValid = false; - 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; - 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 (!isValid) { - tag = key; - break; - } - } - } - 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/util/map-locales.js b/loopback/util/map-locales.js deleted file mode 100644 index 692de3f23..000000000 --- a/loopback/util/map-locales.js +++ /dev/null @@ -1,23 +0,0 @@ -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; - diff --git a/loopback/util/map-methods.js b/loopback/util/map-methods.js deleted file mode 100644 index 2858cd61d..000000000 --- a/loopback/util/map-methods.js +++ /dev/null @@ -1,12 +0,0 @@ -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 4a2032b9cdef49ffcb4d9e356ecdfa3626d04b76 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 23 Feb 2024 07:39:56 +0100 Subject: [PATCH 37/78] refs #5509 fix(EntryDms): sql --- db/versions/10841-orangeGalax/00-entryDms.sql | 9 +-------- modules/entry/back/models/entry-dms.json | 5 +++++ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/db/versions/10841-orangeGalax/00-entryDms.sql b/db/versions/10841-orangeGalax/00-entryDms.sql index d8c495d6d..33ec1e3af 100644 --- a/db/versions/10841-orangeGalax/00-entryDms.sql +++ b/db/versions/10841-orangeGalax/00-entryDms.sql @@ -12,11 +12,4 @@ CREATE OR REPLACE TABLE `vn`.`entryDms` ( INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES - ('WorkerDms', '*', '*', 'ALLOW', 'ROLE', 'employee'), - ('EntryDms', '*', '*', 'ALLOW', 'ROLE', 'employee'), - ('Entry', 'uploadFile', 'WRITE', 'ALLOW', 'ROLE', 'employee'); - -UPDATE `salix`.`ACL` - SET accessType = '*' - WHERE model = 'ClientDms' - AND property = '*'; + ('EntryDms', '*', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/modules/entry/back/models/entry-dms.json b/modules/entry/back/models/entry-dms.json index 5bb3194c2..eb8300e83 100644 --- a/modules/entry/back/models/entry-dms.json +++ b/modules/entry/back/models/entry-dms.json @@ -9,6 +9,11 @@ "table": "entryDms" } }, + "allowedContentTypes": [ + "image/png", + "image/jpeg", + "image/jpg" + ], "properties": { "dmsFk": { "type": "number", From 6e161dfee8b01662f0b3d69ed93bec56e280bc3c Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 23 Feb 2024 12:45:58 +0100 Subject: [PATCH 38/78] fix: refs #6878 column name --- db/routines/vn/procedures/workerTimeControl_clockIn.sql | 2 +- db/versions/10906-limeIvy/00-firstScript.sql | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 db/versions/10906-limeIvy/00-firstScript.sql diff --git a/db/routines/vn/procedures/workerTimeControl_clockIn.sql b/db/routines/vn/procedures/workerTimeControl_clockIn.sql index 77a628d10..e58528487 100644 --- a/db/routines/vn/procedures/workerTimeControl_clockIn.sql +++ b/db/routines/vn/procedures/workerTimeControl_clockIn.sql @@ -75,7 +75,7 @@ BEGIN SET vDated = DATE(vTimed); - SELECT IF(pc.code = 'driveCE', + SELECT IF(pc.code = 'driverCE', wc.dayBreakDriver, wc.dayBreak), wc.shortWeekBreak, diff --git a/db/versions/10906-limeIvy/00-firstScript.sql b/db/versions/10906-limeIvy/00-firstScript.sql new file mode 100644 index 000000000..6ce187d20 --- /dev/null +++ b/db/versions/10906-limeIvy/00-firstScript.sql @@ -0,0 +1,6 @@ +ALTER TABLE vn.professionalCategory DROP COLUMN IF EXISTS code; +ALTER TABLE IF EXISTS vn.professionalCategory ADD COLUMN code VARCHAR(25) UNIQUE DEFAULT NULL; + +UPDATE vn.professionalCategory + SET code = 'driverCE' + WHERE name = 'Conductor C + E'; \ No newline at end of file From efdc8eb1883368ffb0e553e8779b8ec0daf9fa82 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 23 Feb 2024 13:52:44 +0100 Subject: [PATCH 39/78] refs #5878 fix phone --- modules/supplier/back/methods/supplier/updateFiscalData.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/supplier/back/methods/supplier/updateFiscalData.js b/modules/supplier/back/methods/supplier/updateFiscalData.js index 713b97cd4..f2cdd63be 100644 --- a/modules/supplier/back/methods/supplier/updateFiscalData.js +++ b/modules/supplier/back/methods/supplier/updateFiscalData.js @@ -19,7 +19,7 @@ module.exports = Self => { type: 'any' }, { arg: 'phone', - type: 'string' + type: 'any' }, { arg: 'sageTaxTypeFk', type: 'any' From 6dc41815754a853a14afc6fdf74f002bbfc883be Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 23 Feb 2024 13:54:32 +0100 Subject: [PATCH 40/78] refs #5878 fix pr --- modules/client/back/methods/client/updateFiscalData.js | 2 +- package.json | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index f6ea80cfc..9a6255215 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -22,7 +22,7 @@ module.exports = Self => { }, { arg: 'fi', - type: 'any' + type: 'string' }, { arg: 'street', diff --git a/package.json b/package.json index 29d3369e6..302738524 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,6 @@ "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", From d4459291b60c953eda7f071cb3f2a5cad88cfe98 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 23 Feb 2024 14:31:35 +0100 Subject: [PATCH 41/78] refs #5878 fix --- pnpm-lock.yaml | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 41673b0fe..025be234e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,9 +29,6 @@ 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 @@ -134,8 +131,8 @@ devDependencies: specifier: ^7.7.7 version: 7.23.7(@babel/core@7.23.9) '@verdnatura/myt': - specifier: ^1.6.8 - version: 1.6.8 + specifier: ^1.6.7 + version: 1.6.7 angular-mocks: specifier: ^1.7.9 version: 1.8.3 @@ -1628,6 +1625,7 @@ 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==} @@ -1915,6 +1913,7 @@ packages: resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} requiresBuild: true + dev: true optional: true /@puppeteer/browsers@1.9.1: @@ -2634,8 +2633,8 @@ packages: dev: false optional: true - /@verdnatura/myt@1.6.8: - resolution: {integrity: sha512-jpadr6yAR9TQXPv+has5yOYAolR/YEzsxbLgMR7BoDrpLyVFLHJEy4Dfe+Hy11r3AmxCB/8lWM+La1YGvXMWOA==} + /@verdnatura/myt@1.6.7: + resolution: {integrity: sha512-t/Q1T3QzHpZFdxwIyQL/CV5g+HJvWE6Q65VeA9k0svZdX/vezgnQ21nkI+wuvIurIl6BXqq2Arx7EWYkAhGNNA==} hasBin: true dependencies: '@sqltools/formatter': 1.2.5 @@ -3028,6 +3027,7 @@ 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==} @@ -3049,6 +3049,7 @@ 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==} @@ -5206,6 +5207,7 @@ packages: /eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + dev: true /ecc-jsbn@0.1.2: resolution: {integrity: sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==} @@ -5264,6 +5266,7 @@ packages: /emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + dev: true /emojis-list@3.0.0: resolution: {integrity: sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==} @@ -6099,6 +6102,7 @@ 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==} @@ -6492,6 +6496,7 @@ 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==} @@ -6506,7 +6511,7 @@ packages: fs.realpath: 1.0.0 inflight: 1.0.6 inherits: 2.0.4 - minimatch: 3.1.2 + minimatch: 3.0.8 once: 1.4.0 path-is-absolute: 1.0.1 dev: true @@ -8000,6 +8005,7 @@ 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==} @@ -9248,6 +9254,7 @@ 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==} @@ -9653,6 +9660,7 @@ 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==} @@ -9742,6 +9750,7 @@ 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==} @@ -10836,6 +10845,7 @@ 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,6 +12176,7 @@ 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==} @@ -12622,6 +12633,7 @@ 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==} @@ -12668,6 +12680,7 @@ packages: engines: {node: '>=12'} dependencies: ansi-regex: 6.0.1 + dev: true /strip-bom@2.0.0: resolution: {integrity: sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==} @@ -14170,6 +14183,7 @@ 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 00a8b3dc4b1cd08d915ed548ddd8931e76b49507 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 23 Feb 2024 14:33:51 +0100 Subject: [PATCH 42/78] refs #5878 fix --- pnpm-lock.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 025be234e..36bff2fe1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -131,8 +131,8 @@ devDependencies: specifier: ^7.7.7 version: 7.23.7(@babel/core@7.23.9) '@verdnatura/myt': - specifier: ^1.6.7 - version: 1.6.7 + specifier: ^1.6.8 + version: 1.6.8 angular-mocks: specifier: ^1.7.9 version: 1.8.3 @@ -2633,8 +2633,8 @@ packages: dev: false optional: true - /@verdnatura/myt@1.6.7: - resolution: {integrity: sha512-t/Q1T3QzHpZFdxwIyQL/CV5g+HJvWE6Q65VeA9k0svZdX/vezgnQ21nkI+wuvIurIl6BXqq2Arx7EWYkAhGNNA==} + /@verdnatura/myt@1.6.8: + resolution: {integrity: sha512-jpadr6yAR9TQXPv+has5yOYAolR/YEzsxbLgMR7BoDrpLyVFLHJEy4Dfe+Hy11r3AmxCB/8lWM+La1YGvXMWOA==} hasBin: true dependencies: '@sqltools/formatter': 1.2.5 From 771545fa63350bca544f6701f659b40a9cc97d57 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 23 Feb 2024 15:01:57 +0100 Subject: [PATCH 43/78] refs #5640 fix(fixutures): client social name --- db/dump/fixtures.before.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index becd65060..ac5281fb3 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -387,7 +387,7 @@ INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','loses'); INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) - SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1 + SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), UPPER(CONCAT(name, 'Social')), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1 FROM `account`.`role` `r` WHERE `r`.`hasLogin` = 1; From 1a1e7742d3ea5be78389d11d8f39a14b3ce79b34 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 23 Feb 2024 15:32:21 +0100 Subject: [PATCH 44/78] feat: refs #6513 create table --- .../10908-blueAsparagus/00-createSupplierDms.sql | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 db/versions/10908-blueAsparagus/00-createSupplierDms.sql diff --git a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql new file mode 100644 index 000000000..fb592db0d --- /dev/null +++ b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql @@ -0,0 +1,10 @@ +CREATE TABLE IF NOT EXISTS vn.supplierDms( + id int(11) NOT NULL AUTO_INCREMENT, + supplierFk int(11) NOT NULL, + dmsFk int(11) NOT NULL, + editorFk int(10) unsigned DEFAULT NULL, + PRIMARY KEY (id), + CONSTRAINT clientDms_fk_editor FOREIGN KEY (editorFk) REFERENCES account.user(id), + CONSTRAINT dmsFk FOREIGN KEY (dmsFk) REFERENCES dms(id) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT supplierFk FOREIGN KEY (supplierFk) REFERENCES supplier(id) ON UPDATE CASCADE +); From 3c038a060cd0cf98d641aab1e1487584259047a4 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 23 Feb 2024 16:27:49 +0100 Subject: [PATCH 45/78] feat: refs #6513 WIP triggers & logger --- db/routines/vn/triggers/supplierDms_afterDelete.sql | 12 ++++++++++++ db/routines/vn/triggers/supplierDms_beforeInsert.sql | 8 ++++++++ db/routines/vn/triggers/supplierDms_beforeUpdate.sql | 8 ++++++++ .../10908-blueAsparagus/00-createSupplierDms.sql | 9 ++++++++- 4 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 db/routines/vn/triggers/supplierDms_afterDelete.sql create mode 100644 db/routines/vn/triggers/supplierDms_beforeInsert.sql create mode 100644 db/routines/vn/triggers/supplierDms_beforeUpdate.sql diff --git a/db/routines/vn/triggers/supplierDms_afterDelete.sql b/db/routines/vn/triggers/supplierDms_afterDelete.sql new file mode 100644 index 000000000..482decbb6 --- /dev/null +++ b/db/routines/vn/triggers/supplierDms_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`supplierDms_afterDelete` + AFTER DELETE ON `supplierDms` + FOR EACH ROW +BEGIN + INSERT INTO clientLog + SET `action` = 'delete', + `changedModel` = 'supplierDms', + `changedModelId` = OLD.dmsFk, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/supplierDms_beforeInsert.sql b/db/routines/vn/triggers/supplierDms_beforeInsert.sql new file mode 100644 index 000000000..adef31c2b --- /dev/null +++ b/db/routines/vn/triggers/supplierDms_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=root@localhost TRIGGER vn.supplierDms_beforeInsert + BEFORE INSERT ON supplierDms + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/supplierDms_beforeUpdate.sql b/db/routines/vn/triggers/supplierDms_beforeUpdate.sql new file mode 100644 index 000000000..228c5e5ea --- /dev/null +++ b/db/routines/vn/triggers/supplierDms_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=root@localhost TRIGGER vn.supplierDms_beforeUpdate + BEFORE UPDATE ON supplierDms + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql index fb592db0d..23c45cc7b 100644 --- a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql +++ b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql @@ -4,7 +4,14 @@ CREATE TABLE IF NOT EXISTS vn.supplierDms( dmsFk int(11) NOT NULL, editorFk int(10) unsigned DEFAULT NULL, PRIMARY KEY (id), - CONSTRAINT clientDms_fk_editor FOREIGN KEY (editorFk) REFERENCES account.user(id), + CONSTRAINT supplierDms_fk_editor FOREIGN KEY (editorFk) REFERENCES account.user(id), CONSTRAINT dmsFk FOREIGN KEY (dmsFk) REFERENCES dms(id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT supplierFk FOREIGN KEY (supplierFk) REFERENCES supplier(id) ON UPDATE CASCADE ); + +ALTER TABLE `supplierLog` + MODIFY COLUMN `changedModel` ENUM('Supplier','SupplierAddress','SupplierAccount','SupplierContact','SupplierDms') NOT NULL DEFAULT 'Supplier'; + +ALTER TABLE `vn`.`supplierDms` + ADD IF NOT EXISTS editorFk INT UNSIGNED NULL, + ADD CONSTRAINT supplierDms_fk_editor FOREIGN KEY IF NOT EXISTS (editorFk) REFERENCES account.`user`(id); \ No newline at end of file From bed4faceb703cfeb82d70871a2e3f351f81e64ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 23 Feb 2024 18:04:43 +0100 Subject: [PATCH 46/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/entry_beforeUpdate.sql | 14 ++++++++++++++ db/routines/vn/triggers/travel_beforeUpdate.sql | 15 +++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 91d490b21..27b1a53f3 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -47,5 +47,19 @@ BEGIN OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); END IF; + + IF NOT (NEW.invoiceInFk <=> OLD.invoiceInFk)THEN + DECLARE vHanAnyInvoiceBooked BOOL; + + SELECT COUNT(*) INTO vHanAnyInvoiceBooked + FROM entry e + JOIN invoiceIn ii ON ii.id = e.invoiceInFk + WHERE e.id = NEW.id + AND ii.isBooked; + + IF vHanAnyInvoiceBooked THEN + CALL util.throw('The travel has entries with booked invoices') + END IF; + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index 2079cd21e..b12cf154b 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -17,5 +17,20 @@ BEGIN IF NOT (NEW.warehouseInFk <=> OLD.warehouseInFk) THEN CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); END IF; + + IF NOT (NEW.awbFk <=> OLD.awbFk)THEN + DECLARE vHanAnyInvoiceBooked BOOL; + + SELECT COUNT(*) INTO vHanAnyInvoiceBooked + FROM travel t + JOIN entry e ON e.travelFk =t.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk + WHERE t.id = NEW.id + AND ii.isBooked; + + IF vHanAnyInvoiceBooked THEN + CALL util.throw('The travel has entries with booked invoices') + END IF; + END IF; END$$ DELIMITER ; From 5fe4f794cc569b70c0877263959747b7a70ffa00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 23 Feb 2024 18:10:23 +0100 Subject: [PATCH 47/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/entry_beforeUpdate.sql | 7 +++---- db/routines/vn/triggers/travel_beforeUpdate.sql | 11 ++++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 27b1a53f3..260af4908 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -6,6 +6,7 @@ BEGIN DECLARE vIsVirtual BOOL; DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; + DECLARE vHasAnyInvoiceBooked BOOL; SET NEW.editorFk = account.myUser_getId(); @@ -49,15 +50,13 @@ BEGIN END IF; IF NOT (NEW.invoiceInFk <=> OLD.invoiceInFk)THEN - DECLARE vHanAnyInvoiceBooked BOOL; - - SELECT COUNT(*) INTO vHanAnyInvoiceBooked + SELECT COUNT(*) INTO vHasAnyInvoiceBooked FROM entry e JOIN invoiceIn ii ON ii.id = e.invoiceInFk WHERE e.id = NEW.id AND ii.isBooked; - IF vHanAnyInvoiceBooked THEN + IF vHasAnyInvoiceBooked THEN CALL util.throw('The travel has entries with booked invoices') END IF; END IF; diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index b12cf154b..e4297352d 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -3,6 +3,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`travel_beforeUpdate` BEFORE UPDATE ON `travel` FOR EACH ROW BEGIN + DECLARE vHasAnyInvoiceBooked BOOL; + SET NEW.editorFk = account.myUser_getId(); IF NOT (NEW.landed <=> OLD.landed) @@ -19,16 +21,15 @@ BEGIN END IF; IF NOT (NEW.awbFk <=> OLD.awbFk)THEN - DECLARE vHanAnyInvoiceBooked BOOL; - - SELECT COUNT(*) INTO vHanAnyInvoiceBooked + + SELECT COUNT(*) INTO vHasAnyInvoiceBooked FROM travel t JOIN entry e ON e.travelFk =t.id JOIN invoiceIn ii ON ii.id = e.invoiceInFk WHERE t.id = NEW.id AND ii.isBooked; - - IF vHanAnyInvoiceBooked THEN + + IF vHasAnyInvoiceBooked THEN CALL util.throw('The travel has entries with booked invoices') END IF; END IF; From 55bc6418f51fdf225a2ddc78e2eb804749e53e68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 23 Feb 2024 18:13:01 +0100 Subject: [PATCH 48/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/entry_beforeUpdate.sql | 2 +- db/routines/vn/triggers/travel_beforeUpdate.sql | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 260af4908..1be493a07 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -57,7 +57,7 @@ BEGIN AND ii.isBooked; IF vHasAnyInvoiceBooked THEN - CALL util.throw('The travel has entries with booked invoices') + CALL util.throw('The travel has entries with booked invoices'); END IF; END IF; END$$ diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index e4297352d..e622a8e6d 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -20,7 +20,7 @@ BEGIN CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); END IF; - IF NOT (NEW.awbFk <=> OLD.awbFk)THEN + IF NOT (NEW.awbFk <=> OLD.awbFk) THEN SELECT COUNT(*) INTO vHasAnyInvoiceBooked FROM travel t @@ -30,7 +30,7 @@ BEGIN AND ii.isBooked; IF vHasAnyInvoiceBooked THEN - CALL util.throw('The travel has entries with booked invoices') + CALL util.throw('The travel has entries with booked invoices'); END IF; END IF; END$$ From 4cc950011e625272d2289fe1e4274334e5b37bdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 23 Feb 2024 18:15:07 +0100 Subject: [PATCH 49/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/travel_beforeUpdate.sql | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index e622a8e6d..dbac6459b 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -21,10 +21,9 @@ BEGIN END IF; IF NOT (NEW.awbFk <=> OLD.awbFk) THEN - SELECT COUNT(*) INTO vHasAnyInvoiceBooked FROM travel t - JOIN entry e ON e.travelFk =t.id + JOIN entry e ON e.travelFk = t.id JOIN invoiceIn ii ON ii.id = e.invoiceInFk WHERE t.id = NEW.id AND ii.isBooked; From 9f8e44856245e3208a847174a06c05eda46097aa Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 26 Feb 2024 07:22:51 +0100 Subject: [PATCH 50/78] refs #5509 fix(EntryDms): some issues --- modules/entry/back/methods/entry-dms/removeFile.js | 4 ++-- modules/entry/back/methods/entry-dms/uploadFile.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/entry/back/methods/entry-dms/removeFile.js b/modules/entry/back/methods/entry-dms/removeFile.js index 677e627a6..89a87755c 100644 --- a/modules/entry/back/methods/entry-dms/removeFile.js +++ b/modules/entry/back/methods/entry-dms/removeFile.js @@ -2,7 +2,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('removeFile', { - description: 'Removes a claim document', + description: 'Removes a entry document', accessType: 'WRITE', accepts: { arg: 'id', @@ -36,7 +36,7 @@ module.exports = Self => { const targetEntryDms = await Self.findById(id, null, myOptions); const targetDms = await Self.app.models.Dms.removeFile(ctx, targetEntryDms.dmsFk, myOptions); - if (!targetDms || ! targetEntryDms) + if (!targetDms) throw new UserError('Try again'); const entryDmsDestroyed = await targetEntryDms.destroy(myOptions); diff --git a/modules/entry/back/methods/entry-dms/uploadFile.js b/modules/entry/back/methods/entry-dms/uploadFile.js index fe0cfab5f..54b56fed4 100644 --- a/modules/entry/back/methods/entry-dms/uploadFile.js +++ b/modules/entry/back/methods/entry-dms/uploadFile.js @@ -6,7 +6,7 @@ module.exports = Self => { accepts: [{ arg: 'id', type: 'number', - description: 'The claim id', + description: 'The entry id', http: {source: 'path'} }, { From 910cc41beb65b17bb96839e7a016698c892548bd Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 26 Feb 2024 09:35:06 +0100 Subject: [PATCH 51/78] fix: refs #6513 trigger & alter table --- .../vn/triggers/supplierDms_beforeInsert.sql | 4 ++-- .../vn/triggers/supplierDms_beforeUpdate.sql | 4 ++-- .../00-createSupplierDms.sql | 22 ++++++------------- 3 files changed, 11 insertions(+), 19 deletions(-) diff --git a/db/routines/vn/triggers/supplierDms_beforeInsert.sql b/db/routines/vn/triggers/supplierDms_beforeInsert.sql index adef31c2b..130428d1e 100644 --- a/db/routines/vn/triggers/supplierDms_beforeInsert.sql +++ b/db/routines/vn/triggers/supplierDms_beforeInsert.sql @@ -1,6 +1,6 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=root@localhost TRIGGER vn.supplierDms_beforeInsert - BEFORE INSERT ON supplierDms +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`supplierDms_beforeInsert` + BEFORE INSERT ON `supplierDms` FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); diff --git a/db/routines/vn/triggers/supplierDms_beforeUpdate.sql b/db/routines/vn/triggers/supplierDms_beforeUpdate.sql index 228c5e5ea..54dcef049 100644 --- a/db/routines/vn/triggers/supplierDms_beforeUpdate.sql +++ b/db/routines/vn/triggers/supplierDms_beforeUpdate.sql @@ -1,6 +1,6 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=root@localhost TRIGGER vn.supplierDms_beforeUpdate - BEFORE UPDATE ON supplierDms +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`supplierDms_beforeUpdate` + BEFORE UPDATE ON `supplierDms` FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); diff --git a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql index 23c45cc7b..fbdc7ed58 100644 --- a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql +++ b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql @@ -1,17 +1,9 @@ -CREATE TABLE IF NOT EXISTS vn.supplierDms( - id int(11) NOT NULL AUTO_INCREMENT, - supplierFk int(11) NOT NULL, - dmsFk int(11) NOT NULL, - editorFk int(10) unsigned DEFAULT NULL, - PRIMARY KEY (id), - CONSTRAINT supplierDms_fk_editor FOREIGN KEY (editorFk) REFERENCES account.user(id), - CONSTRAINT dmsFk FOREIGN KEY (dmsFk) REFERENCES dms(id) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT supplierFk FOREIGN KEY (supplierFk) REFERENCES supplier(id) ON UPDATE CASCADE -); +ALTER TABLE `vn`.`supplierDms` + MODIFY COLUMN supplierFk int(10) unsigned NOT NULL, + ADD editorFk INT UNSIGNED NULL, + ADD CONSTRAINT user_Fk FOREIGN KEY (editorFk) REFERENCES account.`user`(id), + ADD CONSTRAINT dms_FK FOREIGN KEY (dmsFk) REFERENCES vn.dms(id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT supplier_Fk FOREIGN KEY (supplierFk) REFERENCES vn.supplier(id) ON UPDATE CASCADE; ALTER TABLE `supplierLog` - MODIFY COLUMN `changedModel` ENUM('Supplier','SupplierAddress','SupplierAccount','SupplierContact','SupplierDms') NOT NULL DEFAULT 'Supplier'; - -ALTER TABLE `vn`.`supplierDms` - ADD IF NOT EXISTS editorFk INT UNSIGNED NULL, - ADD CONSTRAINT supplierDms_fk_editor FOREIGN KEY IF NOT EXISTS (editorFk) REFERENCES account.`user`(id); \ No newline at end of file + MODIFY COLUMN `changedModel` ENUM('Supplier','SupplierAddress','SupplierAccount','SupplierContact','SupplierDms') NOT NULL DEFAULT 'Supplier'; \ No newline at end of file From 89a9cc26d30910a2da832ad15fa685e5db99945f Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Feb 2024 09:50:03 +0100 Subject: [PATCH 52/78] fix: ticket #158883 --- db/routines/vn/procedures/clean.sql | 3 ++- db/routines/vn2008/procedures/clean.sql | 5 ----- db/versions/10909-crimsonLaurel/00-firstScript.sql | 5 +++++ 3 files changed, 7 insertions(+), 6 deletions(-) create mode 100644 db/versions/10909-crimsonLaurel/00-firstScript.sql diff --git a/db/routines/vn/procedures/clean.sql b/db/routines/vn/procedures/clean.sql index 7b561cfe0..1b3c8b3a2 100644 --- a/db/routines/vn/procedures/clean.sql +++ b/db/routines/vn/procedures/clean.sql @@ -37,7 +37,8 @@ BEGIN DELETE FROM saleTracking WHERE created < vOneYearAgo; DELETE FROM ticketTracking WHERE created < v18Month; DELETE tobs FROM ticketObservation tobs - JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); + JOIN ticket t ON tobs.ticketFk = t.id + WHERE t.shipped < v5Years; DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo; DELETE FROM sharingCart where ended < vDateShort; DELETE FROM sharingClient where ended < vDateShort; diff --git a/db/routines/vn2008/procedures/clean.sql b/db/routines/vn2008/procedures/clean.sql index 0ff185c46..631cec7b8 100644 --- a/db/routines/vn2008/procedures/clean.sql +++ b/db/routines/vn2008/procedures/clean.sql @@ -25,11 +25,6 @@ proc: BEGIN DELETE FROM Movimientos_mark WHERE odbc_date < vDate; DELETE FROM Splits WHERE Fecha < vDate18; - DELETE tobs - FROM ticket_observation tobs - JOIN Tickets t ON tobs.Id_Ticket = t.Id_Ticket - WHERE t.Fecha < vDate; - DELETE tobs FROM movement_label tobs JOIN Movimientos m ON tobs.Id_Movimiento = m.Id_Movimiento diff --git a/db/versions/10909-crimsonLaurel/00-firstScript.sql b/db/versions/10909-crimsonLaurel/00-firstScript.sql new file mode 100644 index 000000000..58e679dff --- /dev/null +++ b/db/versions/10909-crimsonLaurel/00-firstScript.sql @@ -0,0 +1,5 @@ +DELETE FROM vn.entryObservation + WHERE observationTypeFk IS NULL; + +ALTER TABLE vn.entryObservation + MODIFY COLUMN observationTypeFk tinyint(3) unsigned NOT NULL; From a19ce04a408e0ca8bc0029b66917529b78d921e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 26 Feb 2024 12:18:02 +0100 Subject: [PATCH 53/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/travel_beforeUpdate.sql | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index dbac6459b..db835be85 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -3,12 +3,10 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`travel_beforeUpdate` BEFORE UPDATE ON `travel` FOR EACH ROW BEGIN - DECLARE vHasAnyInvoiceBooked BOOL; SET NEW.editorFk = account.myUser_getId(); - IF NOT (NEW.landed <=> OLD.landed) - OR NOT (NEW.shipped <=> OLD.shipped) THEN + IF NOT (NEW.landed <=> OLD.landed) OR NOT (NEW.shipped <=> OLD.shipped) THEN CALL travel_checkDates(NEW.shipped, NEW.landed); END IF; @@ -19,18 +17,5 @@ BEGIN IF NOT (NEW.warehouseInFk <=> OLD.warehouseInFk) THEN CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); END IF; - - IF NOT (NEW.awbFk <=> OLD.awbFk) THEN - SELECT COUNT(*) INTO vHasAnyInvoiceBooked - FROM travel t - JOIN entry e ON e.travelFk = t.id - JOIN invoiceIn ii ON ii.id = e.invoiceInFk - WHERE t.id = NEW.id - AND ii.isBooked; - - IF vHasAnyInvoiceBooked THEN - CALL util.throw('The travel has entries with booked invoices'); - END IF; - END IF; END$$ DELIMITER ; From bfd86c8972638928368f3d1e712ab93bf6a12761 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 26 Feb 2024 12:18:57 +0100 Subject: [PATCH 54/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/travel_beforeUpdate.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index db835be85..30e0445a5 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -3,10 +3,10 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`travel_beforeUpdate` BEFORE UPDATE ON `travel` FOR EACH ROW BEGIN - SET NEW.editorFk = account.myUser_getId(); - IF NOT (NEW.landed <=> OLD.landed) OR NOT (NEW.shipped <=> OLD.shipped) THEN + IF NOT (NEW.landed <=> OLD.landed) + OR NOT (NEW.shipped <=> OLD.shipped) THEN CALL travel_checkDates(NEW.shipped, NEW.landed); END IF; From 413f7eb8c8f2c6a6f960b37a05c889ccaaaab287 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Feb 2024 12:45:38 +0100 Subject: [PATCH 55/78] fix: refs #6184 saveSign --- modules/route/back/methods/route/cmrEmail.js | 25 ++-- modules/ticket/back/methods/ticket/saveCmr.js | 19 ++- .../ticket/back/methods/ticket/saveSign.js | 129 +++++++++--------- 3 files changed, 86 insertions(+), 87 deletions(-) diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js index 11c4d3dc8..d05d72100 100644 --- a/modules/route/back/methods/route/cmrEmail.js +++ b/modules/route/back/methods/route/cmrEmail.js @@ -48,23 +48,18 @@ module.exports = Self => { if (!recipient) throw new UserError('There is no assigned email for this client'); - const dms = await models.TicketDms.findOne({ - where: {ticketFk: ticketId}, - include: [{ - relation: 'dms', - fields: ['id'], - scope: { - relation: 'dmsType', - scope: { - where: {code: 'cmr'} - } - } - }] - }, myOptions); + const dms = await Self.rawSql(` + SELECT d.id + FROM ticketDms td + JOIN dms d ON d.id = td.dmsFk + JOIN dmsType dt ON dt.id = d.dmsTypeFk + WHERE td.ticketFk = ? + AND dt.code = 'cmr' + `, [ticketId]); - if (!dms) throw new UserError('Cmr file does not exist'); + if (!dms.lenght) throw new UserError('Cmr file does not exist'); - const response = await models.Dms.downloadFile(ctx, dms.id); + const response = await models.Dms.downloadFile(ctx, dms[0].id); const email = new Email('cmr', { ticketId, diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 17760bacc..691af796c 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -42,18 +42,15 @@ module.exports = Self => { const ticket = await models.Ticket.findById(ticketId, myOptions); if (ticket.cmrFk) { - const hasDmsCmr = await models.TicketDms.findOne({ - where: {ticketFk: ticketId}, - include: { - relation: 'dms', - fields: ['dmsFk'], - scope: { - where: {dmsTypeFk: dmsTypeCmr.id} - } - } - }, myOptions); + const hasDmsCmr = await Self.rawSql(` + SELECT d.id + FROM ticketDms td + JOIN dms d ON d.id = td.dmsFk + WHERE td.ticketFk = ? + AND d.dmsTypeFk = ? + `, [ticketId, dmsTypeCmr.id]); - if (hasDmsCmr?.dms()) + if (hasDmsCmr.length) throw new UserError('This ticket already has a cmr saved'); ctx.args.id = ticket.cmrFk; diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index fd40c1c22..14968c203 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -33,8 +33,8 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; let tx; - let dms; - let gestDocCreated = false; + let ticket; + let externalTickets = []; if (typeof options == 'object') Object.assign(myOptions, options); @@ -44,6 +44,11 @@ module.exports = Self => { myOptions.transaction = tx; } + const dmsTypeTicket = await models.DmsType.findOne({ + where: {code: 'ticket'}, + fields: ['id'] + }); + async function setLocation(ticketId) { await models.Delivery.create({ ticketFk: ticketId, @@ -53,102 +58,104 @@ module.exports = Self => { }, myOptions); } - async function gestDocExists(ticketId) { + async function hasSignDms(ticketId) { const ticketDms = await models.TicketDms.findOne({ where: {ticketFk: ticketId}, - fields: ['dmsFk'] - }, myOptions); - - if (!ticketDms) return false; - - const ticket = await models.Ticket.findById(ticketId, {fields: ['isSigned']}, myOptions); - if (ticket.isSigned == true) - return true; - else - await models.Dms.destroyAll({where: {reference: ticketId}}, myOptions); - - return false; + include: [ + { + relation: 'dms', + fields: ['id'], + scope: { + where: {dmsTypeFk: dmsTypeTicket.id} + } + } + ] + }); + if (ticketDms?.dms()?.id) return true; } - async function createGestDoc(id) { - const ticket = await models.Ticket.findById(id, - { - include: [ - { - relation: 'warehouse', - scope: { - fields: ['id'] - } - }, { - relation: 'client', - scope: { - fields: ['name'] - } - }, { - relation: 'route', - scope: { - fields: ['id'] - } - } - ] - }, myOptions); - const dmsType = await models.DmsType.findOne({where: {code: 'Ticket'}, fields: ['id']}, myOptions); + async function createGestDoc() { const ctxUploadFile = Object.assign({}, ctx); - if (ticket.route() === null) - throw new UserError('Ticket without route'); ctxUploadFile.args = { warehouseId: ticket.warehouseFk, companyId: ticket.companyFk, - dmsTypeId: dmsType.id, - reference: '', + dmsTypeId: dmsTypeTicket.id, + reference: ticket.id, description: `Firma del cliente - Ruta ${ticket.route().id}`, - hasFile: false + hasFile: true }; - dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); - gestDocCreated = true; + const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); } try { for (const ticketId of tickets) { - const ticketState = await models.TicketState.findOne( - {where: {ticketFk: ticketId}, - fields: ['alertLevel'] - }, myOptions); + ticket = await models.Ticket.findById(ticketId, { + include: [{ + relation: 'address', + scope: { + include: { + relation: 'province', + scope: { + include: { + relation: 'country', + scope: { + fields: ['code'] + } + } + } + } + } + }, { + relation: 'route', + scope: { + fields: ['id'] + } + }] + }); - const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, + const ticketState = await models.TicketState.findOne({ + where: {ticketFk: ticketId}, + fields: ['alertLevel'] + }); + + const packedAlertLevel = await models.AlertLevel.findOne({ + where: {code: 'PACKED'}, fields: ['id'] - }, myOptions); + }); if (!ticketState) throw new UserError('Ticket does not exist'); + if (!ticket.route()) + throw new UserError('Ticket without route'); if (ticketState.alertLevel < packedAlertLevel.id) throw new UserError('This ticket cannot be signed because it has not been boxed'); - if (await gestDocExists(ticketId)) + if (await ticket.isSigned) throw new UserError('Ticket is already signed'); if (location) await setLocation(ticketId); - if (!gestDocCreated) await createGestDoc(ticketId); - await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); - const ticket = await models.Ticket.findById(ticketId, null, myOptions); + if (!await hasSignDms(ticketId)) await createGestDoc(ticketId); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ - where: { - code: 'DELIVERED' - } - }, myOptions); + where: {code: 'DELIVERED'} + }); await models.Ticket.state(ctx, { ticketFk: ticketId, stateFk: deliveryState.id }, myOptions); - } + if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) { + await models.Ticket.saveCmr(ctx, [ticketId], myOptions); + externalTickets.push(ticketId); + } + } if (tx) await tx.commit(); - return; } catch (e) { if (tx) await tx.rollback(); throw e; } + await models.Route.cmrEmail(ctx, externalTickets); }; }; From a359ace1b8550b4213a5c620a4cc94329c45a26a Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Feb 2024 12:57:49 +0100 Subject: [PATCH 56/78] fix: refs #6184 saveSign --- .../ticket/back/methods/ticket/saveSign.js | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 14968c203..7eb4b4144 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -59,19 +59,15 @@ module.exports = Self => { } async function hasSignDms(ticketId) { - const ticketDms = await models.TicketDms.findOne({ - where: {ticketFk: ticketId}, - include: [ - { - relation: 'dms', - fields: ['id'], - scope: { - where: {dmsTypeFk: dmsTypeTicket.id} - } - } - ] - }); - if (ticketDms?.dms()?.id) return true; + const hasTicketDms = await Self.rawSql(` + SELECT d.id + FROM ticketDms td + JOIN dms d ON d.id = td.dmsFk + WHERE td.ticketFk = ? + AND d.dmsTypeFk = ? + `, [ticketId, dmsTypeTicket.id]); + + if (hasTicketDms.length) return true; } async function createGestDoc() { From 817f685621acc760ca74a2df04ef3be46bba0cab Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Feb 2024 13:00:35 +0100 Subject: [PATCH 57/78] fix: refs #6184 saveSign --- modules/ticket/back/methods/ticket/saveSign.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 7eb4b4144..58599716a 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -65,7 +65,7 @@ module.exports = Self => { JOIN dms d ON d.id = td.dmsFk WHERE td.ticketFk = ? AND d.dmsTypeFk = ? - `, [ticketId, dmsTypeTicket.id]); + `, [ticketId, dmsTypeTicket.id], myOptions); if (hasTicketDms.length) return true; } @@ -108,17 +108,17 @@ module.exports = Self => { fields: ['id'] } }] - }); + }, myOptions); const ticketState = await models.TicketState.findOne({ where: {ticketFk: ticketId}, fields: ['alertLevel'] - }); + }, myOptions); const packedAlertLevel = await models.AlertLevel.findOne({ where: {code: 'PACKED'}, fields: ['id'] - }); + }, myOptions); if (!ticketState) throw new UserError('Ticket does not exist'); @@ -135,7 +135,7 @@ module.exports = Self => { const deliveryState = await models.State.findOne({ where: {code: 'DELIVERED'} - }); + }, myOptions); await models.Ticket.state(ctx, { ticketFk: ticketId, From c1c64d0f89dcbc51e34c2b86318da14ddbdea875 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Feb 2024 13:39:57 +0100 Subject: [PATCH 58/78] fix: refs #6184 saveSign --- modules/ticket/back/methods/ticket/saveSign.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 58599716a..ea9f715a9 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -34,6 +34,8 @@ module.exports = Self => { const myOptions = {userId: ctx.req.accessToken.userId}; let tx; let ticket; + let dms; + let isSignUploaded; let externalTickets = []; if (typeof options == 'object') @@ -80,8 +82,8 @@ module.exports = Self => { description: `Firma del cliente - Ruta ${ticket.route().id}`, hasFile: true }; - const dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); - await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); + dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + isSignUploaded = true; } try { @@ -130,7 +132,9 @@ module.exports = Self => { throw new UserError('Ticket is already signed'); if (location) await setLocation(ticketId); - if (!await hasSignDms(ticketId)) await createGestDoc(ticketId); + if (!await hasSignDms(ticketId) && !isSignUploaded) + await createGestDoc(ticketId); + await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ From 27beefe1efc0fd9cce17823cc99cf8d8829336d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 26 Feb 2024 13:43:32 +0100 Subject: [PATCH 59/78] =?UTF-8?q?feat:Agrupar=20DUA=20en=20funci=C3=B3n=20?= =?UTF-8?q?del=20transitario=20y=20pa=C3=ADs=20#6937?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/versions/10911-wheatGerbera/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/10911-wheatGerbera/00-firstScript.sql diff --git a/db/versions/10911-wheatGerbera/00-firstScript.sql b/db/versions/10911-wheatGerbera/00-firstScript.sql new file mode 100644 index 000000000..371c2c358 --- /dev/null +++ b/db/versions/10911-wheatGerbera/00-firstScript.sql @@ -0,0 +1 @@ +-- Place your SQL code here From a4419a2542bb69e89e840d4412d2ebc2a8fd7322 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Feb 2024 13:57:07 +0100 Subject: [PATCH 60/78] fix: refs #6184 saveSign --- modules/route/back/methods/route/cmrEmail.js | 2 +- modules/ticket/back/methods/ticket/saveSign.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js index d05d72100..0c4cc5061 100644 --- a/modules/route/back/methods/route/cmrEmail.js +++ b/modules/route/back/methods/route/cmrEmail.js @@ -57,7 +57,7 @@ module.exports = Self => { AND dt.code = 'cmr' `, [ticketId]); - if (!dms.lenght) throw new UserError('Cmr file does not exist'); + if (!dms.length) throw new UserError('Cmr file does not exist'); const response = await models.Dms.downloadFile(ctx, dms[0].id); diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index ea9f715a9..00211b6b5 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -134,7 +134,8 @@ module.exports = Self => { if (location) await setLocation(ticketId); if (!await hasSignDms(ticketId) && !isSignUploaded) await createGestDoc(ticketId); - await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); + if (isSignUploaded) + await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ From fa53dcbf9dd8f5a32416c391300dfadb93e34ca9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 26 Feb 2024 13:57:56 +0100 Subject: [PATCH 61/78] =?UTF-8?q?feat:Agrupar=20DUA=20en=20funci=C3=B3n=20?= =?UTF-8?q?del=20transitario=20y=20pa=C3=ADs=20#6937?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../10912-brownCataractarum/00-firstScript.sql | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 db/versions/10912-brownCataractarum/00-firstScript.sql diff --git a/db/versions/10912-brownCataractarum/00-firstScript.sql b/db/versions/10912-brownCataractarum/00-firstScript.sql new file mode 100644 index 000000000..51aea42a1 --- /dev/null +++ b/db/versions/10912-brownCataractarum/00-firstScript.sql @@ -0,0 +1,12 @@ +ALTER TABLE vn.country + MODIFY COLUMN code varchar(2) NOT NULL; + +ALTER TABLE vn.country + ADD CONSTRAINT country_unique UNIQUE KEY (code); + +ALTER TABLE vn.transitoryDuaUnified + ADD countryCodeFk varchar(2) DEFAULT 'EC' NOT NULL; + +ALTER TABLE vn.transitoryDuaUnified + ADD CONSTRAINT transitoryDuaUnified_country_FK FOREIGN KEY (countryCodeFk) + REFERENCES vn.country(code); From 096987040eeed5c3a37feb8eea4b6e55169baf37 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Feb 2024 14:00:04 +0100 Subject: [PATCH 62/78] fix: refs #6184 saveSign --- modules/ticket/back/methods/ticket/saveSign.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 00211b6b5..aa970237f 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -83,6 +83,8 @@ module.exports = Self => { hasFile: true }; dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); + // Si se ha subido ya la firma, no se vuelve a subir, ya que si no + // da un error de deadlock en la db isSignUploaded = true; } From 2932e5338957fc15cb930696519ace766ea889ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 26 Feb 2024 14:00:27 +0100 Subject: [PATCH 63/78] =?UTF-8?q?feat:Agrupar=20DUA=20en=20funci=C3=B3n=20?= =?UTF-8?q?del=20transitario=20y=20pa=C3=ADs=20#6937?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/versions/10911-wheatGerbera/00-firstScript.sql | 1 - 1 file changed, 1 deletion(-) delete mode 100644 db/versions/10911-wheatGerbera/00-firstScript.sql diff --git a/db/versions/10911-wheatGerbera/00-firstScript.sql b/db/versions/10911-wheatGerbera/00-firstScript.sql deleted file mode 100644 index 371c2c358..000000000 --- a/db/versions/10911-wheatGerbera/00-firstScript.sql +++ /dev/null @@ -1 +0,0 @@ --- Place your SQL code here From 3579c94268d1ebe1113752e62690d30ad2c3dde6 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 26 Feb 2024 14:09:53 +0100 Subject: [PATCH 64/78] fix: refs #6184 saveSign --- modules/route/back/methods/route/cmrEmail.js | 25 ++-- modules/ticket/back/methods/ticket/saveCmr.js | 19 ++- .../ticket/back/methods/ticket/saveSign.js | 126 ++++++++++-------- 3 files changed, 86 insertions(+), 84 deletions(-) diff --git a/modules/route/back/methods/route/cmrEmail.js b/modules/route/back/methods/route/cmrEmail.js index 11c4d3dc8..0c4cc5061 100644 --- a/modules/route/back/methods/route/cmrEmail.js +++ b/modules/route/back/methods/route/cmrEmail.js @@ -48,23 +48,18 @@ module.exports = Self => { if (!recipient) throw new UserError('There is no assigned email for this client'); - const dms = await models.TicketDms.findOne({ - where: {ticketFk: ticketId}, - include: [{ - relation: 'dms', - fields: ['id'], - scope: { - relation: 'dmsType', - scope: { - where: {code: 'cmr'} - } - } - }] - }, myOptions); + const dms = await Self.rawSql(` + SELECT d.id + FROM ticketDms td + JOIN dms d ON d.id = td.dmsFk + JOIN dmsType dt ON dt.id = d.dmsTypeFk + WHERE td.ticketFk = ? + AND dt.code = 'cmr' + `, [ticketId]); - if (!dms) throw new UserError('Cmr file does not exist'); + if (!dms.length) throw new UserError('Cmr file does not exist'); - const response = await models.Dms.downloadFile(ctx, dms.id); + const response = await models.Dms.downloadFile(ctx, dms[0].id); const email = new Email('cmr', { ticketId, diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 17760bacc..691af796c 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -42,18 +42,15 @@ module.exports = Self => { const ticket = await models.Ticket.findById(ticketId, myOptions); if (ticket.cmrFk) { - const hasDmsCmr = await models.TicketDms.findOne({ - where: {ticketFk: ticketId}, - include: { - relation: 'dms', - fields: ['dmsFk'], - scope: { - where: {dmsTypeFk: dmsTypeCmr.id} - } - } - }, myOptions); + const hasDmsCmr = await Self.rawSql(` + SELECT d.id + FROM ticketDms td + JOIN dms d ON d.id = td.dmsFk + WHERE td.ticketFk = ? + AND d.dmsTypeFk = ? + `, [ticketId, dmsTypeCmr.id]); - if (hasDmsCmr?.dms()) + if (hasDmsCmr.length) throw new UserError('This ticket already has a cmr saved'); ctx.args.id = ticket.cmrFk; diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index fd40c1c22..aa970237f 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -33,8 +33,10 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; let tx; + let ticket; let dms; - let gestDocCreated = false; + let isSignUploaded; + let externalTickets = []; if (typeof options == 'object') Object.assign(myOptions, options); @@ -44,6 +46,11 @@ module.exports = Self => { myOptions.transaction = tx; } + const dmsTypeTicket = await models.DmsType.findOne({ + where: {code: 'ticket'}, + fields: ['id'] + }); + async function setLocation(ticketId) { await models.Delivery.create({ ticketFk: ticketId, @@ -53,102 +60,105 @@ module.exports = Self => { }, myOptions); } - async function gestDocExists(ticketId) { - const ticketDms = await models.TicketDms.findOne({ - where: {ticketFk: ticketId}, - fields: ['dmsFk'] - }, myOptions); + async function hasSignDms(ticketId) { + const hasTicketDms = await Self.rawSql(` + SELECT d.id + FROM ticketDms td + JOIN dms d ON d.id = td.dmsFk + WHERE td.ticketFk = ? + AND d.dmsTypeFk = ? + `, [ticketId, dmsTypeTicket.id], myOptions); - if (!ticketDms) return false; - - const ticket = await models.Ticket.findById(ticketId, {fields: ['isSigned']}, myOptions); - if (ticket.isSigned == true) - return true; - else - await models.Dms.destroyAll({where: {reference: ticketId}}, myOptions); - - return false; + if (hasTicketDms.length) return true; } - async function createGestDoc(id) { - const ticket = await models.Ticket.findById(id, - { - include: [ - { - relation: 'warehouse', - scope: { - fields: ['id'] - } - }, { - relation: 'client', - scope: { - fields: ['name'] - } - }, { - relation: 'route', - scope: { - fields: ['id'] - } - } - ] - }, myOptions); - const dmsType = await models.DmsType.findOne({where: {code: 'Ticket'}, fields: ['id']}, myOptions); + async function createGestDoc() { const ctxUploadFile = Object.assign({}, ctx); - if (ticket.route() === null) - throw new UserError('Ticket without route'); ctxUploadFile.args = { warehouseId: ticket.warehouseFk, companyId: ticket.companyFk, - dmsTypeId: dmsType.id, - reference: '', + dmsTypeId: dmsTypeTicket.id, + reference: ticket.id, description: `Firma del cliente - Ruta ${ticket.route().id}`, - hasFile: false + hasFile: true }; dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); - gestDocCreated = true; + // Si se ha subido ya la firma, no se vuelve a subir, ya que si no + // da un error de deadlock en la db + isSignUploaded = true; } try { for (const ticketId of tickets) { - const ticketState = await models.TicketState.findOne( - {where: {ticketFk: ticketId}, - fields: ['alertLevel'] - }, myOptions); + ticket = await models.Ticket.findById(ticketId, { + include: [{ + relation: 'address', + scope: { + include: { + relation: 'province', + scope: { + include: { + relation: 'country', + scope: { + fields: ['code'] + } + } + } + } + } + }, { + relation: 'route', + scope: { + fields: ['id'] + } + }] + }, myOptions); - const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, + const ticketState = await models.TicketState.findOne({ + where: {ticketFk: ticketId}, + fields: ['alertLevel'] + }, myOptions); + + const packedAlertLevel = await models.AlertLevel.findOne({ + where: {code: 'PACKED'}, fields: ['id'] }, myOptions); if (!ticketState) throw new UserError('Ticket does not exist'); + if (!ticket.route()) + throw new UserError('Ticket without route'); if (ticketState.alertLevel < packedAlertLevel.id) throw new UserError('This ticket cannot be signed because it has not been boxed'); - if (await gestDocExists(ticketId)) + if (await ticket.isSigned) throw new UserError('Ticket is already signed'); if (location) await setLocation(ticketId); - if (!gestDocCreated) await createGestDoc(ticketId); - await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); - const ticket = await models.Ticket.findById(ticketId, null, myOptions); + if (!await hasSignDms(ticketId) && !isSignUploaded) + await createGestDoc(ticketId); + if (isSignUploaded) + await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); const deliveryState = await models.State.findOne({ - where: { - code: 'DELIVERED' - } + where: {code: 'DELIVERED'} }, myOptions); await models.Ticket.state(ctx, { ticketFk: ticketId, stateFk: deliveryState.id }, myOptions); - } + if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) { + await models.Ticket.saveCmr(ctx, [ticketId], myOptions); + externalTickets.push(ticketId); + } + } if (tx) await tx.commit(); - return; } catch (e) { if (tx) await tx.rollback(); throw e; } + await models.Route.cmrEmail(ctx, externalTickets); }; }; From eba7ef31a280987a7126de6a9704f7ac90cb6b66 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 26 Feb 2024 15:11:02 +0100 Subject: [PATCH 65/78] fix: refs #6513 delete wrong records --- .../00-createSupplierDms.sql | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql index fbdc7ed58..26930880b 100644 --- a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql +++ b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql @@ -1,8 +1,24 @@ +DELETE FROM vn.supplierDms + WHERE dmsFk IN ( + SELECT sd.dmsFk + FROM vn.supplierDms sd + LEFT JOIN vn.dms d ON d.id = sd.dmsFk + WHERE d.id IS NULL + ); + +DELETE FROM vn.supplierDms + WHERE supplierFk IN ( + SELECT sd.supplierFk + FROM vn.supplierDms sd + LEFT JOIN vn.supplier s ON s.id = sd.supplierFk + WHERE s.id IS NULL + ); + ALTER TABLE `vn`.`supplierDms` MODIFY COLUMN supplierFk int(10) unsigned NOT NULL, ADD editorFk INT UNSIGNED NULL, ADD CONSTRAINT user_Fk FOREIGN KEY (editorFk) REFERENCES account.`user`(id), - ADD CONSTRAINT dms_FK FOREIGN KEY (dmsFk) REFERENCES vn.dms(id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT dms_Fk FOREIGN KEY (dmsFk) REFERENCES vn.dms(id) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT supplier_Fk FOREIGN KEY (supplierFk) REFERENCES vn.supplier(id) ON UPDATE CASCADE; ALTER TABLE `supplierLog` From f1329a46247d5381f6562ce6a8ab723864e5c145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 26 Feb 2024 15:43:17 +0100 Subject: [PATCH 66/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/entry_beforeUpdate.sql | 18 ------------------ .../vn/triggers/travel_beforeUpdate.sql | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 1be493a07..a97a90a3d 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -6,7 +6,6 @@ BEGIN DECLARE vIsVirtual BOOL; DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; - DECLARE vHasAnyInvoiceBooked BOOL; SET NEW.editorFk = account.myUser_getId(); @@ -43,22 +42,5 @@ BEGIN CALL supplier_checkIsActive(NEW.supplierFk); SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); END IF; - - IF NOT (NEW.travelFk <=> OLD.travelFk) - OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN - SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); - END IF; - - IF NOT (NEW.invoiceInFk <=> OLD.invoiceInFk)THEN - SELECT COUNT(*) INTO vHasAnyInvoiceBooked - FROM entry e - JOIN invoiceIn ii ON ii.id = e.invoiceInFk - WHERE e.id = NEW.id - AND ii.isBooked; - - IF vHasAnyInvoiceBooked THEN - CALL util.throw('The travel has entries with booked invoices'); - END IF; - END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index 30e0445a5..eef67bcdb 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -3,6 +3,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`travel_beforeUpdate` BEFORE UPDATE ON `travel` FOR EACH ROW BEGIN + DECLARE vHasAnyInvoiceBooked BOOL; + SET NEW.editorFk = account.myUser_getId(); IF NOT (NEW.landed <=> OLD.landed) @@ -17,5 +19,20 @@ BEGIN IF NOT (NEW.warehouseInFk <=> OLD.warehouseInFk) THEN CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); END IF; + + IF NOT (NEW.awbFk <=> OLD.awbFk)THEN + DECLARE vHasAnyInvoiceBooked BOOL; + + SELECT COUNT(*) INTO vHasAnyInvoiceBooked + FROM travel t + JOIN entry e ON e.travelFk = t.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk + WHERE t.id = NEW.id + AND ii.isBooked; + + IF vHasAnyInvoiceBooked THEN + CALL util.throw('The travel has entries with booked invoices'); + END IF; + END IF; END$$ DELIMITER ; From 9cbcd70d4d838d033cb7c57de9c832e133100a63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 26 Feb 2024 15:44:34 +0100 Subject: [PATCH 67/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/entry_beforeUpdate.sql | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index a97a90a3d..60b83002c 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -42,5 +42,10 @@ BEGIN CALL supplier_checkIsActive(NEW.supplierFk); SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); END IF; + + IF NOT (NEW.travelFk <=> OLD.travelFk) + OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN + SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); + END IF; END$$ DELIMITER ; From dcb09cd9f965e02b5361406345af78e7027f87a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 26 Feb 2024 15:54:13 +0100 Subject: [PATCH 68/78] feat: comprobaciones facturas contabilizadas refs #6932 --- db/routines/vn/triggers/travel_beforeUpdate.sql | 2 -- 1 file changed, 2 deletions(-) diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index eef67bcdb..7cc198e3c 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -21,8 +21,6 @@ BEGIN END IF; IF NOT (NEW.awbFk <=> OLD.awbFk)THEN - DECLARE vHasAnyInvoiceBooked BOOL; - SELECT COUNT(*) INTO vHasAnyInvoiceBooked FROM travel t JOIN entry e ON e.travelFk = t.id From 5f20a66ad7379b2e0eb80f860d497ae04c2964a5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 27 Feb 2024 08:50:23 +0100 Subject: [PATCH 69/78] fix: refs #6513 use vn --- db/versions/10908-blueAsparagus/00-createSupplierDms.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql index 26930880b..bc0a40f11 100644 --- a/db/versions/10908-blueAsparagus/00-createSupplierDms.sql +++ b/db/versions/10908-blueAsparagus/00-createSupplierDms.sql @@ -21,5 +21,5 @@ ALTER TABLE `vn`.`supplierDms` ADD CONSTRAINT dms_Fk FOREIGN KEY (dmsFk) REFERENCES vn.dms(id) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT supplier_Fk FOREIGN KEY (supplierFk) REFERENCES vn.supplier(id) ON UPDATE CASCADE; -ALTER TABLE `supplierLog` +ALTER TABLE `vn`.`supplierLog` MODIFY COLUMN `changedModel` ENUM('Supplier','SupplierAddress','SupplierAccount','SupplierContact','SupplierDms') NOT NULL DEFAULT 'Supplier'; \ No newline at end of file From c0988f8d11061b71373e9a5acd4abaa17e68374d Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 27 Feb 2024 09:31:25 +0100 Subject: [PATCH 70/78] fix json --- loopback/locale/es.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 1fd26204c..cf5fb4af4 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -346,5 +346,5 @@ "You cannot update these fields": "No puedes actualizar estos campos", "CountryFK cannot be empty": "El país no puede estar vacío", "Cmr file does not exist": "El archivo del cmr no existe", - "You are not allowed to modify the alias": "No estás autorizado a modificar el alias", + "You are not allowed to modify the alias": "No estás autorizado a modificar el alias" } From a8065ab1a4506419d096ef24b6451efb28728035 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 27 Feb 2024 09:43:53 +0100 Subject: [PATCH 71/78] fix: refs #6184 hasFile false in saveSign and saveCmr --- modules/ticket/back/methods/ticket/saveCmr.js | 2 +- modules/ticket/back/methods/ticket/saveSign.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveCmr.js b/modules/ticket/back/methods/ticket/saveCmr.js index 691af796c..f8d0af8ef 100644 --- a/modules/ticket/back/methods/ticket/saveCmr.js +++ b/modules/ticket/back/methods/ticket/saveCmr.js @@ -63,7 +63,7 @@ module.exports = Self => { warehouseFk: ticket.warehouseFk, reference: ticket.id, contentType: 'application/pdf', - hasFile: true + hasFile: false }; const dms = await models.Dms.createFromStream(data, 'pdf', pdfStream, myOptions); diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index aa970237f..490b05320 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -80,7 +80,7 @@ module.exports = Self => { dmsTypeId: dmsTypeTicket.id, reference: ticket.id, description: `Firma del cliente - Ruta ${ticket.route().id}`, - hasFile: true + hasFile: false }; dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); // Si se ha subido ya la firma, no se vuelve a subir, ya que si no From 699af5b9b73d78a83d2bd41528760624ff4b43cc Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 27 Feb 2024 11:53:55 +0100 Subject: [PATCH 72/78] refs #6531_hotFix_lastTickets --- modules/ticket/back/methods/ticket/myLastModified.js | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/ticket/back/methods/ticket/myLastModified.js b/modules/ticket/back/methods/ticket/myLastModified.js index a47ea570f..096538bfe 100644 --- a/modules/ticket/back/methods/ticket/myLastModified.js +++ b/modules/ticket/back/methods/ticket/myLastModified.js @@ -19,6 +19,7 @@ module.exports = Self => { FROM ticketTracking tt WHERE tt.userFk = ? GROUP BY ticketFk + ORDER BY created DESC LIMIT 5;`; return await Self.rawSql(query, [userId]); }; From c7f527133ed8911350c4083177259350958c855a Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Feb 2024 14:05:43 +0100 Subject: [PATCH 73/78] refs #6053 fixture --- db/dump/fixtures.before.sql | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 7ba85d8d5..060ca7ee9 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -564,13 +564,13 @@ INSERT INTO `vn`.`supplierActivity`(`code`, `name`) INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`, `commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`, `workerFk`, `supplierActivityFk`, `isPayMethodChecked`, `healthRegister`) VALUES - (1, 'PLANTS SL', 'Plants nick', 4100000001, 1, '06089160W', 0, util.VN_CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), - (2, 'FARMER KING', 'The farmer', 4000020002, 1, '87945234L', 0, util.VN_CURDATE(), 1, 'supplier address 2', 'GOTHAM', 2, 43022, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), + (1, 'PLANTS SL', 'Plants nick', 4100000001, 1, '06089160W', 0, util.VN_CURDATE(), 1, 'supplier address 1', 'GOTHAM', 1, 46000, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), + (2, 'FARMER KING', 'The farmer', 4000020002, 1, '87945234L', 0, util.VN_CURDATE(), 1, 'supplier address 2', 'GOTHAM', 2, 46000, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), (69, 'PACKAGING', 'Packaging nick', 4100000069, 1, '94935005K', 0, util.VN_CURDATE(), 1, 'supplier address 5', 'ASGARD', 3, 46600, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), - (442, 'VERDNATURA LEVANTE SL', 'Verdnatura', 5115000442, 1, '06815934E', 0, util.VN_CURDATE(), 1, 'supplier address 3', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), + (442, 'VERDNATURA LEVANTE SL', 'Verdnatura', 5115000442, 1, '06815934E', 0, util.VN_CURDATE(), 1, 'supplier address 3', 'GOTHAM', 1, 46000, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), (567, 'HOLLAND', 'Holland nick', 4000020567, 1, '14364089Z', 0, util.VN_CURDATE(), 1, 'supplier address 6', 'ASGARD', 3, 46600, 1, 2, 10, 93, 2, 8, 18, 'animals', 1, '400664487V'), (791, 'BROS SL', 'Bros nick', 5115000791, 1, '37718083S', 0, util.VN_CURDATE(), 1, 'supplier address 7', 'ASGARD', 3, 46600, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), - (1381, 'ORNAMENTALES', 'Ornamentales', 7185001381, 1, '07972486L', 0, util.VN_CURDATE(), 1, 'supplier address 4', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'); + (1381, 'ORNAMENTALES', 'Ornamentales', 7185001381, 1, '07972486L', 0, util.VN_CURDATE(), 1, 'supplier address 4', 'GOTHAM', 1, 46000, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'); INSERT INTO `vn`.`supplierAddress`(`id`, `supplierFk`, `nickname`, `street`, `provinceFk`, `postalCode`, `city`, `phone`, `mobile`) VALUES From 831da1344ae873d350de3b82989cabfbec3655e5 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Feb 2024 14:21:15 +0100 Subject: [PATCH 74/78] fix jenkins --- Jenkinsfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Jenkinsfile b/Jenkinsfile index 821316c87..9ca7f5d19 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -71,6 +71,7 @@ pipeline { stage('Back') { steps { sh 'pnpm install --prefer-offline' + sh 'pnpx puppeteer browsers install chrome' } } stage('Print') { From 7044a843548b52d4f26e69e09c3f226714fb2008 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Feb 2024 14:26:18 +0100 Subject: [PATCH 75/78] fix puppeteer --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 302738524..588106b4c 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ "mysql": "2.18.1", "node-ssh": "^11.0.0", "object.pick": "^1.3.0", - "puppeteer": "^21.11.0", + "puppeteer": "^22.3.0", "read-chunk": "^3.2.0", "require-yaml": "0.0.1", "smbhash": "0.0.1", From d4133580c4bb98627b11629ae17bb46e2546c515 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Feb 2024 14:30:34 +0100 Subject: [PATCH 76/78] fix pnpm --- pnpm-lock.yaml | 117 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 81 insertions(+), 36 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 36bff2fe1..613b3af2d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -93,8 +93,8 @@ dependencies: specifier: ^1.3.0 version: 1.3.0 puppeteer: - specifier: ^21.11.0 - version: 21.11.0 + specifier: ^22.3.0 + version: 22.3.0 read-chunk: specifier: ^3.2.0 version: 3.2.0 @@ -1916,16 +1916,17 @@ packages: dev: true optional: true - /@puppeteer/browsers@1.9.1: - resolution: {integrity: sha512-PuvK6xZzGhKPvlx3fpfdM2kYY3P/hB1URtK8wA7XUJ6prn6pp22zvJHu48th0SGcHL9SutbPHrFuQgfXTFobWA==} - engines: {node: '>=16.3.0'} + /@puppeteer/browsers@2.1.0: + resolution: {integrity: sha512-xloWvocjvryHdUjDam/ZuGMh7zn4Sn3ZAaV4Ah2e2EwEt90N3XphZlSsU3n0VDc1F7kggCjMuH0UuxfPQ5mD9w==} + engines: {node: '>=18'} hasBin: true dependencies: debug: 4.3.4(supports-color@6.1.0) extract-zip: 2.0.1 progress: 2.0.3 - proxy-agent: 6.3.1 - tar-fs: 3.0.4 + proxy-agent: 6.4.0 + semver: 7.6.0 + tar-fs: 3.0.5 unbzip2-stream: 1.4.3 yargs: 17.7.2 transitivePeerDependencies: @@ -3498,6 +3499,37 @@ packages: /balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + /bare-events@2.2.0: + resolution: {integrity: sha512-Yyyqff4PIFfSuthCZqLlPISTWHmnQxoPuAvkmgzsJEmG3CesdIv6Xweayl0JkCZJSB2yYIdJyEz97tpxNhgjbg==} + requiresBuild: true + dev: false + optional: true + + /bare-fs@2.2.0: + resolution: {integrity: sha512-+VhW202E9eTVGkX7p+TNXtZC4RTzj9JfJW7PtfIbZ7mIQ/QT9uOafQTx7lx2n9ERmWsXvLHF4hStAFn4gl2mQw==} + requiresBuild: true + dependencies: + bare-events: 2.2.0 + bare-os: 2.2.0 + bare-path: 2.1.0 + streamx: 2.15.6 + dev: false + optional: true + + /bare-os@2.2.0: + resolution: {integrity: sha512-hD0rOPfYWOMpVirTACt4/nK8mC55La12K5fY1ij8HAdfQakD62M+H4o4tpfKzVGLgRDTuk3vjA4GqGXXCeFbag==} + requiresBuild: true + dev: false + optional: true + + /bare-path@2.1.0: + resolution: {integrity: sha512-DIIg7ts8bdRKwJRJrUMy/PICEaQZaPGZ26lsSx9MJSwIhSrcdHn7/C8W+XmnG/rKi6BaRcz+JO00CjZteybDtw==} + requiresBuild: true + dependencies: + bare-os: 2.2.0 + dev: false + optional: true + /base64-js@0.0.2: resolution: {integrity: sha512-Pj9L87dCdGcKlSqPVUjD+q96pbIx1zQQLb2CUiWURfjiBELv84YX+0nGnKmyT/9KkC7PQk7UN1w+Al8bBozaxQ==} engines: {node: '>= 0.4'} @@ -4060,12 +4092,12 @@ packages: engines: {node: '>=6.0'} dev: true - /chromium-bidi@0.5.8(devtools-protocol@0.0.1232444): - resolution: {integrity: sha512-blqh+1cEQbHBKmok3rVJkBlBxt9beKBgOsxbFgs7UJcoVbbeZ+K7+6liAsjgpc8l1Xd55cQUy14fXZdGSb4zIw==} + /chromium-bidi@0.5.10(devtools-protocol@0.0.1249869): + resolution: {integrity: sha512-4hsPE1VaLLM/sgNK/SlLbI24Ra7ZOuWAjA3rhw1lVCZ8ZiUgccS6cL5L/iqo4hjRcl5vwgYJ8xTtbXdulA9b6Q==} peerDependencies: devtools-protocol: '*' dependencies: - devtools-protocol: 0.0.1232444 + devtools-protocol: 0.0.1249869 mitt: 3.0.1 urlpattern-polyfill: 10.0.0 dev: false @@ -5049,8 +5081,8 @@ packages: resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==} dev: true - /devtools-protocol@0.0.1232444: - resolution: {integrity: sha512-pM27vqEfxSxRkTMnF+XCmxSEb6duO5R+t8A9DEEJgy4Wz2RVanje2mmj99B6A3zv2r/qGfYlOvYznUhuokizmg==} + /devtools-protocol@0.0.1249869: + resolution: {integrity: sha512-Ctp4hInA0BEavlUoRy9mhGq0i+JSo/AwVyX2EFgZmV1kYB+Zq+EMBAn52QWu6FbRr10hRb6pBl420upbp4++vg==} dev: false /diff-sequences@26.6.2: @@ -7288,8 +7320,8 @@ packages: - supports-color dev: true - /http-proxy-agent@7.0.0: - resolution: {integrity: sha512-+ZT+iBxVUQ1asugqnD6oWoRiS25AkjNfG085dKJGtGxkdwLQrMKU5wJr2bOOFAXzKcTuqq+7fZlTMgG3SRfIYQ==} + /http-proxy-agent@7.0.2: + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} engines: {node: '>= 14'} dependencies: agent-base: 7.1.0 @@ -7367,8 +7399,8 @@ packages: transitivePeerDependencies: - supports-color - /https-proxy-agent@7.0.2: - resolution: {integrity: sha512-NmLNjm6ucYwtcUmL7JQC1ZQ57LmHP4lT15FQ8D61nak1rO6DH+fz5qNK2Ap5UN4ZapYICE3/0KodcLYSPsPbaA==} + /https-proxy-agent@7.0.4: + resolution: {integrity: sha512-wlwpilI7YdjSkWaQ/7omYBMTliDcmCN8OLihO6I9B86g06lMyAoqgoDpV0XqoaPOKj+0DIdAvnsWfyAAhmimcg==} engines: {node: '>= 14'} dependencies: agent-base: 7.1.0 @@ -9780,7 +9812,9 @@ packages: /mkdirp-classic@0.5.3: resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} + requiresBuild: true dev: false + optional: true /mkdirp@0.3.0: resolution: {integrity: sha512-OHsdUcVAQ6pOtg5JYWpCBo9W/GySVuwvP9hueRMW7UqshC0tbfzLv8wjySTPm3tfUZ/21CE9E1pJagOA91Pxew==} @@ -10692,8 +10726,8 @@ packages: agent-base: 7.1.0 debug: 4.3.4(supports-color@6.1.0) get-uri: 6.0.2 - http-proxy-agent: 7.0.0 - https-proxy-agent: 7.0.2 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.4 pac-resolver: 7.0.0 socks-proxy-agent: 8.0.2 transitivePeerDependencies: @@ -11149,14 +11183,14 @@ packages: forwarded: 0.2.0 ipaddr.js: 1.9.1 - /proxy-agent@6.3.1: - resolution: {integrity: sha512-Rb5RVBy1iyqOtNl15Cw/llpeLH8bsb37gM1FUfKQ+Wck6xHlbAhWGUFiTRHtkjqGTA5pSHz6+0hrPW/oECihPQ==} + /proxy-agent@6.4.0: + resolution: {integrity: sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==} engines: {node: '>= 14'} dependencies: agent-base: 7.1.0 debug: 4.3.4(supports-color@6.1.0) - http-proxy-agent: 7.0.0 - https-proxy-agent: 7.0.2 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.4 lru-cache: 7.18.3 pac-proxy-agent: 7.0.1 proxy-from-env: 1.1.0 @@ -11222,15 +11256,15 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} - /puppeteer-core@21.11.0: - resolution: {integrity: sha512-ArbnyA3U5SGHokEvkfWjW+O8hOxV1RSJxOgriX/3A4xZRqixt9ZFHD0yPgZQF05Qj0oAqi8H/7stDorjoHY90Q==} - engines: {node: '>=16.13.2'} + /puppeteer-core@22.3.0: + resolution: {integrity: sha512-Ho5Vdpdro05ZyCx/l5Hkc5vHiibKTaY37fIAD9NF9Gi/vDxkVTeX40U/mFnEmeoxyuYALvWCJfi7JTT82R6Tuw==} + engines: {node: '>=18'} dependencies: - '@puppeteer/browsers': 1.9.1 - chromium-bidi: 0.5.8(devtools-protocol@0.0.1232444) + '@puppeteer/browsers': 2.1.0 + chromium-bidi: 0.5.10(devtools-protocol@0.0.1249869) cross-fetch: 4.0.0 debug: 4.3.4(supports-color@6.1.0) - devtools-protocol: 0.0.1232444 + devtools-protocol: 0.0.1249869 ws: 8.16.0 transitivePeerDependencies: - bufferutil @@ -11239,15 +11273,15 @@ packages: - utf-8-validate dev: false - /puppeteer@21.11.0: - resolution: {integrity: sha512-9jTHuYe22TD3sNxy0nEIzC7ZrlRnDgeX3xPkbS7PnbdwYjl2o/z/YuCrRBwezdKpbTDTJ4VqIggzNyeRcKq3cg==} - engines: {node: '>=16.13.2'} + /puppeteer@22.3.0: + resolution: {integrity: sha512-GC+tyjzYKjaNjhlDAuqRgDM+IOsqOG75Da4L28G4eULNLLxKDt+79x2OOSQ47HheJBgGq7ATSExNE6gayxP6cg==} + engines: {node: '>=18'} hasBin: true requiresBuild: true dependencies: - '@puppeteer/browsers': 1.9.1 + '@puppeteer/browsers': 2.1.0 cosmiconfig: 9.0.0 - puppeteer-core: 21.11.0 + puppeteer-core: 22.3.0 transitivePeerDependencies: - bufferutil - encoding @@ -11288,6 +11322,7 @@ packages: /queue-tick@1.0.1: resolution: {integrity: sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==} + requiresBuild: true dev: false /quick-lru@4.0.1: @@ -11987,6 +12022,14 @@ packages: dependencies: lru-cache: 6.0.0 + /semver@7.6.0: + resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==} + engines: {node: '>=10'} + hasBin: true + dependencies: + lru-cache: 6.0.0 + dev: false + /send@0.18.0(supports-color@6.1.0): resolution: {integrity: sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==} engines: {node: '>= 0.8.0'} @@ -12986,12 +13029,14 @@ packages: dev: false optional: true - /tar-fs@3.0.4: - resolution: {integrity: sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==} + /tar-fs@3.0.5: + resolution: {integrity: sha512-JOgGAmZyMgbqpLwct7ZV8VzkEB6pxXFBVErLtb+XCOqzc6w1xiWKI9GVd6bwk68EX7eJ4DWmfXVmq8K2ziZTGg==} dependencies: - mkdirp-classic: 0.5.3 pump: 3.0.0 tar-stream: 3.1.7 + optionalDependencies: + bare-fs: 2.2.0 + bare-path: 2.1.0 dev: false /tar-stream@1.6.2: From 7316673a0bb22b2b836ad07f62db155da8fb3676 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Feb 2024 14:51:08 +0100 Subject: [PATCH 77/78] fix pnpm --- package.json | 2 +- pnpm-lock.yaml | 101 ++++++++++++++----------------------------------- 2 files changed, 30 insertions(+), 73 deletions(-) diff --git a/package.json b/package.json index 588106b4c..302738524 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ "mysql": "2.18.1", "node-ssh": "^11.0.0", "object.pick": "^1.3.0", - "puppeteer": "^22.3.0", + "puppeteer": "^21.11.0", "read-chunk": "^3.2.0", "require-yaml": "0.0.1", "smbhash": "0.0.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 613b3af2d..3e335c06c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -93,8 +93,8 @@ dependencies: specifier: ^1.3.0 version: 1.3.0 puppeteer: - specifier: ^22.3.0 - version: 22.3.0 + specifier: ^21.11.0 + version: 21.11.0 read-chunk: specifier: ^3.2.0 version: 3.2.0 @@ -1916,17 +1916,16 @@ packages: dev: true optional: true - /@puppeteer/browsers@2.1.0: - resolution: {integrity: sha512-xloWvocjvryHdUjDam/ZuGMh7zn4Sn3ZAaV4Ah2e2EwEt90N3XphZlSsU3n0VDc1F7kggCjMuH0UuxfPQ5mD9w==} - engines: {node: '>=18'} + /@puppeteer/browsers@1.9.1: + resolution: {integrity: sha512-PuvK6xZzGhKPvlx3fpfdM2kYY3P/hB1URtK8wA7XUJ6prn6pp22zvJHu48th0SGcHL9SutbPHrFuQgfXTFobWA==} + engines: {node: '>=16.3.0'} hasBin: true dependencies: debug: 4.3.4(supports-color@6.1.0) extract-zip: 2.0.1 progress: 2.0.3 - proxy-agent: 6.4.0 - semver: 7.6.0 - tar-fs: 3.0.5 + proxy-agent: 6.3.1 + tar-fs: 3.0.4 unbzip2-stream: 1.4.3 yargs: 17.7.2 transitivePeerDependencies: @@ -3499,37 +3498,6 @@ packages: /balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - /bare-events@2.2.0: - resolution: {integrity: sha512-Yyyqff4PIFfSuthCZqLlPISTWHmnQxoPuAvkmgzsJEmG3CesdIv6Xweayl0JkCZJSB2yYIdJyEz97tpxNhgjbg==} - requiresBuild: true - dev: false - optional: true - - /bare-fs@2.2.0: - resolution: {integrity: sha512-+VhW202E9eTVGkX7p+TNXtZC4RTzj9JfJW7PtfIbZ7mIQ/QT9uOafQTx7lx2n9ERmWsXvLHF4hStAFn4gl2mQw==} - requiresBuild: true - dependencies: - bare-events: 2.2.0 - bare-os: 2.2.0 - bare-path: 2.1.0 - streamx: 2.15.6 - dev: false - optional: true - - /bare-os@2.2.0: - resolution: {integrity: sha512-hD0rOPfYWOMpVirTACt4/nK8mC55La12K5fY1ij8HAdfQakD62M+H4o4tpfKzVGLgRDTuk3vjA4GqGXXCeFbag==} - requiresBuild: true - dev: false - optional: true - - /bare-path@2.1.0: - resolution: {integrity: sha512-DIIg7ts8bdRKwJRJrUMy/PICEaQZaPGZ26lsSx9MJSwIhSrcdHn7/C8W+XmnG/rKi6BaRcz+JO00CjZteybDtw==} - requiresBuild: true - dependencies: - bare-os: 2.2.0 - dev: false - optional: true - /base64-js@0.0.2: resolution: {integrity: sha512-Pj9L87dCdGcKlSqPVUjD+q96pbIx1zQQLb2CUiWURfjiBELv84YX+0nGnKmyT/9KkC7PQk7UN1w+Al8bBozaxQ==} engines: {node: '>= 0.4'} @@ -3818,7 +3786,7 @@ packages: resolution: {integrity: sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==} dependencies: base64-js: 1.5.1 - ieee754: 1.1.13 + ieee754: 1.2.1 isarray: 1.0.0 dev: false @@ -4092,12 +4060,12 @@ packages: engines: {node: '>=6.0'} dev: true - /chromium-bidi@0.5.10(devtools-protocol@0.0.1249869): - resolution: {integrity: sha512-4hsPE1VaLLM/sgNK/SlLbI24Ra7ZOuWAjA3rhw1lVCZ8ZiUgccS6cL5L/iqo4hjRcl5vwgYJ8xTtbXdulA9b6Q==} + /chromium-bidi@0.5.8(devtools-protocol@0.0.1232444): + resolution: {integrity: sha512-blqh+1cEQbHBKmok3rVJkBlBxt9beKBgOsxbFgs7UJcoVbbeZ+K7+6liAsjgpc8l1Xd55cQUy14fXZdGSb4zIw==} peerDependencies: devtools-protocol: '*' dependencies: - devtools-protocol: 0.0.1249869 + devtools-protocol: 0.0.1232444 mitt: 3.0.1 urlpattern-polyfill: 10.0.0 dev: false @@ -5081,8 +5049,8 @@ packages: resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==} dev: true - /devtools-protocol@0.0.1249869: - resolution: {integrity: sha512-Ctp4hInA0BEavlUoRy9mhGq0i+JSo/AwVyX2EFgZmV1kYB+Zq+EMBAn52QWu6FbRr10hRb6pBl420upbp4++vg==} + /devtools-protocol@0.0.1232444: + resolution: {integrity: sha512-pM27vqEfxSxRkTMnF+XCmxSEb6duO5R+t8A9DEEJgy4Wz2RVanje2mmj99B6A3zv2r/qGfYlOvYznUhuokizmg==} dev: false /diff-sequences@26.6.2: @@ -9814,7 +9782,6 @@ packages: resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} requiresBuild: true dev: false - optional: true /mkdirp@0.3.0: resolution: {integrity: sha512-OHsdUcVAQ6pOtg5JYWpCBo9W/GySVuwvP9hueRMW7UqshC0tbfzLv8wjySTPm3tfUZ/21CE9E1pJagOA91Pxew==} @@ -11183,8 +11150,8 @@ packages: forwarded: 0.2.0 ipaddr.js: 1.9.1 - /proxy-agent@6.4.0: - resolution: {integrity: sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==} + /proxy-agent@6.3.1: + resolution: {integrity: sha512-Rb5RVBy1iyqOtNl15Cw/llpeLH8bsb37gM1FUfKQ+Wck6xHlbAhWGUFiTRHtkjqGTA5pSHz6+0hrPW/oECihPQ==} engines: {node: '>= 14'} dependencies: agent-base: 7.1.0 @@ -11256,15 +11223,15 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} - /puppeteer-core@22.3.0: - resolution: {integrity: sha512-Ho5Vdpdro05ZyCx/l5Hkc5vHiibKTaY37fIAD9NF9Gi/vDxkVTeX40U/mFnEmeoxyuYALvWCJfi7JTT82R6Tuw==} - engines: {node: '>=18'} + /puppeteer-core@21.11.0: + resolution: {integrity: sha512-ArbnyA3U5SGHokEvkfWjW+O8hOxV1RSJxOgriX/3A4xZRqixt9ZFHD0yPgZQF05Qj0oAqi8H/7stDorjoHY90Q==} + engines: {node: '>=16.13.2'} dependencies: - '@puppeteer/browsers': 2.1.0 - chromium-bidi: 0.5.10(devtools-protocol@0.0.1249869) + '@puppeteer/browsers': 1.9.1 + chromium-bidi: 0.5.8(devtools-protocol@0.0.1232444) cross-fetch: 4.0.0 debug: 4.3.4(supports-color@6.1.0) - devtools-protocol: 0.0.1249869 + devtools-protocol: 0.0.1232444 ws: 8.16.0 transitivePeerDependencies: - bufferutil @@ -11273,15 +11240,15 @@ packages: - utf-8-validate dev: false - /puppeteer@22.3.0: - resolution: {integrity: sha512-GC+tyjzYKjaNjhlDAuqRgDM+IOsqOG75Da4L28G4eULNLLxKDt+79x2OOSQ47HheJBgGq7ATSExNE6gayxP6cg==} - engines: {node: '>=18'} + /puppeteer@21.11.0: + resolution: {integrity: sha512-9jTHuYe22TD3sNxy0nEIzC7ZrlRnDgeX3xPkbS7PnbdwYjl2o/z/YuCrRBwezdKpbTDTJ4VqIggzNyeRcKq3cg==} + engines: {node: '>=16.13.2'} hasBin: true requiresBuild: true dependencies: - '@puppeteer/browsers': 2.1.0 + '@puppeteer/browsers': 1.9.1 cosmiconfig: 9.0.0 - puppeteer-core: 22.3.0 + puppeteer-core: 21.11.0 transitivePeerDependencies: - bufferutil - encoding @@ -12022,14 +11989,6 @@ packages: dependencies: lru-cache: 6.0.0 - /semver@7.6.0: - resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==} - engines: {node: '>=10'} - hasBin: true - dependencies: - lru-cache: 6.0.0 - dev: false - /send@0.18.0(supports-color@6.1.0): resolution: {integrity: sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==} engines: {node: '>= 0.8.0'} @@ -13029,14 +12988,12 @@ packages: dev: false optional: true - /tar-fs@3.0.5: - resolution: {integrity: sha512-JOgGAmZyMgbqpLwct7ZV8VzkEB6pxXFBVErLtb+XCOqzc6w1xiWKI9GVd6bwk68EX7eJ4DWmfXVmq8K2ziZTGg==} + /tar-fs@3.0.4: + resolution: {integrity: sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==} dependencies: + mkdirp-classic: 0.5.3 pump: 3.0.0 tar-stream: 3.1.7 - optionalDependencies: - bare-fs: 2.2.0 - bare-path: 2.1.0 dev: false /tar-stream@1.6.2: From 0af17fb081fcb4c3f2d1805719a9c4f7c95ae074 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 29 Feb 2024 10:22:19 +0100 Subject: [PATCH 78/78] refs #6956 deploy: init version 2412 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 302738524..3a442cac5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.10.0", + "version": "24.12.0", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0",