From c2de5c5ff4fa4c07f9c6721b540832d566778b52 Mon Sep 17 00:00:00 2001 From: alexandre Date: Tue, 2 May 2023 07:28:59 +0200 Subject: [PATCH 01/30] refs #4797 added redirection section --- db/dump/fixtures.sql | 7 +++++- loopback/locale/es.json | 23 ++++++++++--------- modules/client/back/models/client.json | 2 +- modules/worker/front/index.js | 1 + modules/worker/front/notifications/index.html | 2 ++ modules/worker/front/notifications/index.js | 21 +++++++++++++++++ modules/worker/front/routes.json | 9 ++++++++ 7 files changed, 52 insertions(+), 13 deletions(-) create mode 100644 modules/worker/front/notifications/index.html create mode 100644 modules/worker/front/notifications/index.js diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 15ccece35..6554adc33 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2723,7 +2723,10 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`) INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) VALUES - (1, 9); + (1, 9), + (1, 1), + (2, 1), + (4, 1); INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`) VALUES @@ -2735,6 +2738,8 @@ INSERT INTO `util`.`notificationSubscription` (`notificationFk`, `userFk`) VALUES (1, 1109), (1, 1110), + (2, 1110), + (4, 1110), (2, 1109), (1,9), (1,3); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 3ef3c4a22..628f7ace6 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -279,15 +279,16 @@ "Comment added to client": "Observación añadida al cliente {{clientFk}}", "Cannot create a new claimBeginning from a different ticket": "No se puede crear una línea de reclamación de un ticket diferente al origen", "company": "Compañía", - "country": "País", - "clientId": "Id cliente", - "clientSocialName": "Cliente", - "amount": "Importe", - "taxableBase": "Base", - "ticketFk": "Id ticket", - "isActive": "Activo", - "hasToInvoice": "Facturar", - "isTaxDataChecked": "Datos comprobados", - "comercialId": "Id comercial", - "comercialName": "Comercial" + "country": "País", + "clientId": "Id cliente", + "clientSocialName": "Cliente", + "amount": "Importe", + "taxableBase": "Base", + "ticketFk": "Id ticket", + "isActive": "Activo", + "hasToInvoice": "Facturar", + "isTaxDataChecked": "Datos comprobados", + "comercialId": "Id comercial", + "comercialName": "Comercial", + "You dont have permission to modify this user": "No tienes permiso para modificar este usuario" } diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index 5f56a1ed2..73b6cccb4 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -158,7 +158,7 @@ }, "user": { "type": "belongsTo", - "model": "Account", + "model": "VnUser", "foreignKey": "id" }, "payMethod": { diff --git a/modules/worker/front/index.js b/modules/worker/front/index.js index 8fad2c0df..5c03dc8de 100644 --- a/modules/worker/front/index.js +++ b/modules/worker/front/index.js @@ -20,4 +20,5 @@ import './dms/create'; import './dms/edit'; import './note/index'; import './note/create'; +import './notifications'; diff --git a/modules/worker/front/notifications/index.html b/modules/worker/front/notifications/index.html new file mode 100644 index 000000000..7fb3b870e --- /dev/null +++ b/modules/worker/front/notifications/index.html @@ -0,0 +1,2 @@ + + diff --git a/modules/worker/front/notifications/index.js b/modules/worker/front/notifications/index.js new file mode 100644 index 000000000..622892979 --- /dev/null +++ b/modules/worker/front/notifications/index.js @@ -0,0 +1,21 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; + +class Controller extends Section { + constructor($element, $) { + super($element, $); + } + + async $onInit() { + const url = await this.vnApp.getUrl(`worker/${this.$params.id}/notifications`); + window.open(url).focus(); + } +} + +ngModule.vnComponent('vnWorkerNotifications', { + template: require('./index.html'), + controller: Controller, + bindings: { + ticket: '<' + } +}); diff --git a/modules/worker/front/routes.json b/modules/worker/front/routes.json index 25a0ffbcf..bce0172a2 100644 --- a/modules/worker/front/routes.json +++ b/modules/worker/front/routes.json @@ -15,6 +15,7 @@ {"state": "worker.card.timeControl", "icon": "access_time"}, {"state": "worker.card.calendar", "icon": "icon-calendar"}, {"state": "worker.card.pda", "icon": "phone_android"}, + {"state": "worker.card.notifications", "icon": "notifications"}, {"state": "worker.card.pbx", "icon": "icon-pbx"}, {"state": "worker.card.dms.index", "icon": "cloud_upload"}, { @@ -109,6 +110,14 @@ "params": { "worker": "$ctrl.worker" } + }, { + "url": "/notifications", + "state": "worker.card.notifications", + "component": "vn-worker-notifications", + "description": "Notifications", + "params": { + "worker": "$ctrl.worker" + } }, { "url": "/time-control?timestamp", "state": "worker.card.timeControl", From 70c46efe275e0e518c884d8e76eedf4174f02ec9 Mon Sep 17 00:00:00 2001 From: alexandre Date: Tue, 2 May 2023 09:51:04 +0200 Subject: [PATCH 02/30] refs #4797 fix back test --- .../specs/notificationSubscription.spec.js | 23 ++++++++----------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/back/models/specs/notificationSubscription.spec.js b/back/models/specs/notificationSubscription.spec.js index c7f37abed..c5ef698fd 100644 --- a/back/models/specs/notificationSubscription.spec.js +++ b/back/models/specs/notificationSubscription.spec.js @@ -1,8 +1,9 @@ const models = require('vn-loopback/server/server').models; describe('loopback model NotificationSubscription', () => { - it('Should fail to delete a notification if the user is not editing itself or a subordinate', async() => { + it('should fail to delete a notification if the user is not editing itself or a subordinate', async() => { const tx = await models.NotificationSubscription.beginTransaction({}); + let error; try { const options = {transaction: tx}; @@ -11,29 +12,23 @@ describe('loopback model NotificationSubscription', () => { const ctx = {req: {accessToken: {userId: user}}}; const notification = await models.NotificationSubscription.findById(notificationSubscriptionId); - let error; - - try { - await models.NotificationSubscription.deleteNotification(ctx, notification.id, options); - } catch (e) { - error = e; - } + await models.NotificationSubscription.deleteNotification(ctx, notification.id, options); expect(error.message).toContain('You dont have permission to modify this user'); await tx.rollback(); } catch (e) { + error = e; await tx.rollback(); - throw e; } }); - it('Should delete a notification if the user is editing itself', async() => { + it('should delete a notification if the user is editing itself', async() => { const tx = await models.NotificationSubscription.beginTransaction({}); try { const options = {transaction: tx}; const user = 9; - const notificationSubscriptionId = 4; + const notificationSubscriptionId = 6; const ctx = {req: {accessToken: {userId: user}}}; const notification = await models.NotificationSubscription.findById(notificationSubscriptionId); @@ -49,13 +44,13 @@ describe('loopback model NotificationSubscription', () => { } }); - it('Should delete a notification if the user is editing a subordinate', async() => { + it('should delete a notification if the user is editing a subordinate', async() => { const tx = await models.NotificationSubscription.beginTransaction({}); try { const options = {transaction: tx}; - const user = 9; - const notificationSubscriptionId = 5; + const user = 19; + const notificationSubscriptionId = 4; const ctx = {req: {accessToken: {userId: user}}}; const notification = await models.NotificationSubscription.findById(notificationSubscriptionId); From 4c0ec6faf53a4118a46e97ddc1b59d7d71651341 Mon Sep 17 00:00:00 2001 From: alexandre Date: Tue, 2 May 2023 14:26:47 +0200 Subject: [PATCH 03/30] changedModel sms --- e2e/paths/13-supplier/03_fiscal_data.spec.js | 2 +- modules/client/back/methods/client/sendSms.js | 2 +- modules/ticket/back/methods/ticket/sendSms.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/e2e/paths/13-supplier/03_fiscal_data.spec.js b/e2e/paths/13-supplier/03_fiscal_data.spec.js index 31b3fafd2..170a8d05a 100644 --- a/e2e/paths/13-supplier/03_fiscal_data.spec.js +++ b/e2e/paths/13-supplier/03_fiscal_data.spec.js @@ -15,7 +15,7 @@ const $inputs = { sageTaxType: 'vn-supplier-fiscal-data [ng-model="$ctrl.supplier.sageTaxTypeFk"]' }; -fdescribe('Supplier fiscal data path', () => { +describe('Supplier fiscal data path', () => { let browser; let page; diff --git a/modules/client/back/methods/client/sendSms.js b/modules/client/back/methods/client/sendSms.js index 9d6a12416..456d1d621 100644 --- a/modules/client/back/methods/client/sendSms.js +++ b/modules/client/back/methods/client/sendSms.js @@ -44,7 +44,7 @@ module.exports = Self => { originFk: id, userFk: userId, action: 'insert', - changedModel: 'sms', + changedModel: 'Sms', newInstance: { destinationFk: id, destination: destination, diff --git a/modules/ticket/back/methods/ticket/sendSms.js b/modules/ticket/back/methods/ticket/sendSms.js index 2336ae859..3c361b783 100644 --- a/modules/ticket/back/methods/ticket/sendSms.js +++ b/modules/ticket/back/methods/ticket/sendSms.js @@ -58,7 +58,7 @@ module.exports = Self => { originFk: id, userFk: userId, action: 'insert', - changedModel: 'sms', + changedModel: 'Sms', newInstance: { destinationFk: id, destination: destination, From e7d16dc8baf1e26c8a02cd7f80082b49967a1f9d Mon Sep 17 00:00:00 2001 From: alexandre Date: Tue, 9 May 2023 11:34:32 +0200 Subject: [PATCH 04/30] refs #4797 fix test, add getList --- back/methods/notification/getList.js | 80 ++++++++++++ .../notification/specs/getList.spec.js | 38 ++++++ back/models/notificationSubscription.js | 76 ++++------- .../specs/notificationSubscription.spec.js | 123 +++++++++++++----- .../232001/00-notificationSubscription.sql | 3 + loopback/locale/es.json | 3 +- 6 files changed, 240 insertions(+), 83 deletions(-) create mode 100644 back/methods/notification/getList.js create mode 100644 back/methods/notification/specs/getList.spec.js create mode 100644 db/changes/232001/00-notificationSubscription.sql diff --git a/back/methods/notification/getList.js b/back/methods/notification/getList.js new file mode 100644 index 000000000..9f3367184 --- /dev/null +++ b/back/methods/notification/getList.js @@ -0,0 +1,80 @@ +module.exports = Self => { + Self.remoteMethod('getList', { + description: 'Get list of the available and active notification subscriptions', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'number', + description: 'User to modify', + http: {source: 'path'} + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:id/getList`, + verb: 'GET' + } + }); + + Self.getList = async(id, options) => { + const notifications = []; + const models = Self.app.models; + + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const activeNotifications = await models.NotificationSubscription.find({ + include: {relation: 'notification'}, + where: {userFk: id} + }, myOptions); + + const roles = await models.RoleMapping.find({ + fields: ['roleId'], + where: {principalId: id} + }, myOptions); + + const availableNotifications = await models.NotificationAcl.find({ + include: {relation: 'notification'}, + where: { + roleFk: { + inq: roles.map(role => { + return role.roleId; + }), + }, + } + }, myOptions); + + activeNotifications.forEach(subscription => { + notifications.push({ + id: subscription.id, + notificationFk: subscription.notificationFk, + name: subscription.notification().name, + description: subscription.notification().description, + active: true + }); + }); + + availableNotifications.forEach(acl => { + const activeNotif = notifications.find( + notif => notif.notificationFk === acl.notificationFk + ); + if (!activeNotif) { + notifications.push({ + id: null, + notificationFk: acl.notificationFk, + name: acl.notification().name, + description: acl.notification().description, + active: false, + }); + } + }); + + return notifications; + }; +}; diff --git a/back/methods/notification/specs/getList.spec.js b/back/methods/notification/specs/getList.spec.js new file mode 100644 index 000000000..b220f2215 --- /dev/null +++ b/back/methods/notification/specs/getList.spec.js @@ -0,0 +1,38 @@ +const models = require('vn-loopback/server/server').models; + +describe('NotificationSubscription getList()', () => { + it('should return a list of available and active notifications of a user', async() => { + const userId = 1109; + const activeNotifications = await models.NotificationSubscription.find({ + where: {userFk: userId} + }); + const roles = await models.RoleMapping.find({ + fields: ['roleId'], + where: {principalId: userId} + }); + const availableNotifications = await models.NotificationAcl.find({ + where: { + roleFk: { + inq: roles.map(role => { + return role.roleId; + }), + }, + } + }); + + const result = await models.NotificationSubscription.getList(userId); + + expect(result.filter(notification => notification.active == true).length) + .toEqual(activeNotifications.length); + + expect(result.filter(notification => notification.active == false).length) + .toEqual(availableNotifications.length - activeNotifications.length); + }); + + it('should return empty from a non existent user', async() => { + const userId = 123456789; + const result = await models.NotificationSubscription.getList(userId); + + expect(result.length).toEqual(0); + }); +}); diff --git a/back/models/notificationSubscription.js b/back/models/notificationSubscription.js index f1b2811fa..a4d4a8bac 100644 --- a/back/models/notificationSubscription.js +++ b/back/models/notificationSubscription.js @@ -1,62 +1,40 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { + require('../methods/notification/getList')(Self); + Self.observe('before save', async function(ctx) { + await checkModifyPermission(ctx); + }); + + Self.observe('before delete', async function(ctx) { + await checkModifyPermission(ctx); + }); + + async function checkModifyPermission(ctx) { const models = Self.app.models; + const instance = ctx.instance; const userId = ctx.options.accessToken.userId; - const user = await ctx.instance.userFk; - const modifiedUser = await getUserToModify(null, user, models); - if (userId != modifiedUser.id && userId != modifiedUser.bossFk) - throw new UserError('You dont have permission to modify this user'); - }); + let notificationFk; + let workerId; - Self.remoteMethod('deleteNotification', { - description: 'Deletes a notification subscription', - accepts: [ - { - arg: 'ctx', - type: 'object', - http: {source: 'context'} - }, - { - arg: 'notificationId', - type: 'number', - required: true - }, - ], - returns: { - type: 'object', - root: true - }, - http: { - verb: 'POST', - path: '/deleteNotification' + if (instance) { + notificationFk = instance.notificationFk; + workerId = instance.userFk; + } else { + const notificationSubscription = await models.NotificationSubscription.findById(ctx.where.id); + notificationFk = notificationSubscription.notificationFk; + workerId = notificationSubscription.userFk; } - }); - Self.deleteNotification = async function(ctx, notificationId) { - const models = Self.app.models; - const user = ctx.req.accessToken.userId; - const modifiedUser = await getUserToModify(notificationId, null, models); - - if (user != modifiedUser.id && user != modifiedUser.bossFk) - throw new UserError('You dont have permission to modify this user'); - - await models.NotificationSubscription.destroyById(notificationId); - }; - - async function getUserToModify(notificationId, userFk, models) { - let userToModify = userFk; - if (notificationId) { - const subscription = await models.NotificationSubscription.findById(notificationId); - userToModify = subscription.userFk; - } - return await models.Worker.findOne({ - fields: ['id', 'bossFk'], - where: { - id: userToModify - } + const worker = await models.Worker.findById(workerId, {fields: ['id', 'bossFk']}); + const notificationsAvailables = await models.NotificationSubscription.getList(workerId); + const hasAcl = notificationsAvailables.some(function(available) { + return available.notificationFk === notificationFk; }); + + if (!hasAcl || (userId != worker.id && userId != worker.bossFk)) + throw new UserError('The notification subscription of this worker cant be modified'); } }; diff --git a/back/models/specs/notificationSubscription.spec.js b/back/models/specs/notificationSubscription.spec.js index c5ef698fd..c2adcbc59 100644 --- a/back/models/specs/notificationSubscription.spec.js +++ b/back/models/specs/notificationSubscription.spec.js @@ -1,69 +1,126 @@ const models = require('vn-loopback/server/server').models; describe('loopback model NotificationSubscription', () => { - it('should fail to delete a notification if the user is not editing itself or a subordinate', async() => { + it('should fail to add a notification subscription if the worker doesnt have ACLs', async() => { const tx = await models.NotificationSubscription.beginTransaction({}); let error; try { - const options = {transaction: tx}; - const user = 9; - const notificationSubscriptionId = 2; - const ctx = {req: {accessToken: {userId: user}}}; - const notification = await models.NotificationSubscription.findById(notificationSubscriptionId); + const options = {transaction: tx, accessToken: {userId: 9}}; + await models.NotificationSubscription.create({notificationFk: 1, userFk: 62}, options); - await models.NotificationSubscription.deleteNotification(ctx, notification.id, options); - - expect(error.message).toContain('You dont have permission to modify this user'); await tx.rollback(); } catch (e) { + await tx.rollback(); error = e; - await tx.rollback(); } + + expect(error.message).toEqual('The notification subscription of this worker cant be modified'); }); - it('should delete a notification if the user is editing itself', async() => { + it('should fail to add a notification subscription if the user isnt editing itself or subordinate', async() => { const tx = await models.NotificationSubscription.beginTransaction({}); + let error; try { - const options = {transaction: tx}; - const user = 9; + const options = {transaction: tx, accessToken: {userId: 1}}; + await models.NotificationSubscription.create({notificationFk: 1, userFk: 9}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual('The notification subscription of this worker cant be modified'); + }); + + it('should fail to delete a notification subscription if the user isnt editing itself or subordinate', async() => { + const tx = await models.NotificationSubscription.beginTransaction({}); + let error; + + try { + const options = {transaction: tx, accessToken: {userId: 9}}; + const notificationSubscriptionId = 2; + await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual('The notification subscription of this worker cant be modified'); + }); + + it('should add a notification subscription if the user is editing itself', async() => { + const tx = await models.NotificationSubscription.beginTransaction({}); + let error; + + try { + const options = {transaction: tx, accessToken: {userId: 9}}; + await models.NotificationSubscription.create({notificationFk: 2, userFk: 9}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toBeUndefined(); + }); + + it('should delete a notification subscription if the user is editing itself', async() => { + const tx = await models.NotificationSubscription.beginTransaction({}); + let error; + + try { + const options = {transaction: tx, accessToken: {userId: 9}}; const notificationSubscriptionId = 6; - const ctx = {req: {accessToken: {userId: user}}}; - const notification = await models.NotificationSubscription.findById(notificationSubscriptionId); + await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options); - await models.NotificationSubscription.deleteNotification(ctx, notification.id, options); - - const deletedNotification = await models.NotificationSubscription.findById(notificationSubscriptionId); - - expect(deletedNotification).toBeNull(); await tx.rollback(); } catch (e) { await tx.rollback(); - throw e; + error = e; } + + expect(error).toBeUndefined(); }); - it('should delete a notification if the user is editing a subordinate', async() => { + it('should add a notification subscription if the user is editing a subordinate', async() => { const tx = await models.NotificationSubscription.beginTransaction({}); + let error; try { - const options = {transaction: tx}; - const user = 19; - const notificationSubscriptionId = 4; - const ctx = {req: {accessToken: {userId: user}}}; - const notification = await models.NotificationSubscription.findById(notificationSubscriptionId); + const options = {transaction: tx, accessToken: {userId: 9}}; + await models.NotificationSubscription.create({notificationFk: 1, userFk: 5}, options); - await models.NotificationSubscription.deleteNotification(ctx, notification.id, options); - - const deletedNotification = await models.NotificationSubscription.findById(notificationSubscriptionId); - - expect(deletedNotification).toBeNull(); await tx.rollback(); } catch (e) { await tx.rollback(); - throw e; + error = e; } + + expect(error).toBeUndefined(); + }); + + it('should delete a notification subscription if the user is editing a subordinate', async() => { + const tx = await models.NotificationSubscription.beginTransaction({}); + let error; + + try { + const options = {transaction: tx, accessToken: {userId: 19}}; + const notificationSubscriptionId = 4; + await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toBeUndefined(); }); }); diff --git a/db/changes/232001/00-notificationSubscription.sql b/db/changes/232001/00-notificationSubscription.sql new file mode 100644 index 000000000..ef081437d --- /dev/null +++ b/db/changes/232001/00-notificationSubscription.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('NotificationSubscription', 'getList', 'READ', 'ALLOW', 'ROLE', 'employee'); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 527fa1108..a9659329f 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -290,5 +290,6 @@ "isTaxDataChecked": "Datos comprobados", "comercialId": "Id comercial", "comercialName": "Comercial", - "Invalid NIF for VIES": "Invalid NIF for VIES" + "Invalid NIF for VIES": "Invalid NIF for VIES", + "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada" } From 5171e63188bbd3dbc5f1b3ab1bf5fa354d9572cd Mon Sep 17 00:00:00 2001 From: alexandre Date: Tue, 9 May 2023 14:20:20 +0200 Subject: [PATCH 05/30] refs #4797 minor fixes --- back/methods/notification/getList.js | 8 ++++---- back/methods/notification/specs/getList.spec.js | 7 ------- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/back/methods/notification/getList.js b/back/methods/notification/getList.js index 9f3367184..f8a163126 100644 --- a/back/methods/notification/getList.js +++ b/back/methods/notification/getList.js @@ -50,7 +50,7 @@ module.exports = Self => { } }, myOptions); - activeNotifications.forEach(subscription => { + for (subscription of activeNotifications) { notifications.push({ id: subscription.id, notificationFk: subscription.notificationFk, @@ -58,9 +58,9 @@ module.exports = Self => { description: subscription.notification().description, active: true }); - }); + } - availableNotifications.forEach(acl => { + for (acl of availableNotifications) { const activeNotif = notifications.find( notif => notif.notificationFk === acl.notificationFk ); @@ -73,7 +73,7 @@ module.exports = Self => { active: false, }); } - }); + } return notifications; }; diff --git a/back/methods/notification/specs/getList.spec.js b/back/methods/notification/specs/getList.spec.js index b220f2215..7c986eba2 100644 --- a/back/methods/notification/specs/getList.spec.js +++ b/back/methods/notification/specs/getList.spec.js @@ -28,11 +28,4 @@ describe('NotificationSubscription getList()', () => { expect(result.filter(notification => notification.active == false).length) .toEqual(availableNotifications.length - activeNotifications.length); }); - - it('should return empty from a non existent user', async() => { - const userId = 123456789; - const result = await models.NotificationSubscription.getList(userId); - - expect(result.length).toEqual(0); - }); }); From f9e7963e74c1c2701e89c8ba9e47663f97381b64 Mon Sep 17 00:00:00 2001 From: alexandre Date: Wed, 10 May 2023 14:10:00 +0200 Subject: [PATCH 06/30] refs #4797 minor fixes --- back/methods/notification/getList.js | 48 +++++++++---------------- back/models/notificationSubscription.js | 4 +-- 2 files changed, 18 insertions(+), 34 deletions(-) diff --git a/back/methods/notification/getList.js b/back/methods/notification/getList.js index f8a163126..cb0f1a4f9 100644 --- a/back/methods/notification/getList.js +++ b/back/methods/notification/getList.js @@ -21,7 +21,7 @@ module.exports = Self => { }); Self.getList = async(id, options) => { - const notifications = []; + const notifications = new Map(); const models = Self.app.models; const myOptions = {}; @@ -29,11 +29,6 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const activeNotifications = await models.NotificationSubscription.find({ - include: {relation: 'notification'}, - where: {userFk: id} - }, myOptions); - const roles = await models.RoleMapping.find({ fields: ['roleId'], where: {principalId: id} @@ -43,38 +38,29 @@ module.exports = Self => { include: {relation: 'notification'}, where: { roleFk: { - inq: roles.map(role => { - return role.roleId; - }), + inq: roles.map(role => role.roleId), }, } }, myOptions); - for (subscription of activeNotifications) { - notifications.push({ - id: subscription.id, - notificationFk: subscription.notificationFk, - name: subscription.notification().name, - description: subscription.notification().description, - active: true + for (acl of availableNotifications) { + notifications.set(acl.notificationFk, { + id: null, + notificationFk: acl.notificationFk, + name: acl.notification().name, + description: acl.notification().description, + active: false, }); } - for (acl of availableNotifications) { - const activeNotif = notifications.find( - notif => notif.notificationFk === acl.notificationFk - ); - if (!activeNotif) { - notifications.push({ - id: null, - notificationFk: acl.notificationFk, - name: acl.notification().name, - description: acl.notification().description, - active: false, - }); - } - } + const activeNotifications = await models.NotificationSubscription.find({ + include: {relation: 'notification'}, + where: {userFk: id} + }, myOptions); - return notifications; + for (subscription of activeNotifications) + notifications.get(subscription.notificationFk).active = true; + + return [...notifications.values()]; }; }; diff --git a/back/models/notificationSubscription.js b/back/models/notificationSubscription.js index a4d4a8bac..f750a0528 100644 --- a/back/models/notificationSubscription.js +++ b/back/models/notificationSubscription.js @@ -30,9 +30,7 @@ module.exports = Self => { const worker = await models.Worker.findById(workerId, {fields: ['id', 'bossFk']}); const notificationsAvailables = await models.NotificationSubscription.getList(workerId); - const hasAcl = notificationsAvailables.some(function(available) { - return available.notificationFk === notificationFk; - }); + const hasAcl = notificationsAvailables.some(available => available.notificationFk === notificationFk); if (!hasAcl || (userId != worker.id && userId != worker.bossFk)) throw new UserError('The notification subscription of this worker cant be modified'); From 9cb756544e69ec3561d153604145067d5e01d752 Mon Sep 17 00:00:00 2001 From: alexandre Date: Wed, 10 May 2023 14:13:38 +0200 Subject: [PATCH 07/30] refs #4797 added id to notification in activeNotifications --- back/methods/notification/getList.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/back/methods/notification/getList.js b/back/methods/notification/getList.js index cb0f1a4f9..fe5aa23a5 100644 --- a/back/methods/notification/getList.js +++ b/back/methods/notification/getList.js @@ -58,8 +58,13 @@ module.exports = Self => { where: {userFk: id} }, myOptions); - for (subscription of activeNotifications) - notifications.get(subscription.notificationFk).active = true; + for (subscription of activeNotifications) { + const notification = notifications.get(subscription.notificationFk); + if (notification) { + notification.active = true; + notification.id = subscription.id; + } + } return [...notifications.values()]; }; From 33ef9bdf61ea9f42a3ef5053ab81a5fe5a95be61 Mon Sep 17 00:00:00 2001 From: alexandre Date: Thu, 11 May 2023 07:18:58 +0200 Subject: [PATCH 08/30] refs #4797 refactor --- back/methods/notification/getList.js | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/back/methods/notification/getList.js b/back/methods/notification/getList.js index fe5aa23a5..35a0498c0 100644 --- a/back/methods/notification/getList.js +++ b/back/methods/notification/getList.js @@ -43,6 +43,11 @@ module.exports = Self => { } }, myOptions); + const activeNotifications = await models.NotificationSubscription.find({ + include: {relation: 'notification'}, + where: {userFk: id} + }, myOptions); + for (acl of availableNotifications) { notifications.set(acl.notificationFk, { id: null, @@ -53,17 +58,14 @@ module.exports = Self => { }); } - const activeNotifications = await models.NotificationSubscription.find({ - include: {relation: 'notification'}, - where: {userFk: id} - }, myOptions); - for (subscription of activeNotifications) { - const notification = notifications.get(subscription.notificationFk); - if (notification) { - notification.active = true; - notification.id = subscription.id; - } + notifications.set(subscription.notificationFk, { + id: subscription.id, + notificationFk: subscription.notificationFk, + name: subscription.notification().name, + description: subscription.notification().description, + active: true, + }); } return [...notifications.values()]; From 2c254cbc089ab55d2d0c2f3a91edc5704dd7487b Mon Sep 17 00:00:00 2001 From: alexandre Date: Mon, 15 May 2023 14:34:32 +0200 Subject: [PATCH 09/30] refs #4797 added fields --- back/methods/notification/getList.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/back/methods/notification/getList.js b/back/methods/notification/getList.js index 35a0498c0..780b8eb74 100644 --- a/back/methods/notification/getList.js +++ b/back/methods/notification/getList.js @@ -35,6 +35,7 @@ module.exports = Self => { }, myOptions); const availableNotifications = await models.NotificationAcl.find({ + fields: ['notificationFk', 'roleFk'], include: {relation: 'notification'}, where: { roleFk: { @@ -44,6 +45,7 @@ module.exports = Self => { }, myOptions); const activeNotifications = await models.NotificationSubscription.find({ + fields: ['id', 'notificationFk'], include: {relation: 'notification'}, where: {userFk: id} }, myOptions); From 8db7a5b16a812c4b74adfb77782bcbb8e42b5c7d Mon Sep 17 00:00:00 2001 From: alexandre Date: Thu, 18 May 2023 14:53:09 +0200 Subject: [PATCH 10/30] refs #4797 moved sql --- db/changes/232201/.gitkeep | 0 db/changes/{232001 => 232201}/00-notificationSubscription.sql | 0 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 db/changes/232201/.gitkeep rename db/changes/{232001 => 232201}/00-notificationSubscription.sql (100%) diff --git a/db/changes/232201/.gitkeep b/db/changes/232201/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/db/changes/232001/00-notificationSubscription.sql b/db/changes/232201/00-notificationSubscription.sql similarity index 100% rename from db/changes/232001/00-notificationSubscription.sql rename to db/changes/232201/00-notificationSubscription.sql From 4d3d38ebe301bdd62a7cc252ab7bbbb8cba7a3ce Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Oct 2023 15:22:04 +0200 Subject: [PATCH 11/30] refs #6014 feat: executeRoutine --- .../methods/application/executeRoutine.js | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 loopback/common/methods/application/executeRoutine.js diff --git a/loopback/common/methods/application/executeRoutine.js b/loopback/common/methods/application/executeRoutine.js new file mode 100644 index 000000000..a5557bc61 --- /dev/null +++ b/loopback/common/methods/application/executeRoutine.js @@ -0,0 +1,61 @@ +module.exports = Self => { + Self.remoteMethodCtx('executeRoutine', { + description: 'Return the routes by worker', + accessType: '*', + accepts: [ + { + arg: 'routine', + type: 'string', + description: 'The routine sql', + required: true, + http: {source: 'path'} + }, + { + arg: 'params', + type: ['any'], + description: 'The array of params', + required: true, + } + ], + returns: { + type: 'any', + root: true + }, + http: { + path: `/:routine/execute-routine`, + verb: 'POST' + } + }); + + Self.executeRoutine = async(ctx, routine, params, options) => { + const userId = ctx.req.accessToken.userId; + + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const user = await Self.app.models.VnUser.findById(userId, { + fields: ['id', 'roleFk'], + include: { + relation: 'role', + scope: { + fields: ['id', 'name'] + } + } + }); + + const inherits = await Self.app.models.RoleRole.find({ + where: { + + } + }); + console.log(user.role.name); + + const checkACL = await models.ACL.checkAccessAcl(ctx, 'Application', routine, '*'); + if (!checkACL) throw error; + + const requestParams = [routine]; + requestParams.concat(params); + return Self.app.models.Route.rawSql(`CALL ?(...)`, requestParams, myOptions); + }; +}; From 483526c9702fe03ddd2fcc18586cb6b62cc36102 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 23 Oct 2023 15:03:05 +0200 Subject: [PATCH 12/30] refs #6015 feat(executeRoutine): check db restrictions. test: add executeRoutine tests --- db/changes/234201/00-ACL_executeRoutine.sql | 3 + .../methods/application/executeRoutine.js | 67 +++++++-- .../application/spec/executeRoutine.spec.js | 138 ++++++++++++++++++ loopback/common/models/application.js | 1 + loopback/common/models/procs-priv.json | 44 ++++++ loopback/server/model-config.json | 10 +- 6 files changed, 248 insertions(+), 15 deletions(-) create mode 100644 db/changes/234201/00-ACL_executeRoutine.sql create mode 100644 loopback/common/methods/application/spec/executeRoutine.spec.js create mode 100644 loopback/common/models/procs-priv.json diff --git a/db/changes/234201/00-ACL_executeRoutine.sql b/db/changes/234201/00-ACL_executeRoutine.sql new file mode 100644 index 000000000..dd112171a --- /dev/null +++ b/db/changes/234201/00-ACL_executeRoutine.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('Application', 'executeRoutine', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/loopback/common/methods/application/executeRoutine.js b/loopback/common/methods/application/executeRoutine.js index a5557bc61..eed34b344 100644 --- a/loopback/common/methods/application/executeRoutine.js +++ b/loopback/common/methods/application/executeRoutine.js @@ -1,3 +1,5 @@ +const UserError = require('vn-loopback/util/user-error'); + module.exports = Self => { Self.remoteMethodCtx('executeRoutine', { description: 'Return the routes by worker', @@ -6,15 +8,24 @@ module.exports = Self => { { arg: 'routine', type: 'string', - description: 'The routine sql', + description: 'The routine name', required: true, http: {source: 'path'} }, { arg: 'params', type: ['any'], - description: 'The array of params', - required: true, + description: 'The params array', + }, + { + arg: 'schema', + type: 'string', + description: 'The routine schema', + }, + { + arg: 'type', + type: 'string', + description: 'The routine type', } ], returns: { @@ -27,14 +38,23 @@ module.exports = Self => { } }); - Self.executeRoutine = async(ctx, routine, params, options) => { + Self.executeRoutine = async(ctx, routine, params, schema, type, options) => { const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + const isFunction = type == 'function'; + params = params ?? []; + schema = schema ?? 'vn'; + type = type ?? 'procedure'; + let caller = 'CALL'; - const myOptions = {}; + if (isFunction) + caller = 'SELECT'; + + const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); - const user = await Self.app.models.VnUser.findById(userId, { + const user = await models.VnUser.findById(userId, { fields: ['id', 'roleFk'], include: { relation: 'role', @@ -44,18 +64,37 @@ module.exports = Self => { } }); - const inherits = await Self.app.models.RoleRole.find({ + const inherits = await models.RoleRole.find({ + include: { + relation: 'inherits', + scope: { + fields: ['id', 'name'] + } + }, where: { - + role: user.role().id } }); - console.log(user.role.name); - const checkACL = await models.ACL.checkAccessAcl(ctx, 'Application', routine, '*'); - if (!checkACL) throw error; + const roles = inherits.map(inherit => inherit.inherits().name); - const requestParams = [routine]; - requestParams.concat(params); - return Self.app.models.Route.rawSql(`CALL ?(...)`, requestParams, myOptions); + const canExecute = await models.ProcsPriv.findOne({ + where: { + schema, + type: type.toUpperCase(), + name: routine, + host: process.env.NODE_ENV ? '' : '%', + role: {inq: roles} + } + }); + + if (!canExecute) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); + + let argString = params.map(() => '?').join(','); + + const query = `${caller} ${schema}.${routine}(${argString})`; + + const [response] = await models.ProcsPriv.rawSql(query, params, myOptions); + return isFunction ? Object.values(response)[0] : response; }; }; diff --git a/loopback/common/methods/application/spec/executeRoutine.spec.js b/loopback/common/methods/application/spec/executeRoutine.spec.js new file mode 100644 index 000000000..150c5d416 --- /dev/null +++ b/loopback/common/methods/application/spec/executeRoutine.spec.js @@ -0,0 +1,138 @@ +const models = require('vn-loopback/server/server').models; + +describe('Application executeRoutine()', () => { + const userWithoutPrivileges = 1; + const userWithPrivileges = 9; + const userWithInheritedPrivileges = 120; + let tx; + + function getCtx(userId) { + return { + req: { + accessToken: {userId}, + headers: {origin: 'http://localhost'} + } + }; + } + + beforeEach(async() => { + tx = await models.Application.beginTransaction({}); + const options = {transaction: tx}; + + await models.Application.rawSql(` + CREATE OR REPLACE PROCEDURE vn.myProcedure(vMyParam INT) + BEGIN + SELECT vMyParam myParam, t.* + FROM ticket t + LIMIT 2; + END + `, null, options); + + await models.Application.rawSql(` + CREATE OR REPLACE FUNCTION bs.myFunction(vMyParam INT) RETURNS int(11) + BEGIN + RETURN vMyParam; + END + `, null, options); + + await models.Application.rawSql(` + GRANT EXECUTE ON PROCEDURE vn.myProcedure TO developer; + GRANT EXECUTE ON FUNCTION bs.myFunction TO developer; + `, null, options); + }); + + it('should throw error when execute procedure and not have privileges', async() => { + const ctx = getCtx(userWithoutPrivileges); + + let error; + try { + const options = {transaction: tx}; + + await models.Application.executeRoutine( + ctx, + 'myProcedure', + [1], + null, + null, + options + ); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual(`You don't have enough privileges`); + }); + + it('should execute procedure and get data', async() => { + const ctx = getCtx(userWithPrivileges); + try { + const options = {transaction: tx}; + + const response = await models.Application.executeRoutine( + ctx, + 'myProcedure', + [1], + null, + null, + options + ); + + expect(response.length).toEqual(2); + expect(response[0].myParam).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should execute function and get data', async() => { + const ctx = getCtx(userWithPrivileges); + try { + const options = {transaction: tx}; + + const response = await models.Application.executeRoutine( + ctx, + 'myFunction', + [1], + 'bs', + 'function', + options + ); + + expect(response).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should execute function and get data with user with inherited privileges', async() => { + const ctx = getCtx(userWithInheritedPrivileges); + try { + const options = {transaction: tx}; + + const response = await models.Application.executeRoutine( + ctx, + 'myFunction', + [1], + 'bs', + 'function', + options + ); + + expect(response).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/loopback/common/models/application.js b/loopback/common/models/application.js index 5e767fdc1..b9e639b1b 100644 --- a/loopback/common/models/application.js +++ b/loopback/common/models/application.js @@ -2,4 +2,5 @@ module.exports = function(Self) { require('../methods/application/status')(Self); require('../methods/application/post')(Self); + require('../methods/application/executeRoutine')(Self); }; diff --git a/loopback/common/models/procs-priv.json b/loopback/common/models/procs-priv.json new file mode 100644 index 000000000..25221d586 --- /dev/null +++ b/loopback/common/models/procs-priv.json @@ -0,0 +1,44 @@ +{ + "name": "ProcsPriv", + "base": "VnModel", + "options": { + "mysql": { + "table": "mysql.procs_priv" + } + }, + "properties": { + "name": { + "id": 1, + "type": "string", + "mysql": { + "columnName": "Routine_name" + } + }, + "schema": { + "id": 3, + "type": "string", + "mysql": { + "columnName": "Db" + } + }, + "role": { + "type": "string", + "mysql": { + "columnName": "user" + } + }, + "type": { + "id": 2, + "type": "string", + "mysql": { + "columnName": "Routine_type" + } + }, + "host": { + "type": "string", + "mysql": { + "columnName": "Host" + } + } + } +} diff --git a/loopback/server/model-config.json b/loopback/server/model-config.json index 52b539f60..33ef3797d 100644 --- a/loopback/server/model-config.json +++ b/loopback/server/model-config.json @@ -49,5 +49,13 @@ }, "Container": { "dataSource": "vn" + }, + "ProcsPriv": { + "dataSource": "vn", + "options": { + "mysql": { + "table": "mysql.procs_priv" + } + } } -} \ No newline at end of file +} From 175e73e5659169d8ea79af2f76b5443f4b08800c Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 2 Nov 2023 14:05:14 +0100 Subject: [PATCH 13/30] fix(clientCredit): refs #6150 se arreglan los inserts en clientCredit --- db/changes/234601/00-clientAfterUpdate.sql | 77 +++++++++++++++++++ modules/client/back/models/client-config.json | 3 + modules/client/back/models/client.js | 20 ++--- .../client/back/models/specs/client.spec.js | 4 +- modules/ticket/front/summary/index.html | 2 +- modules/worker/back/methods/worker/new.js | 13 +++- 6 files changed, 102 insertions(+), 17 deletions(-) create mode 100644 db/changes/234601/00-clientAfterUpdate.sql diff --git a/db/changes/234601/00-clientAfterUpdate.sql b/db/changes/234601/00-clientAfterUpdate.sql new file mode 100644 index 000000000..4ae594deb --- /dev/null +++ b/db/changes/234601/00-clientAfterUpdate.sql @@ -0,0 +1,77 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_beforeUpdate` + BEFORE UPDATE ON `client` + FOR EACH ROW +BEGIN + DECLARE vText VARCHAR(255) DEFAULT NULL; + DECLARE vPayMethodFk INT; + + SET NEW.editorFk = account.myUser_getId(); + + IF NOT(NEW.credit <=> OLD.credit) THEN + INSERT INTO clientCredit + SET clientFk = NEW.id, + amount = NEW.credit, + workerFk = NEW.editorFk; + END IF; + -- Comprueba que el formato de los teléfonos es válido + + IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN + CALL pbx.phone_isValid(NEW.phone); + END IF; + + IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN + CALL pbx.phone_isValid(NEW.mobile); + END IF; + + SELECT id INTO vPayMethodFk + FROM vn.payMethod + WHERE code = 'bankDraft'; + + IF NEW.payMethodFk = vPayMethodFk AND NEW.dueDay = 0 THEN + SET NEW.dueDay = 5; + END IF; + + -- Avisar al comercial si ha llegado la documentación sepa/core + + IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN + SET vText = 'Sepa de VNL'; + END IF; + + IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN + SET vText = 'Core de VNL'; + END IF; + + IF vText IS NOT NULL + THEN + INSERT INTO mail(receiver, replyTo, `subject`, body) + SELECT + CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), + 'administracion@verdnatura.es', + CONCAT('Cliente ', NEW.id), + CONCAT('Recibida la documentación: ', vText) + FROM worker w + LEFT JOIN account.user u ON w.id = u.id AND u.active + LEFT JOIN account.account ac ON ac.id = u.id + WHERE w.id = NEW.salesPersonFk; + END IF; + + IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN + IF (SELECT COUNT(clientFk) + FROM clientProtected + WHERE clientFk = NEW.id + ) > 0 THEN + CALL util.throw("HAS_CLIENT_PROTECTED"); + END IF; + END IF; + + IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN + SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); + END IF; + + IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN + SET NEW.isTaxDataChecked = 0; + END IF; + +END$$ +DELIMITER ; diff --git a/modules/client/back/models/client-config.json b/modules/client/back/models/client-config.json index 90d47333d..6c5eae7d7 100644 --- a/modules/client/back/models/client-config.json +++ b/modules/client/back/models/client-config.json @@ -17,6 +17,9 @@ }, "maxCreditRows": { "type": "number" + }, + "defaultCredit": { + "type": "number" } } } \ No newline at end of file diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index e16e884cc..72b702779 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -450,14 +450,14 @@ module.exports = Self => { if (lastCredit && lastCredit.amount == 0) { const zeroCreditEditor = - await models.ACL.checkAccessAcl(accessToken, 'Client', 'zeroCreditEditor', 'WRITE'); + await models.ACL.checkAccessAcl(accessToken, 'Client', 'zeroCreditEditor', 'WRITE'); const lastCreditIsNotEditable = - await models.ACL.checkAccessAcl( - {req: {accessToken: {userId: lastCredit.workerFk}}}, - 'Client', - 'zeroCreditEditor', - 'WRITE' - ); + await models.ACL.checkAccessAcl( + {req: {accessToken: {userId: lastCredit.workerFk}}}, + 'Client', + 'zeroCreditEditor', + 'WRITE' + ); if (lastCreditIsNotEditable && !zeroCreditEditor) throw new UserError(`You can't change the credit set to zero from a financialBoss`); @@ -483,12 +483,6 @@ module.exports = Self => { if (userRequiredRoles <= 0) throw new UserError(`You don't have enough privileges to set this credit amount`); } - - await models.ClientCredit.create({ - amount: changes.credit, - clientFk: finalState.id, - workerFk: userId - }, ctx.options); }; Self.changeCreditManagement = async function changeCreditManagement(ctx, finalState, changes) { diff --git a/modules/client/back/models/specs/client.spec.js b/modules/client/back/models/specs/client.spec.js index 201d14bb4..bf134fbf9 100644 --- a/modules/client/back/models/specs/client.spec.js +++ b/modules/client/back/models/specs/client.spec.js @@ -62,13 +62,13 @@ describe('Client Model', () => { const options = {transaction: tx}; const ctx = {options}; - // Set credit to zero by a financialBoss const financialBoss = await models.VnUser.findOne({ where: {name: 'financialBoss'} }, options); ctx.options.accessToken = {userId: financialBoss.id}; - await models.Client.changeCredit(ctx, instance, {credit: 0}); + const testClient = await models.Client.findById(instance.id, options); + await testClient.updateAttributes({credit: 0}, ctx.options); const salesAssistant = await models.VnUser.findOne({ where: {name: 'salesAssistant'} diff --git a/modules/ticket/front/summary/index.html b/modules/ticket/front/summary/index.html index 3c60352a7..4cf7ed11d 100644 --- a/modules/ticket/front/summary/index.html +++ b/modules/ticket/front/summary/index.html @@ -212,7 +212,7 @@ {{::sale.quantity}}
- {{::sale.item.name}} + {{::sale.concept}}

{{::sale.item.subName}}

diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 5316daf01..c9cebda7a 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -119,7 +119,8 @@ module.exports = Self => { Self.new = async(ctx, options) => { const models = Self.app.models; - const myOptions = {userId: ctx.req.accessToken.userId}; + const {userId} = ctx.req.accessToken; + const myOptions = {userId}; const args = ctx.args; let tx; @@ -188,6 +189,16 @@ module.exports = Self => { myOptions ); + const {defaultCredit} = await models.ClientConfig.findOne(myOptions); + + await models.ClientCredit.create( + { + clientFk: user.id, + amount: defaultCredit, + workerFk: userId + }, myOptions + ); + const address = await models.Address.create( { clientFk: user.id, From 8c5e40c27fb8477027294feefb65cb6076e02a80 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 3 Nov 2023 15:16:03 +0100 Subject: [PATCH 14/30] refs #4797 fix: correct sql folder --- db/changes/{232201 => 234601}/00-notificationSubscription.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{232201 => 234601}/00-notificationSubscription.sql (100%) diff --git a/db/changes/232201/00-notificationSubscription.sql b/db/changes/234601/00-notificationSubscription.sql similarity index 100% rename from db/changes/232201/00-notificationSubscription.sql rename to db/changes/234601/00-notificationSubscription.sql From 7ca3ea156cc1937564056c350da526fc121f7d4d Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 6 Nov 2023 09:16:10 +0100 Subject: [PATCH 15/30] feat(claimViewer): refs #5881 nuevo rol claimViewer --- db/changes/234601/00-claimViewweAcl.sql | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 db/changes/234601/00-claimViewweAcl.sql diff --git a/db/changes/234601/00-claimViewweAcl.sql b/db/changes/234601/00-claimViewweAcl.sql new file mode 100644 index 000000000..e913c0ed9 --- /dev/null +++ b/db/changes/234601/00-claimViewweAcl.sql @@ -0,0 +1,31 @@ +INSERT INTO `account`.`role` (`name`, `description`, `hasLogin`) + VALUES ('claimViewer','Trabajadores que consulta las reclamaciones ',1); + +INSERT INTO `account`.`roleInherit` (`role`,`inheritsFrom`) + SELECT `r`.`id`, `r2`.`id` + FROM `account`.`role` `r` + JOIN `account`.`role` `r2` ON `r2`.`name` = 'claimViewer' + WHERE `r`.`name` IN ( + 'salesPerson', + 'buyer', + 'deliveryBoss', + 'handmadeBoss' + ); + +DELETE FROM `salix`.`ACL` + WHERE `model`= 'claim' + AND `property` IN ( + 'filter', + 'find', + 'findById', + 'getSummary' + ); + +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) + VALUES ('Claim','filter','READ','ALLOW','ROLE','claimViewer'); +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) + VALUES ('Claim','find','READ','ALLOW','ROLE','claimViewer'); +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) + VALUES ('Claim','findById','READ','ALLOW','ROLE','claimViewer'); +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) + VALUES ('Claim','getSummary','READ','ALLOW','ROLE','claimViewer'); \ No newline at end of file From a75565f2ce3e549355ee9601958acec07f9697a1 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 6 Nov 2023 14:23:36 +0100 Subject: [PATCH 16/30] feat(client.create): refs #6150 clientCredit update fix --- db/changes/234601/00-clientAfterUpdate.sql | 48 +++++++++++++++++++++- db/dump/fixtures.sql | 3 +- modules/worker/back/methods/worker/new.js | 10 ----- 3 files changed, 49 insertions(+), 12 deletions(-) diff --git a/db/changes/234601/00-clientAfterUpdate.sql b/db/changes/234601/00-clientAfterUpdate.sql index 4ae594deb..49854ebcd 100644 --- a/db/changes/234601/00-clientAfterUpdate.sql +++ b/db/changes/234601/00-clientAfterUpdate.sql @@ -1,3 +1,7 @@ +ALTER TABLE `vn`.`client` MODIFY COLUMN `credit` decimal(10,2) unsigned DEFAULT 0.00 NOT NULL; + +DELETE FROM `salix`.`ACL` WHERE `model` = 'Client' AND `property` = 'create'; + DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_beforeUpdate` BEFORE UPDATE ON `client` @@ -72,6 +76,48 @@ BEGIN IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN SET NEW.isTaxDataChecked = 0; END IF; - END$$ DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticket_afterInsert` + AFTER INSERT ON `ticket` + FOR EACH ROW +BEGIN + DECLARE vClientType VARCHAR(255); + DECLARE vStateCode VARCHAR(255); + DECLARE vTransferorFirstShipped DATE; + + IF NEW.credit NOT NULL AND NEW.credit <> 0 THEN + INSERT INTO clientCredit + SET clientFk = NEW.id, + workerFk = NEW.editorFk, + amount = NEW.credit; + END IF; + + -- Borrar cuando se cambie el insert ticket en la APP móvil + + SELECT typeFk INTO vClientType + FROM vn.`client` WHERE id = NEW.clientFk; + + IF vClientType = 'loses' THEN + SET vStateCode = 'DELIVERED'; + ELSE + SET vStateCode = 'FREE'; + END IF; + + CALL ticket_setState(NEW.id, vStateCode); + + IF YEAR(NEW.shipped) > 2000 THEN + SELECT cnb.firstShipped INTO vTransferorFirstShipped + FROM bs.clientNewBorn cnb + JOIN `client` c ON c.transferorFk = cnb.clientFk + WHERE c.id = NEW.clientFk; + + INSERT INTO bs.clientNewBorn(clientFk, firstShipped, lastShipped) + VALUES(NEW.clientFk, IFNULL(vTransferorFirstShipped, util.VN_CURDATE()), util.VN_CURDATE()) + ON DUPLICATE KEY UPDATE lastShipped = util.VN_CURDATE(); + END IF; +END$$ +DELIMITER ; + diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index faf58fd78..1dd8a7bd8 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -491,7 +491,8 @@ INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) VALUES (1, 9999999, 20), (2, 10000, 21), - (3, 600, 13); + (3, 600, 13), + (4, 300, 37); INSERT INTO `vn`.`clientObservation`(`id`, `clientFk`, `workerFk`, `text`, `created`) VALUES diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index c9cebda7a..6610e6919 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -189,16 +189,6 @@ module.exports = Self => { myOptions ); - const {defaultCredit} = await models.ClientConfig.findOne(myOptions); - - await models.ClientCredit.create( - { - clientFk: user.id, - amount: defaultCredit, - workerFk: userId - }, myOptions - ); - const address = await models.Address.create( { clientFk: user.id, From b442c9f5ed2a5b09389c3be63af8bd8261494e0a Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 6 Nov 2023 14:54:56 +0100 Subject: [PATCH 17/30] fix: refs #6150 ticket to client trigger --- db/changes/234601/00-clientAfterUpdate.sql | 38 +++++++--------------- 1 file changed, 12 insertions(+), 26 deletions(-) diff --git a/db/changes/234601/00-clientAfterUpdate.sql b/db/changes/234601/00-clientAfterUpdate.sql index 49854ebcd..90ff5d52a 100644 --- a/db/changes/234601/00-clientAfterUpdate.sql +++ b/db/changes/234601/00-clientAfterUpdate.sql @@ -80,44 +80,30 @@ END$$ DELIMITER ; DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticket_afterInsert` - AFTER INSERT ON `ticket` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_beforeInsert` + BEFORE INSERT ON `client` FOR EACH ROW BEGIN - DECLARE vClientType VARCHAR(255); - DECLARE vStateCode VARCHAR(255); - DECLARE vTransferorFirstShipped DATE; - - IF NEW.credit NOT NULL AND NEW.credit <> 0 THEN + IF NEW.credit NOT NULL AND NEW.credit THEN INSERT INTO clientCredit SET clientFk = NEW.id, workerFk = NEW.editorFk, amount = NEW.credit; END IF; - -- Borrar cuando se cambie el insert ticket en la APP móvil + SET NEW.editorFk = account.myUser_getId(); - SELECT typeFk INTO vClientType - FROM vn.`client` WHERE id = NEW.clientFk; - - IF vClientType = 'loses' THEN - SET vStateCode = 'DELIVERED'; - ELSE - SET vStateCode = 'FREE'; + IF (NEW.phone <> '') THEN + CALL pbx.phone_isValid(NEW.phone); END IF; - CALL ticket_setState(NEW.id, vStateCode); - - IF YEAR(NEW.shipped) > 2000 THEN - SELECT cnb.firstShipped INTO vTransferorFirstShipped - FROM bs.clientNewBorn cnb - JOIN `client` c ON c.transferorFk = cnb.clientFk - WHERE c.id = NEW.clientFk; - - INSERT INTO bs.clientNewBorn(clientFk, firstShipped, lastShipped) - VALUES(NEW.clientFk, IFNULL(vTransferorFirstShipped, util.VN_CURDATE()), util.VN_CURDATE()) - ON DUPLICATE KEY UPDATE lastShipped = util.VN_CURDATE(); + IF (NEW.mobile <> '') THEN + CALL pbx.phone_isValid(NEW.mobile); END IF; + + SET NEW.accountingAccount = 4300000000 + NEW.id; + + SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END$$ DELIMITER ; From 1c6618d49432d07ff59ec49b7676bd7d78e302d9 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 6 Nov 2023 14:56:48 +0100 Subject: [PATCH 18/30] fix(new): refs #6150 revert chabges in worker new method --- modules/worker/back/methods/worker/new.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 6610e6919..5316daf01 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -119,8 +119,7 @@ module.exports = Self => { Self.new = async(ctx, options) => { const models = Self.app.models; - const {userId} = ctx.req.accessToken; - const myOptions = {userId}; + const myOptions = {userId: ctx.req.accessToken.userId}; const args = ctx.args; let tx; From 0818efaa9936c8eb7244c5df83887852cb97cd2b Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 6 Nov 2023 14:58:39 +0100 Subject: [PATCH 19/30] fix(fixtures): refs #6150 clientCredit --- db/dump/fixtures.sql | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index d0afa8d81..d70279e7d 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -491,8 +491,7 @@ INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) VALUES (1, 9999999, 20), (2, 10000, 21), - (3, 600, 13), - (4, 300, 37); + (3, 600, 13); INSERT INTO `vn`.`clientObservation`(`id`, `clientFk`, `workerFk`, `text`, `created`) VALUES From d30c4e446379ae2adbb2112cb84ae205ad252b3a Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 7 Nov 2023 16:13:21 +0100 Subject: [PATCH 20/30] refs #5652 feat:addressShortage --- db/changes/234601/00-addressShortage.sql | 97 +++++++++++++++++++ modules/client/back/model-config.json | 3 + .../client/back/models/addressShortage.json | 22 +++++ 3 files changed, 122 insertions(+) create mode 100644 db/changes/234601/00-addressShortage.sql create mode 100644 modules/client/back/models/addressShortage.json diff --git a/db/changes/234601/00-addressShortage.sql b/db/changes/234601/00-addressShortage.sql new file mode 100644 index 000000000..dd8ef8e4b --- /dev/null +++ b/db/changes/234601/00-addressShortage.sql @@ -0,0 +1,97 @@ + +-- Place your SQL code here + +ALTER TABLE `vn`.`productionConfig` ADD shortageAddressFk int(11) COMMENT 'Address por defecto para añadir un item de alta'; +ALTER TABLE `vn`.`productionConfig` ADD CONSTRAINT productionConfig_FK FOREIGN KEY (shortageAddressFk) REFERENCES vn.address(id) ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE `vn`.`sale` MODIFY COLUMN originalQuantity double(9,1) DEFAULT NULL NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity'; + +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) VALUES( 'AddressShortage', '*', 'READ', 'ALLOW', 'ROLE', 'production'); + +-- vn.addressShortage definition + +CREATE TABLE `vn`.`addressShortage` ( + `addressFk` int(11) NOT NULL, + PRIMARY KEY (`addressFk`), + CONSTRAINT `addressShortage_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + + +DELIMITER $$ + +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDiscard`( + vItemFk INT, + vWarehouseFk INT, + vQuantity INT, + vAddressFk INT) +BEGIN +/** + * Procedimiento para dar dar de baja/alta un item, si vAddressFk es NULL se entiende que se da de alta y se toma el addressFk de la configuración + * + * @param vItemFk Identificador del ítem + * @param vWarehouseFk id del warehouse + * @param vQuantity a dar de alta/baja + * @param vAddressFk id address + */ + DECLARE vTicketFk INT; + DECLARE vClientFk INT; + DECLARE vCompanyVnlFk INT; + DECLARE vCalc INT; + DECLARE vAddressShortage INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + SELECT DEFAULT(companyFk) INTO vCompanyVnlFk + FROM vn.ticket LIMIT 1; + + IF vAddressFk IS NULL THEN + SELECT pc.shortageAddressFk FROM productionConfig pc INTO vAddressShortage; + ELSE + SET vAddressShortage = vAddressFk; + END IF; + + SELECT a.clientFk INTO vClientFk + FROM address a + WHERE a.id = vAddressFk; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN ticketState ts ON ts.ticketFk = t.id + WHERE t.warehouseFk = vWarehouseFk + AND a.id = vAddressShortage + AND DATE(t.shipped) = util.VN_CURDATE() + AND ts.code = 'DELIVERED' + LIMIT 1; + + CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); + + IF vTicketFk IS NULL THEN + CALL ticket_add( + vClientFk, + util.VN_CURDATE(), + vWarehouseFk, + vCompanyVnlFk, + vAddressFk, + NULL, + NULL, + util.VN_CURDATE(), + account.myUser_getId(), + FALSE, + vTicketFk); + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity) + SELECT vTicketFk, + vItemFk, + CONCAT(longName,' ', worker_getCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)), + vQuantity + FROM item + WHERE id = vItemFk; + + UPDATE cache.visible + SET visible = visible - vQuantity + WHERE calc_id = vCalc + AND item_id = vItemFk; +END$$ +DELIMITER ; diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index 296b5e6a7..0cc5df9a2 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -5,6 +5,9 @@ "AddressObservation": { "dataSource": "vn" }, + "AddressShortage": { + "dataSource": "vn" + }, "BankEntity": { "dataSource": "vn" }, diff --git a/modules/client/back/models/addressShortage.json b/modules/client/back/models/addressShortage.json new file mode 100644 index 000000000..1ae8d986c --- /dev/null +++ b/modules/client/back/models/addressShortage.json @@ -0,0 +1,22 @@ +{ + "name": "AddressShortage", + "base": "VnModel", + "options": { + "mysql": { + "table": "addressShortage" + } + }, + "properties": { + "addressFk": { + "type": "number", + "id": true + } + }, + "relations": { + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + } + } +} \ No newline at end of file From 5751065e6a0f14d27314ec1cad944b52ddc57d83 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 8 Nov 2023 11:50:04 +0100 Subject: [PATCH 21/30] refs #5652 feat:addressShortage --- db/changes/234601/00-addressShortage.sql | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/db/changes/234601/00-addressShortage.sql b/db/changes/234601/00-addressShortage.sql index dd8ef8e4b..57c07d480 100644 --- a/db/changes/234601/00-addressShortage.sql +++ b/db/changes/234601/00-addressShortage.sql @@ -1,8 +1,8 @@ -- Place your SQL code here -ALTER TABLE `vn`.`productionConfig` ADD shortageAddressFk int(11) COMMENT 'Address por defecto para añadir un item de alta'; -ALTER TABLE `vn`.`productionConfig` ADD CONSTRAINT productionConfig_FK FOREIGN KEY (shortageAddressFk) REFERENCES vn.address(id) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE `vn`.`productionConfig` ADD shortageAddressFk int(11) COMMENT 'Consignatario por defecto para añadir un item de alta'; +ALTER TABLE `vn`.`productionConfig` ADD CONSTRAINT productionConfig_FK FOREIGN KEY (shortageAddressFk) REFERENCES vn.address(id) ON DELETE RESTRICT ON UPDATE CASCADE; ALTER TABLE `vn`.`sale` MODIFY COLUMN originalQuantity double(9,1) DEFAULT NULL NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity'; @@ -35,17 +35,18 @@ BEGIN */ DECLARE vTicketFk INT; DECLARE vClientFk INT; - DECLARE vCompanyVnlFk INT; + DECLARE vDefaultCompanyFk INT; DECLARE vCalc INT; DECLARE vAddressShortage INT; SELECT barcodeToItem(vItemFk) INTO vItemFk; - SELECT DEFAULT(companyFk) INTO vCompanyVnlFk + SELECT DEFAULT(companyFk) INTO vDefaultCompanyFk FROM vn.ticket LIMIT 1; IF vAddressFk IS NULL THEN - SELECT pc.shortageAddressFk FROM productionConfig pc INTO vAddressShortage; + SELECT pc.shortageAddressFk INTO vAddressShortage + FROM productionConfig pc ; ELSE SET vAddressShortage = vAddressFk; END IF; @@ -71,7 +72,7 @@ BEGIN vClientFk, util.VN_CURDATE(), vWarehouseFk, - vCompanyVnlFk, + vDefaultCompanyFk, vAddressFk, NULL, NULL, From 0de5bc510935f985078ca364d809f0ac75456f85 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 8 Nov 2023 14:56:47 +0100 Subject: [PATCH 22/30] refs #4797 refactor: getList & notificationSubscription method --- .vscode/settings.json | 5 ++- back/methods/notification/getList.js | 51 ++++++++----------------- back/models/notificationSubscription.js | 40 ++++++++++++++++++- 3 files changed, 57 insertions(+), 39 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 05d23f3bb..9ed1c8fc2 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -10,5 +10,8 @@ "eslint.format.enable": true, "[javascript]": { "editor.defaultFormatter": "dbaeumer.vscode-eslint" - } + }, + "cSpell.words": [ + "salix" + ] } diff --git a/back/methods/notification/getList.js b/back/methods/notification/getList.js index 780b8eb74..3881f0f63 100644 --- a/back/methods/notification/getList.js +++ b/back/methods/notification/getList.js @@ -21,55 +21,34 @@ module.exports = Self => { }); Self.getList = async(id, options) => { - const notifications = new Map(); - const models = Self.app.models; + const activeNotificationsMap = new Map(); const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - const roles = await models.RoleMapping.find({ - fields: ['roleId'], - where: {principalId: id} - }, myOptions); - - const availableNotifications = await models.NotificationAcl.find({ - fields: ['notificationFk', 'roleFk'], - include: {relation: 'notification'}, - where: { - roleFk: { - inq: roles.map(role => role.roleId), - }, - } - }, myOptions); - - const activeNotifications = await models.NotificationSubscription.find({ + const availableNotificationsMap = await Self.getAvailable(id, myOptions); + const activeNotifications = await Self.app.models.NotificationSubscription.find({ fields: ['id', 'notificationFk'], include: {relation: 'notification'}, where: {userFk: id} }, myOptions); - for (acl of availableNotifications) { - notifications.set(acl.notificationFk, { - id: null, - notificationFk: acl.notificationFk, - name: acl.notification().name, - description: acl.notification().description, - active: false, + for (active of activeNotifications) { + activeNotificationsMap.set(active.notificationFk, { + id: active.id, + notificationFk: active.notificationFk, + name: active.notification().name, + description: active.notification().description, + active: true }); + availableNotificationsMap.delete(active.notificationFk); } - for (subscription of activeNotifications) { - notifications.set(subscription.notificationFk, { - id: subscription.id, - notificationFk: subscription.notificationFk, - name: subscription.notification().name, - description: subscription.notification().description, - active: true, - }); - } - - return [...notifications.values()]; + return { + active: [...activeNotificationsMap.entries()], + available: [...availableNotificationsMap.entries()] + }; }; }; diff --git a/back/models/notificationSubscription.js b/back/models/notificationSubscription.js index f750a0528..8efb83e7d 100644 --- a/back/models/notificationSubscription.js +++ b/back/models/notificationSubscription.js @@ -29,10 +29,46 @@ module.exports = Self => { } const worker = await models.Worker.findById(workerId, {fields: ['id', 'bossFk']}); - const notificationsAvailables = await models.NotificationSubscription.getList(workerId); - const hasAcl = notificationsAvailables.some(available => available.notificationFk === notificationFk); + const available = await Self.getAvailable(workerId); + const hasAcl = available.has(notificationFk); if (!hasAcl || (userId != worker.id && userId != worker.bossFk)) throw new UserError('The notification subscription of this worker cant be modified'); } + + Self.getAvailable = async function(userId, options) { + const availableNotificationsMap = new Map(); + const models = Self.app.models; + + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const roles = await models.RoleMapping.find({ + fields: ['roleId'], + where: {principalId: userId} + }, myOptions); + + const availableNotifications = await models.NotificationAcl.find({ + fields: ['notificationFk', 'roleFk'], + include: {relation: 'notification'}, + where: { + roleFk: { + inq: roles.map(role => role.roleId), + }, + } + }, myOptions); + + for (available of availableNotifications) { + availableNotificationsMap.set(available.notificationFk, { + id: null, + notificationFk: available.notificationFk, + name: available.notification().name, + description: available.notification().description, + active: false + }); + } + return availableNotificationsMap; + }; }; From 204323ac69f448988f93d81ba22206d1500b1027 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 8 Nov 2023 14:57:07 +0100 Subject: [PATCH 23/30] test(notification_getList): fix --- .../notification/specs/getList.spec.js | 30 ++++--------------- db/dump/fixtures.sql | 2 ++ 2 files changed, 8 insertions(+), 24 deletions(-) diff --git a/back/methods/notification/specs/getList.spec.js b/back/methods/notification/specs/getList.spec.js index 7c986eba2..52ac497a5 100644 --- a/back/methods/notification/specs/getList.spec.js +++ b/back/methods/notification/specs/getList.spec.js @@ -2,30 +2,12 @@ const models = require('vn-loopback/server/server').models; describe('NotificationSubscription getList()', () => { it('should return a list of available and active notifications of a user', async() => { - const userId = 1109; - const activeNotifications = await models.NotificationSubscription.find({ - where: {userFk: userId} - }); - const roles = await models.RoleMapping.find({ - fields: ['roleId'], - where: {principalId: userId} - }); - const availableNotifications = await models.NotificationAcl.find({ - where: { - roleFk: { - inq: roles.map(role => { - return role.roleId; - }), - }, - } - }); + const userId = 9; + const {active, available} = await models.NotificationSubscription.getList(userId); + const notifications = await models.Notification.find({}); + const totalAvailable = notifications.length - active.length; - const result = await models.NotificationSubscription.getList(userId); - - expect(result.filter(notification => notification.active == true).length) - .toEqual(activeNotifications.length); - - expect(result.filter(notification => notification.active == false).length) - .toEqual(availableNotifications.length - activeNotifications.length); + expect(active.length).toEqual(2); + expect(available.length).toEqual(totalAvailable); }); }); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 77440ab9f..efee3bd28 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2790,7 +2790,9 @@ INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) (1, 9), (1, 1), (2, 1), + (3, 9), (4, 1), + (5, 9), (6, 9); INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`) From 4258015c07336fbb7182d8e86e8b5ebc2809a802 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 9 Nov 2023 08:04:38 +0100 Subject: [PATCH 24/30] refs #5870 feat:fixModel --- modules/worker/back/models/operator.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/modules/worker/back/models/operator.json b/modules/worker/back/models/operator.json index 2417078e1..6da3945fc 100644 --- a/modules/worker/back/models/operator.json +++ b/modules/worker/back/models/operator.json @@ -33,6 +33,16 @@ "type": "belongsTo", "model": "Sector", "foreignKey": "sectorFk" + }, + "train": { + "type": "belongsTo", + "model": "Train", + "foreignKey": "trainFk" + }, + "printer": { + "type": "belongsTo", + "model": "Printer", + "foreignKey": "labelerFk" } } } From 973eff4520c526bebad43daad9b4e97dd795792b Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 9 Nov 2023 09:05:56 +0100 Subject: [PATCH 25/30] refs #6415 fix. sql files --- db/changes/234201/00-packagingFkviews.sql | 2 ++ .../234601/00-ACLticketTrackingState.sql | 8 ----- .../00-claimViewerAcl.sql} | 10 +++--- db/changes/234601/00-claimViewweAcl.sql | 31 ----------------- db/changes/234601/00-clientAfterUpdate.sql | 20 ++--------- db/dump/fixtures.sql | 34 +++++++++---------- 6 files changed, 27 insertions(+), 78 deletions(-) rename db/changes/{233601/00-createClaimReader.sql => 234601/00-claimViewerAcl.sql} (86%) delete mode 100644 db/changes/234601/00-claimViewweAcl.sql diff --git a/db/changes/234201/00-packagingFkviews.sql b/db/changes/234201/00-packagingFkviews.sql index abc7dc004..49d41c26c 100644 --- a/db/changes/234201/00-packagingFkviews.sql +++ b/db/changes/234201/00-packagingFkviews.sql @@ -1,3 +1,5 @@ +CREATE SCHEMA IF NOT EXISTS `vn2008`; + CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn`.`awbVolume` diff --git a/db/changes/234601/00-ACLticketTrackingState.sql b/db/changes/234601/00-ACLticketTrackingState.sql index 0f7bd4f44..ca6dce0c9 100644 --- a/db/changes/234601/00-ACLticketTrackingState.sql +++ b/db/changes/234601/00-ACLticketTrackingState.sql @@ -2,11 +2,3 @@ UPDATE `salix`.`ACL` SET `property` = 'state', `model` = 'Ticket' WHERE `property` = 'changeState'; - -REVOKE INSERT, UPDATE, DELETE ON `vn`.`ticketTracking` FROM 'productionboss'@; -REVOKE INSERT, UPDATE, DELETE ON `vn`.`ticketTracking` FROM 'productionAssi'@; -REVOKE INSERT, UPDATE, DELETE ON `vn`.`ticketTracking` FROM 'hr'@; -REVOKE INSERT, UPDATE, DELETE ON `vn`.`ticketTracking` FROM 'salesPerson'@; -REVOKE INSERT, UPDATE, DELETE ON `vn`.`ticketTracking` FROM 'deliveryPerson'@; -REVOKE INSERT, UPDATE, DELETE ON `vn`.`ticketTracking` FROM 'employee'@; -REVOKE EXECUTE ON `vn`.`ticket_setState` FROM 'employee'@; diff --git a/db/changes/233601/00-createClaimReader.sql b/db/changes/234601/00-claimViewerAcl.sql similarity index 86% rename from db/changes/233601/00-createClaimReader.sql rename to db/changes/234601/00-claimViewerAcl.sql index e913c0ed9..17d8d4ce0 100644 --- a/db/changes/233601/00-createClaimReader.sql +++ b/db/changes/234601/00-claimViewerAcl.sql @@ -21,11 +21,11 @@ DELETE FROM `salix`.`ACL` 'getSummary' ); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) VALUES ('Claim','filter','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) VALUES ('Claim','find','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) VALUES ('Claim','findById','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) - VALUES ('Claim','getSummary','READ','ALLOW','ROLE','claimViewer'); \ No newline at end of file +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Claim','getSummary','READ','ALLOW','ROLE','claimViewer'); diff --git a/db/changes/234601/00-claimViewweAcl.sql b/db/changes/234601/00-claimViewweAcl.sql deleted file mode 100644 index e913c0ed9..000000000 --- a/db/changes/234601/00-claimViewweAcl.sql +++ /dev/null @@ -1,31 +0,0 @@ -INSERT INTO `account`.`role` (`name`, `description`, `hasLogin`) - VALUES ('claimViewer','Trabajadores que consulta las reclamaciones ',1); - -INSERT INTO `account`.`roleInherit` (`role`,`inheritsFrom`) - SELECT `r`.`id`, `r2`.`id` - FROM `account`.`role` `r` - JOIN `account`.`role` `r2` ON `r2`.`name` = 'claimViewer' - WHERE `r`.`name` IN ( - 'salesPerson', - 'buyer', - 'deliveryBoss', - 'handmadeBoss' - ); - -DELETE FROM `salix`.`ACL` - WHERE `model`= 'claim' - AND `property` IN ( - 'filter', - 'find', - 'findById', - 'getSummary' - ); - -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) - VALUES ('Claim','filter','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) - VALUES ('Claim','find','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) - VALUES ('Claim','findById','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) - VALUES ('Claim','getSummary','READ','ALLOW','ROLE','claimViewer'); \ No newline at end of file diff --git a/db/changes/234601/00-clientAfterUpdate.sql b/db/changes/234601/00-clientAfterUpdate.sql index 90ff5d52a..c6483813f 100644 --- a/db/changes/234601/00-clientAfterUpdate.sql +++ b/db/changes/234601/00-clientAfterUpdate.sql @@ -80,30 +80,16 @@ END$$ DELIMITER ; DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_beforeInsert` - BEFORE INSERT ON `client` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_AfterInsert` + AFTER INSERT ON `client` FOR EACH ROW BEGIN - IF NEW.credit NOT NULL AND NEW.credit THEN + IF NEW.credit IS NOT NULL AND NEW.credit THEN INSERT INTO clientCredit SET clientFk = NEW.id, workerFk = NEW.editorFk, amount = NEW.credit; END IF; - - SET NEW.editorFk = account.myUser_getId(); - - IF (NEW.phone <> '') THEN - CALL pbx.phone_isValid(NEW.phone); - END IF; - - IF (NEW.mobile <> '') THEN - CALL pbx.phone_isValid(NEW.mobile); - END IF; - - SET NEW.accountingAccount = 4300000000 + NEW.id; - - SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END$$ DELIMITER ; diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index d70279e7d..ae47a1eef 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -470,22 +470,22 @@ CREATE TEMPORARY TABLE tmp.address WHERE `defaultAddressFk` IS NULL; DROP TEMPORARY TABLE tmp.address; -INSERT INTO `vn`.`clientCredit`(`id`, `clientFk`, `workerFk`, `amount`, `created`) +INSERT INTO `vn`.`clientCredit`(`clientFk`, `workerFk`, `amount`, `created`) VALUES - (1 , 1101, 5, 300, DATE_ADD(util.VN_CURDATE(), INTERVAL -11 MONTH)), - (2 , 1101, 5, 900, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 MONTH)), - (3 , 1101, 5, 800, DATE_ADD(util.VN_CURDATE(), INTERVAL -9 MONTH)), - (4 , 1101, 5, 700, DATE_ADD(util.VN_CURDATE(), INTERVAL -8 MONTH)), - (5 , 1101, 5, 600, DATE_ADD(util.VN_CURDATE(), INTERVAL -7 MONTH)), - (6 , 1101, 5, 500, DATE_ADD(util.VN_CURDATE(), INTERVAL -6 MONTH)), - (7 , 1101, 5, 400, DATE_ADD(util.VN_CURDATE(), INTERVAL -5 MONTH)), - (8 , 1101, 9, 300, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)), - (9 , 1101, 9, 200, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)), - (10, 1101, 9, 100, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), - (11, 1101, 9, 50 , DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), - (12, 1102, 9, 800, util.VN_CURDATE()), - (14, 1104, 9, 90 , util.VN_CURDATE()), - (15, 1105, 9, 90 , util.VN_CURDATE()); + (1101, 5, 300, DATE_ADD(util.VN_CURDATE(), INTERVAL -11 MONTH)), + (1101, 5, 900, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 MONTH)), + (1101, 5, 800, DATE_ADD(util.VN_CURDATE(), INTERVAL -9 MONTH)), + (1101, 5, 700, DATE_ADD(util.VN_CURDATE(), INTERVAL -8 MONTH)), + (1101, 5, 600, DATE_ADD(util.VN_CURDATE(), INTERVAL -7 MONTH)), + (1101, 5, 500, DATE_ADD(util.VN_CURDATE(), INTERVAL -6 MONTH)), + (1101, 5, 400, DATE_ADD(util.VN_CURDATE(), INTERVAL -5 MONTH)), + (1101, 9, 300, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)), + (1101, 9, 200, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)), + (1101, 9, 100, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), + (1101, 9, 50 , DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), + (1102, 9, 800, util.VN_CURDATE()), + (1104, 9, 90 , util.VN_CURDATE()), + (1105, 9, 90 , util.VN_CURDATE()); INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) VALUES @@ -2758,7 +2758,7 @@ INSERT INTO `vn`.`sectorCollectionSaleGroup` (`sectorCollectionFk`, `saleGroupFk VALUES (1, 1); -INSERT INTO `vn`.`workerTimeControlConfig` (`id`, `dayBreak`, `dayBreakDriver`, `shortWeekBreak`, `longWeekBreak`, `weekScope`, `mailPass`, `mailHost`, `mailSuccessFolder`, `mailErrorFolder`, `mailUser`, `minHoursToBreak`, `breakHours`, `hoursCompleteWeek`, `startNightlyHours`, `endNightlyHours`, `maxTimePerDay`, `breakTime`, `timeToBreakTime`, `dayMaxTime`, `shortWeekDays`, `longWeekDays`, `teleworkingStart`, `teleworkingStartBreakTime`, `maxTimeToBreak`, `maxWorkShortCycle`, `maxWorkLongCycle`) +INSERT INTO `vn`.`workerTimeControlConfig` (`id`, `dayBreak`, `dayBreakDriver`, `shortWeekBreak`, `longWeekBreak`, `weekScope`, `mailPass`, `mailHost`, `mailSuccessFolder`, `mailErrorFolder`, `mailUser`, `minHoursToBreak`, `breakHours`, `hoursCompleteWeek`, `startNightlyHours`, `endNightlyHours`, `maxTimePerDay`, `breakTime`, `timeToBreakTime`, `dayMaxTime`, `shortWeekDays`, `longWeekDays`, `teleworkingStart`, `teleworkingStartBreakTime`, `maxTimeToBreak`, `maxWorkShortCycle`, `maxWorkLongCycle`) VALUES (1, 43200, 32400, 129600, 259200, 1080000, '', 'imap.verdnatura.es', 'Leidos.exito', 'Leidos.error', 'timeControl', 5.00, 0.33, 40, '22:00:00', '06:00:00', 72000, 1200, 18000, 72000, 6, 13, 28800, 32400, 3600, 561600, 950400); @@ -2986,4 +2986,4 @@ INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) VALUES (1, 'Error in VAT calculation'), (2, 'Error in sales details'), - (3, 'Error in customer data'); \ No newline at end of file + (3, 'Error in customer data'); From dbe684441950b10151e7d9085e4024200571e397 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 9 Nov 2023 09:31:32 +0100 Subject: [PATCH 26/30] refs #6415 feat: init version 23.48 --- CHANGELOG.md | 6 ++++++ db/changes/234801/.gitkeep | 0 package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 db/changes/234801/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index 29d270a3e..30afaa69b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2348.01] - 2023-11-30 + +### Added +### Changed +### Fixed + ## [2346.01] - 2023-11-16 ### Added diff --git a/db/changes/234801/.gitkeep b/db/changes/234801/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json index 5bf7a2cb1..b66279ae3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.46.01", + "version": "23.48.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.46.01", + "version": "23.48.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index b1539f9a0..04fcb008b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.46.01", + "version": "23.48.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From a0c4573f4d09f16e21e8d043a04bea17d4092d1d Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 9 Nov 2023 09:34:37 +0100 Subject: [PATCH 27/30] refs #4797 fix: correct sql folder --- db/changes/{234601 => 234801}/00-notificationSubscription.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234601 => 234801}/00-notificationSubscription.sql (100%) diff --git a/db/changes/234601/00-notificationSubscription.sql b/db/changes/234801/00-notificationSubscription.sql similarity index 100% rename from db/changes/234601/00-notificationSubscription.sql rename to db/changes/234801/00-notificationSubscription.sql From 69255fe2fcacd1dc716b26dcf0c60b8face6882d Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 10 Nov 2023 10:58:58 +0100 Subject: [PATCH 28/30] refs #6014 feat(execute): use user_hasRoutinePriv. feat(execute): split in executeProc & executeFunc --- .vscode/settings.json | 3 +- db/changes/234201/00-ACL_executeRoutine.sql | 3 - db/changes/234801/00-ACL_executeRoutine.sql | 4 + db/dump/structure.sql | 84 ++++++++++++++ .../common/methods/application/execute.js | 34 ++++++ .../common/methods/application/executeFunc.js | 38 +++++++ .../common/methods/application/executeProc.js | 36 ++++++ .../methods/application/executeRoutine.js | 100 ----------------- ...executeRoutine.spec.js => execute.spec.js} | 103 +++++++++++------- loopback/common/models/application.js | 4 +- 10 files changed, 265 insertions(+), 144 deletions(-) delete mode 100644 db/changes/234201/00-ACL_executeRoutine.sql create mode 100644 db/changes/234801/00-ACL_executeRoutine.sql create mode 100644 loopback/common/methods/application/execute.js create mode 100644 loopback/common/methods/application/executeFunc.js create mode 100644 loopback/common/methods/application/executeProc.js delete mode 100644 loopback/common/methods/application/executeRoutine.js rename loopback/common/methods/application/spec/{executeRoutine.spec.js => execute.spec.js} (51%) diff --git a/.vscode/settings.json b/.vscode/settings.json index 9ed1c8fc2..899dfc788 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -12,6 +12,7 @@ "editor.defaultFormatter": "dbaeumer.vscode-eslint" }, "cSpell.words": [ - "salix" + "salix", + "fdescribe" ] } diff --git a/db/changes/234201/00-ACL_executeRoutine.sql b/db/changes/234201/00-ACL_executeRoutine.sql deleted file mode 100644 index dd112171a..000000000 --- a/db/changes/234201/00-ACL_executeRoutine.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) - VALUES - ('Application', 'executeRoutine', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/234801/00-ACL_executeRoutine.sql b/db/changes/234801/00-ACL_executeRoutine.sql new file mode 100644 index 000000000..cfe7018e9 --- /dev/null +++ b/db/changes/234801/00-ACL_executeRoutine.sql @@ -0,0 +1,4 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('Application', 'executeProc', '*', 'ALLOW', 'ROLE', 'employee'), + ('Application', 'executeFunc', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/dump/structure.sql b/db/dump/structure.sql index b242821fc..a8280dc1d 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -2352,6 +2352,90 @@ BEGIN END IF; END ;; DELIMITER ; + + +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `account`.`user_hasRoutinePriv`(vType ENUM('PROCEDURE', 'FUNCTION'), + vChain VARCHAR(100), + vUserFk INT +) RETURNS tinyint(1) + READS SQL DATA +BEGIN + +/** + * Search if the user has privileges on routines. + * + * @param vType procedure or function + * @param vChain string passed with this syntax dbName.tableName + * @param vUserFk user to ckeck + * @return vHasPrivilege + */ + DECLARE vHasPrivilege BOOL DEFAULT FALSE; + DECLARE vDb VARCHAR(50); + DECLARE vObject VARCHAR(50); + DECLARE vChainExists BOOL; + DECLARE vExecutePriv INT DEFAULT 262144; + -- 262144 = CONV(1000000000000000000, 2, 10) + -- 1000000000000000000 execution permission expressed in binary base + + SET vDb = SUBSTRING_INDEX(vChain, '.', 1); + SET vChain = SUBSTRING(vChain, LENGTH(vDb) + 2); + SET vObject = SUBSTRING_INDEX(vChain, '.', 1); + + SELECT COUNT(*) INTO vChainExists + FROM mysql.proc + WHERE db = vDb + AND `name` = vObject + AND `type` = vType + LIMIT 1; + + IF NOT vChainExists THEN + RETURN FALSE; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tRole; + CREATE TEMPORARY TABLE tRole + (INDEX (`name`)) + ENGINE = MEMORY + SELECT r.`name` + FROM user u + JOIN roleRole rr ON rr.role = u.role + JOIN `role` r ON r.id = rr.inheritsFrom + WHERE u.id = vUserFk; + + SELECT TRUE INTO vHasPrivilege + FROM mysql.global_priv gp + JOIN tRole tr ON tr.name = gp.`User` + OR CONCAT('$', tr.name) = gp.`User` + WHERE JSON_VALUE(gp.Priv, '$.access') >= vExecutePriv + AND gp.Host = '' + LIMIT 1; + + IF NOT vHasPrivilege THEN + SELECT TRUE INTO vHasPrivilege + FROM mysql.db db + JOIN tRole tr ON tr.name = db.`User` + WHERE db.Db = vDb + AND db.Execute_priv = 'Y'; + END IF; + + IF NOT vHasPrivilege THEN + SELECT TRUE INTO vHasPrivilege + FROM mysql.procs_priv pp + JOIN tRole tr ON tr.name = pp.`User` + WHERE pp.Db = vDb + AND pp.Routine_name = vObject + AND pp.Routine_type = vType + AND pp.Proc_priv = 'Execute' + LIMIT 1; + END IF; + + DROP TEMPORARY TABLE tRole; + RETURN vHasPrivilege; +END ;; +DELIMITER ; + + /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; diff --git a/loopback/common/methods/application/execute.js b/loopback/common/methods/application/execute.js new file mode 100644 index 000000000..7a24df0d4 --- /dev/null +++ b/loopback/common/methods/application/execute.js @@ -0,0 +1,34 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.execute = async(ctx, routine, params, schema, type, options) => { + const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + let caller = 'CALL'; + + params = params ?? []; + schema = schema ?? 'vn'; + type = type ?? 'procedure'; + + const myOptions = {userId: ctx.req.accessToken.userId}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const chain = `${schema}.${routine}`; + const [canExecute] = await models.ProcsPriv.rawSql( + 'SELECT account.user_hasRoutinePriv(?,?,?)', + [type.toUpperCase(), chain, userId], + myOptions); + if (!Object.values(canExecute)[0]) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); + + const isFunction = type == 'function'; + let argString = params.map(() => '?').join(','); + + if (isFunction) + caller = 'SELECT'; + const query = `${caller} ${chain}(${argString})`; + + const [response] = await models.ProcsPriv.rawSql(query, params, myOptions); + return response; + }; +}; diff --git a/loopback/common/methods/application/executeFunc.js b/loopback/common/methods/application/executeFunc.js new file mode 100644 index 000000000..0a90e8639 --- /dev/null +++ b/loopback/common/methods/application/executeFunc.js @@ -0,0 +1,38 @@ +module.exports = Self => { + Self.remoteMethodCtx('executeFunc', { + description: 'Return result of function', + accessType: '*', + accepts: [ + { + arg: 'routine', + type: 'string', + description: 'The routine name', + required: true, + http: {source: 'path'} + }, + { + arg: 'params', + type: ['any'], + description: 'The params array', + }, + { + arg: 'schema', + type: 'string', + description: 'The routine schema', + } + ], + returns: { + type: 'any', + root: true + }, + http: { + path: `/:routine/execute-func`, + verb: 'POST' + } + }); + + Self.executeFunc = async(ctx, routine, params, schema, options) => { + const response = await Self.execute(ctx, routine, params, schema, 'function', options); + return Object.values(response)[0]; + }; +}; diff --git a/loopback/common/methods/application/executeProc.js b/loopback/common/methods/application/executeProc.js new file mode 100644 index 000000000..635944eb7 --- /dev/null +++ b/loopback/common/methods/application/executeProc.js @@ -0,0 +1,36 @@ +module.exports = Self => { + Self.remoteMethodCtx('executeProc', { + description: 'Return result of procedure', + accessType: '*', + accepts: [ + { + arg: 'routine', + type: 'string', + description: 'The routine name', + required: true, + http: {source: 'path'} + }, + { + arg: 'params', + type: ['any'], + description: 'The params array', + }, + { + arg: 'schema', + type: 'string', + description: 'The routine schema', + } + ], + returns: { + type: 'any', + root: true + }, + http: { + path: `/:routine/execute-proc`, + verb: 'POST' + } + }); + + Self.executeProc = async(ctx, routine, params, schema, options) => + Self.execute(ctx, routine, params, schema, 'procedure', options); +}; diff --git a/loopback/common/methods/application/executeRoutine.js b/loopback/common/methods/application/executeRoutine.js deleted file mode 100644 index eed34b344..000000000 --- a/loopback/common/methods/application/executeRoutine.js +++ /dev/null @@ -1,100 +0,0 @@ -const UserError = require('vn-loopback/util/user-error'); - -module.exports = Self => { - Self.remoteMethodCtx('executeRoutine', { - description: 'Return the routes by worker', - accessType: '*', - accepts: [ - { - arg: 'routine', - type: 'string', - description: 'The routine name', - required: true, - http: {source: 'path'} - }, - { - arg: 'params', - type: ['any'], - description: 'The params array', - }, - { - arg: 'schema', - type: 'string', - description: 'The routine schema', - }, - { - arg: 'type', - type: 'string', - description: 'The routine type', - } - ], - returns: { - type: 'any', - root: true - }, - http: { - path: `/:routine/execute-routine`, - verb: 'POST' - } - }); - - Self.executeRoutine = async(ctx, routine, params, schema, type, options) => { - const userId = ctx.req.accessToken.userId; - const models = Self.app.models; - const isFunction = type == 'function'; - params = params ?? []; - schema = schema ?? 'vn'; - type = type ?? 'procedure'; - let caller = 'CALL'; - - if (isFunction) - caller = 'SELECT'; - - const myOptions = {userId: ctx.req.accessToken.userId}; - if (typeof options == 'object') - Object.assign(myOptions, options); - - const user = await models.VnUser.findById(userId, { - fields: ['id', 'roleFk'], - include: { - relation: 'role', - scope: { - fields: ['id', 'name'] - } - } - }); - - const inherits = await models.RoleRole.find({ - include: { - relation: 'inherits', - scope: { - fields: ['id', 'name'] - } - }, - where: { - role: user.role().id - } - }); - - const roles = inherits.map(inherit => inherit.inherits().name); - - const canExecute = await models.ProcsPriv.findOne({ - where: { - schema, - type: type.toUpperCase(), - name: routine, - host: process.env.NODE_ENV ? '' : '%', - role: {inq: roles} - } - }); - - if (!canExecute) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); - - let argString = params.map(() => '?').join(','); - - const query = `${caller} ${schema}.${routine}(${argString})`; - - const [response] = await models.ProcsPriv.rawSql(query, params, myOptions); - return isFunction ? Object.values(response)[0] : response; - }; -}; diff --git a/loopback/common/methods/application/spec/executeRoutine.spec.js b/loopback/common/methods/application/spec/execute.spec.js similarity index 51% rename from loopback/common/methods/application/spec/executeRoutine.spec.js rename to loopback/common/methods/application/spec/execute.spec.js index 150c5d416..26e648531 100644 --- a/loopback/common/methods/application/spec/executeRoutine.spec.js +++ b/loopback/common/methods/application/spec/execute.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -describe('Application executeRoutine()', () => { +describe('Application execute()/executeProc()/executeFunc()', () => { const userWithoutPrivileges = 1; const userWithPrivileges = 9; const userWithInheritedPrivileges = 120; @@ -48,7 +48,7 @@ describe('Application executeRoutine()', () => { try { const options = {transaction: tx}; - await models.Application.executeRoutine( + await models.Application.execute( ctx, 'myProcedure', [1], @@ -71,7 +71,7 @@ describe('Application executeRoutine()', () => { try { const options = {transaction: tx}; - const response = await models.Application.executeRoutine( + const response = await models.Application.execute( ctx, 'myProcedure', [1], @@ -90,49 +90,74 @@ describe('Application executeRoutine()', () => { } }); - it('should execute function and get data', async() => { - const ctx = getCtx(userWithPrivileges); - try { - const options = {transaction: tx}; + describe('Application executeProc()', () => { + it('should execute procedure and get data (executeProc)', async() => { + const ctx = getCtx(userWithPrivileges); + try { + const options = {transaction: tx}; - const response = await models.Application.executeRoutine( - ctx, - 'myFunction', - [1], - 'bs', - 'function', - options - ); + const response = await models.Application.executeProc( + ctx, + 'myProcedure', + [1], + null, + options + ); - expect(response).toEqual(1); + expect(response.length).toEqual(2); + expect(response[0].myParam).toEqual(1); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); - it('should execute function and get data with user with inherited privileges', async() => { - const ctx = getCtx(userWithInheritedPrivileges); - try { - const options = {transaction: tx}; + describe('Application executeFunc()', () => { + it('should execute function and get data', async() => { + const ctx = getCtx(userWithPrivileges); + try { + const options = {transaction: tx}; - const response = await models.Application.executeRoutine( - ctx, - 'myFunction', - [1], - 'bs', - 'function', - options - ); + const response = await models.Application.executeFunc( + ctx, + 'myFunction', + [1], + 'bs', + options + ); - expect(response).toEqual(1); + expect(response).toEqual(1); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should execute function and get data with user with inherited privileges', async() => { + const ctx = getCtx(userWithInheritedPrivileges); + try { + const options = {transaction: tx}; + + const response = await models.Application.executeFunc( + ctx, + 'myFunction', + [1], + 'bs', + options + ); + + expect(response).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); }); diff --git a/loopback/common/models/application.js b/loopback/common/models/application.js index b9e639b1b..ac8ae78f0 100644 --- a/loopback/common/models/application.js +++ b/loopback/common/models/application.js @@ -2,5 +2,7 @@ module.exports = function(Self) { require('../methods/application/status')(Self); require('../methods/application/post')(Self); - require('../methods/application/executeRoutine')(Self); + require('../methods/application/execute')(Self); + require('../methods/application/executeProc')(Self); + require('../methods/application/executeFunc')(Self); }; From 59d2da24eb6d5329b0700453abaabb3215105f79 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 13 Nov 2023 09:36:20 +0100 Subject: [PATCH 29/30] refs #6014 refactor(execute): split code --- .../common/methods/application/execute.js | 19 +++++++------------ .../common/methods/application/executeFunc.js | 6 +++++- .../common/methods/application/executeProc.js | 9 +++++++-- .../methods/application/spec/execute.spec.js | 8 ++------ 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/loopback/common/methods/application/execute.js b/loopback/common/methods/application/execute.js index 7a24df0d4..c0475dbfe 100644 --- a/loopback/common/methods/application/execute.js +++ b/loopback/common/methods/application/execute.js @@ -1,32 +1,27 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.execute = async(ctx, routine, params, schema, type, options) => { + Self.execute = async(ctx, query, params, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; - let caller = 'CALL'; - params = params ?? []; - schema = schema ?? 'vn'; - type = type ?? 'procedure'; const myOptions = {userId: ctx.req.accessToken.userId}; if (typeof options == 'object') Object.assign(myOptions, options); - const chain = `${schema}.${routine}`; + let [caller, chain] = query.split(' '); + if (!chain.includes('.')) chain = 'vn.' + chain; + const [canExecute] = await models.ProcsPriv.rawSql( 'SELECT account.user_hasRoutinePriv(?,?,?)', - [type.toUpperCase(), chain, userId], + [caller == 'CALL' ? 'PROCEDURE' : 'FUNCTION', chain, userId], myOptions); + if (!Object.values(canExecute)[0]) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); - const isFunction = type == 'function'; let argString = params.map(() => '?').join(','); - - if (isFunction) - caller = 'SELECT'; - const query = `${caller} ${chain}(${argString})`; + query = `${query}(${argString})`; const [response] = await models.ProcsPriv.rawSql(query, params, myOptions); return response; diff --git a/loopback/common/methods/application/executeFunc.js b/loopback/common/methods/application/executeFunc.js index 0a90e8639..49e2cdc21 100644 --- a/loopback/common/methods/application/executeFunc.js +++ b/loopback/common/methods/application/executeFunc.js @@ -32,7 +32,11 @@ module.exports = Self => { }); Self.executeFunc = async(ctx, routine, params, schema, options) => { - const response = await Self.execute(ctx, routine, params, schema, 'function', options); + if (schema) + routine = schema + '.' + routine; + + const query = `SELECT ${routine}`; + const response = await Self.execute(ctx, query, params, options); return Object.values(response)[0]; }; }; diff --git a/loopback/common/methods/application/executeProc.js b/loopback/common/methods/application/executeProc.js index 635944eb7..524831e86 100644 --- a/loopback/common/methods/application/executeProc.js +++ b/loopback/common/methods/application/executeProc.js @@ -31,6 +31,11 @@ module.exports = Self => { } }); - Self.executeProc = async(ctx, routine, params, schema, options) => - Self.execute(ctx, routine, params, schema, 'procedure', options); + Self.executeProc = async(ctx, routine, params, schema, options) => { + if (schema) + routine = schema + '.' + routine; + + const query = `CALL ${routine}`; + return Self.execute(ctx, query, params, options); + }; }; diff --git a/loopback/common/methods/application/spec/execute.spec.js b/loopback/common/methods/application/spec/execute.spec.js index 26e648531..4c5727984 100644 --- a/loopback/common/methods/application/spec/execute.spec.js +++ b/loopback/common/methods/application/spec/execute.spec.js @@ -50,10 +50,8 @@ describe('Application execute()/executeProc()/executeFunc()', () => { await models.Application.execute( ctx, - 'myProcedure', + 'CALL myProcedure', [1], - null, - null, options ); @@ -73,10 +71,8 @@ describe('Application execute()/executeProc()/executeFunc()', () => { const response = await models.Application.execute( ctx, - 'myProcedure', + 'CALL myProcedure', [1], - null, - null, options ); From cce61ae8ccf9b7d747a0f934a187b9adcfb8bc59 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 14 Nov 2023 09:17:46 +0100 Subject: [PATCH 30/30] refs #6014 refactor(execute): schema required --- .../common/methods/application/execute.js | 12 +++++------ .../common/methods/application/executeFunc.js | 19 +++++++++--------- .../common/methods/application/executeProc.js | 20 +++++++++---------- .../methods/application/spec/execute.spec.js | 12 ++++++----- 4 files changed, 30 insertions(+), 33 deletions(-) diff --git a/loopback/common/methods/application/execute.js b/loopback/common/methods/application/execute.js index c0475dbfe..7995b12e3 100644 --- a/loopback/common/methods/application/execute.js +++ b/loopback/common/methods/application/execute.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.execute = async(ctx, query, params, options) => { + Self.execute = async(ctx, type, query, params, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; params = params ?? []; @@ -10,20 +10,18 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - let [caller, chain] = query.split(' '); - if (!chain.includes('.')) chain = 'vn.' + chain; + const chain = query.split(' ')[1]; const [canExecute] = await models.ProcsPriv.rawSql( 'SELECT account.user_hasRoutinePriv(?,?,?)', - [caller == 'CALL' ? 'PROCEDURE' : 'FUNCTION', chain, userId], + [type, chain, userId], myOptions); if (!Object.values(canExecute)[0]) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); - let argString = params.map(() => '?').join(','); - query = `${query}(${argString})`; + const argString = params.map(() => '?').join(','); - const [response] = await models.ProcsPriv.rawSql(query, params, myOptions); + const [response] = await models.ProcsPriv.rawSql(query + `(${argString})`, params, myOptions); return response; }; }; diff --git a/loopback/common/methods/application/executeFunc.js b/loopback/common/methods/application/executeFunc.js index 49e2cdc21..f915f4482 100644 --- a/loopback/common/methods/application/executeFunc.js +++ b/loopback/common/methods/application/executeFunc.js @@ -10,16 +10,17 @@ module.exports = Self => { required: true, http: {source: 'path'} }, + { + arg: 'schema', + type: 'string', + description: 'The routine schema', + required: true, + }, { arg: 'params', type: ['any'], description: 'The params array', }, - { - arg: 'schema', - type: 'string', - description: 'The routine schema', - } ], returns: { type: 'any', @@ -31,12 +32,10 @@ module.exports = Self => { } }); - Self.executeFunc = async(ctx, routine, params, schema, options) => { - if (schema) - routine = schema + '.' + routine; + Self.executeFunc = async(ctx, routine, schema, params, options) => { + const query = `SELECT ${schema}.${routine}`; - const query = `SELECT ${routine}`; - const response = await Self.execute(ctx, query, params, options); + const response = await Self.execute(ctx, 'FUNCTION', query, params, options); return Object.values(response)[0]; }; }; diff --git a/loopback/common/methods/application/executeProc.js b/loopback/common/methods/application/executeProc.js index 524831e86..5859611d9 100644 --- a/loopback/common/methods/application/executeProc.js +++ b/loopback/common/methods/application/executeProc.js @@ -10,16 +10,17 @@ module.exports = Self => { required: true, http: {source: 'path'} }, + { + arg: 'schema', + type: 'string', + description: 'The routine schema', + required: true, + }, { arg: 'params', type: ['any'], description: 'The params array', }, - { - arg: 'schema', - type: 'string', - description: 'The routine schema', - } ], returns: { type: 'any', @@ -31,11 +32,8 @@ module.exports = Self => { } }); - Self.executeProc = async(ctx, routine, params, schema, options) => { - if (schema) - routine = schema + '.' + routine; - - const query = `CALL ${routine}`; - return Self.execute(ctx, query, params, options); + Self.executeProc = async(ctx, routine, schema, params, options) => { + const query = `CALL ${schema}.${routine}`; + return Self.execute(ctx, 'PROCEDURE', query, params, options); }; }; diff --git a/loopback/common/methods/application/spec/execute.spec.js b/loopback/common/methods/application/spec/execute.spec.js index 4c5727984..1a0a8ace9 100644 --- a/loopback/common/methods/application/spec/execute.spec.js +++ b/loopback/common/methods/application/spec/execute.spec.js @@ -50,7 +50,8 @@ describe('Application execute()/executeProc()/executeFunc()', () => { await models.Application.execute( ctx, - 'CALL myProcedure', + 'PROCEDURE', + 'CALL vn.myProcedure', [1], options ); @@ -71,7 +72,8 @@ describe('Application execute()/executeProc()/executeFunc()', () => { const response = await models.Application.execute( ctx, - 'CALL myProcedure', + 'PROCEDURE', + 'CALL vn.myProcedure', [1], options ); @@ -95,8 +97,8 @@ describe('Application execute()/executeProc()/executeFunc()', () => { const response = await models.Application.executeProc( ctx, 'myProcedure', + 'vn', [1], - null, options ); @@ -120,8 +122,8 @@ describe('Application execute()/executeProc()/executeFunc()', () => { const response = await models.Application.executeFunc( ctx, 'myFunction', - [1], 'bs', + [1], options ); @@ -142,8 +144,8 @@ describe('Application execute()/executeProc()/executeFunc()', () => { const response = await models.Application.executeFunc( ctx, 'myFunction', - [1], 'bs', + [1], options );